Skip to main content

voxel_framework/mobs/
mod.rs

1//! Simple mob (enemy entity) system for voxel worlds.
2//!
3//! Provides a complete AI loop — patrol → chase → attack — with voxel
4//! collision, gravity, player damage, and death events. Mobs are represented
5//! as capsule-shaped entities that collide with the chunk world using
6//! [`crate::world::resolve_capsule_collision`].
7//!
8//! # Quick start
9//!
10//! ```no_run
11//! use bevy::prelude::*;
12//! use voxel_framework::VoxelPlugin;
13//! use voxel_framework::mobs::{MobPlugin, MobConfig, spawn_mob};
14//! use voxel_framework::voxel::DefaultTerrainVoxel;
15//!
16//! App::new()
17//!     .add_plugins(DefaultPlugins)
18//!     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
19//!     .add_plugins(MobPlugin::<DefaultTerrainVoxel>::new())
20//!     .add_systems(Startup, |
21//!         mut commands: Commands,
22//!         mut meshes: ResMut<Assets<Mesh>>,
23//!         mut materials: ResMut<Assets<StandardMaterial>>,
24//!     | {
25//!         spawn_mob(
26//!             Vec3::new(8.0, 70.0, 8.0),
27//!             MobConfig::default(),
28//!             &mut commands, &mut meshes, &mut materials,
29//!         );
30//!     })
31//!     .run();
32//! ```
33
34use std::collections::BTreeMap;
35
36use bevy::prelude::*;
37
38use crate::chunk::{Chunk, world_to_chunk_coord};
39use crate::player::{Player, PlayerHealth};
40use crate::voxel::VoxelType;
41use crate::world::ChunkManager;
42use crate::world::collision::resolve_capsule_collision;
43
44mod spawner;
45
46pub use spawner::{
47    DAY_END, DAY_START, DespawnOutsideWindow, MobSpawnRules, MobSpawnerPlugin, SpawnContext,
48    SpawnPlacement, SpawnRing, SpawnRule, SpawnZone, TimeWindow,
49};
50
51// ─── Constants ────────────────────────────────────────────────────────────────
52
53/// Half-height of the mob capsule along the Y axis (world units).
54pub const MOB_HALF_HEIGHT: f32 = 0.5;
55/// Radius of the mob capsule (world units).
56pub const MOB_RADIUS: f32 = 0.35;
57
58// ─── Components ───────────────────────────────────────────────────────────────
59
60/// AI behaviour state for a [`Mob`] entity.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum MobAiState {
63    /// Wanders randomly near the spawn point.
64    Patrol,
65    /// Has detected the player; moves toward them.
66    Chase,
67    /// Close enough to strike; swings at the player.
68    Attack,
69}
70
71/// Core mob component — attached to every mob entity.
72#[derive(Component)]
73pub struct Mob {
74    /// Current hit points. Mob is dead when `<= 0.0`.
75    pub health: f32,
76    /// Current AI mode.
77    pub ai_state: MobAiState,
78    /// Horizontal velocity accumulated this frame (m/s).
79    pub velocity: Vec3,
80    /// Vertical velocity for gravity/jumping (m/s, Y component only).
81    pub vertical_velocity: f32,
82    /// Whether the mob is resting on solid ground.
83    pub on_ground: bool,
84    /// Countdown until the next attack swing (seconds).
85    pub attack_cooldown: f32,
86    /// Accumulated time for patrol direction changes.
87    pub patrol_timer: f32,
88    /// Current patrol walk direction (horizontal, unnormalised may be zero).
89    pub patrol_dir: Vec3,
90    /// World-space position where this mob was spawned (patrol centre).
91    pub home_position: Vec3,
92}
93
94// ─── Config ───────────────────────────────────────────────────────────────────
95
96/// Per-mob-type configuration.
97///
98/// Insert as many [`MobConfig`] instances as you need — one per mob variety.
99/// Pass one to [`spawn_mob`] when spawning an entity.
100#[derive(Clone, Debug)]
101pub struct MobConfig {
102    /// Initial (and maximum) health points.
103    pub max_health: f32,
104    /// Horizontal movement speed while chasing (m/s).
105    pub chase_speed: f32,
106    /// Horizontal movement speed while patrolling (m/s).
107    pub patrol_speed: f32,
108    /// Distance at which the mob detects the player.
109    pub detection_radius: f32,
110    /// Distance at which melee attacks are triggered.
111    pub attack_range: f32,
112    /// Damage dealt per attack swing.
113    pub attack_damage: f32,
114    /// Minimum seconds between attacks.
115    pub attack_cooldown: f32,
116    /// How far the mob wanders from its spawn point while patrolling.
117    pub patrol_radius: f32,
118    /// Distance from the player at which the mob despawns (unloads).
119    pub despawn_distance: f32,
120    /// Gravity acceleration (m/s²). Positive = downward.
121    ///
122    /// `Some(g)` enables grounded behaviour: the mob accelerates downward each
123    /// frame and snaps to the ground via capsule collision (Minecraft-style).
124    /// `None` disables gravity and ground-snapping entirely so the mob floats
125    /// freely in 3D — useful for zero-g / space games where mobs should drift
126    /// alongside a [`crate::player::PlayerMode::FreeFlightSixDof`] player.
127    ///
128    /// In zero-g mode the mob's `vertical_velocity` field stays at `0.0`;
129    /// only horizontal AI velocity drives motion.
130    pub gravity: Option<f32>,
131    /// RGB color used for the default box mesh.
132    pub color: Color,
133}
134
135impl Default for MobConfig {
136    fn default() -> Self {
137        Self {
138            max_health: 20.0,
139            chase_speed: 3.5,
140            patrol_speed: 1.2,
141            detection_radius: 12.0,
142            attack_range: 1.5,
143            attack_damage: 4.0,
144            attack_cooldown: 1.2,
145            patrol_radius: 6.0,
146            despawn_distance: 64.0,
147            gravity: Some(20.0),
148            color: Color::srgb(0.6, 0.1, 0.1),
149        }
150    }
151}
152
153// ─── Events ───────────────────────────────────────────────────────────────────
154
155/// Emitted when a mob's health drops to zero or below.
156///
157/// Systems that handle loot drops or achievements should read this message.
158#[derive(bevy::ecs::message::Message, Debug, Clone)]
159pub struct MobDied {
160    /// World-space position of the mob at the moment of death.
161    pub position: Vec3,
162}
163
164// ─── Spawn ────────────────────────────────────────────────────────────────────
165
166/// Spawns a mob entity at `position` using the given [`MobConfig`].
167///
168/// The mob is rendered as a colored box mesh (1×1×1 voxel).  For custom
169/// visuals, spawn the mob yourself and attach the [`Mob`] component instead.
170pub fn spawn_mob(
171    position: Vec3,
172    config: MobConfig,
173    commands: &mut Commands,
174    meshes: &mut Assets<Mesh>,
175    materials: &mut Assets<StandardMaterial>,
176) -> Entity {
177    let mesh = meshes.add(Cuboid::new(
178        MOB_RADIUS * 2.0,
179        (MOB_HALF_HEIGHT + MOB_RADIUS) * 2.0,
180        MOB_RADIUS * 2.0,
181    ));
182    let material = materials.add(StandardMaterial {
183        base_color: config.color,
184        ..default()
185    });
186    commands
187        .spawn((
188            Mob {
189                health: config.max_health,
190                ai_state: MobAiState::Patrol,
191                velocity: Vec3::ZERO,
192                vertical_velocity: 0.0,
193                on_ground: false,
194                attack_cooldown: 0.0,
195                patrol_timer: 0.0,
196                patrol_dir: Vec3::ZERO,
197                home_position: position,
198            },
199            MobConfigComponent(config),
200            Transform::from_translation(position),
201            Visibility::default(),
202            Mesh3d(mesh),
203            MeshMaterial3d(material),
204        ))
205        .id()
206}
207
208/// Internal component that stores the [`MobConfig`] on the entity so systems
209/// can read it without a separate resource lookup.
210#[derive(Component)]
211pub struct MobConfigComponent(pub MobConfig);
212
213// ─── Mob kinds ────────────────────────────────────────────────────────────────
214
215/// Named mob type, such as `"slime"` or `"night_slime"`.
216///
217/// Mobs spawned through [`spawn_mob_kind`] carry this component so games and
218/// spawners can count or filter mobs by type. Mobs spawned with the plain
219/// [`spawn_mob`] have no kind.
220#[derive(Component, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
221pub struct MobKind(String);
222
223impl MobKind {
224    /// Creates a kind from its name.
225    pub fn new(name: impl Into<String>) -> Self {
226        Self(name.into())
227    }
228
229    /// Returns the kind's name.
230    pub fn as_str(&self) -> &str {
231        &self.0
232    }
233}
234
235impl From<&str> for MobKind {
236    fn from(name: &str) -> Self {
237        Self::new(name)
238    }
239}
240
241impl From<String> for MobKind {
242    fn from(name: String) -> Self {
243        Self::new(name)
244    }
245}
246
247impl AsRef<str> for MobKind {
248    fn as_ref(&self) -> &str {
249        &self.0
250    }
251}
252
253impl std::fmt::Display for MobKind {
254    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255        f.write_str(&self.0)
256    }
257}
258
259/// Error returned by [`MobRegistry::register_variant`].
260#[derive(Clone, Debug, PartialEq, Eq)]
261pub enum MobRegistryError {
262    /// The base kind a variant derives from is not registered.
263    UnknownBase(MobKind),
264}
265
266impl std::fmt::Display for MobRegistryError {
267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        match self {
269            Self::UnknownBase(kind) => write!(f, "unknown base mob kind `{kind}`"),
270        }
271    }
272}
273
274impl std::error::Error for MobRegistryError {}
275
276/// Registry of named mob types, each backed by a [`MobConfig`].
277///
278/// Every mob type is a configuration of the same base mob (the colored box
279/// with patrol/chase/attack AI). Use [`MobRegistry::register_variant`] to
280/// derive a new type from an existing one and change only what differs.
281///
282/// [`MobPlugin`] initializes an empty registry; games fill it at startup.
283///
284/// ```
285/// use bevy::prelude::Color;
286/// use voxel_framework::mobs::{MobConfig, MobKind, MobRegistry};
287///
288/// let mut registry = MobRegistry::default();
289/// registry.register("slime", MobConfig::default());
290/// registry
291///     .register_variant("night_slime", "slime", |config| {
292///         config.chase_speed = 5.0;
293///         config.color = Color::srgb(0.3, 0.1, 0.6);
294///     })
295///     .unwrap();
296///
297/// assert_eq!(registry.get(&MobKind::new("night_slime")).unwrap().chase_speed, 5.0);
298/// ```
299#[derive(Resource, Clone, Debug, Default)]
300pub struct MobRegistry {
301    kinds: BTreeMap<MobKind, MobConfig>,
302}
303
304impl MobRegistry {
305    /// Registers (or replaces) a mob type.
306    pub fn register(&mut self, kind: impl Into<MobKind>, config: MobConfig) -> &mut Self {
307        self.kinds.insert(kind.into(), config);
308        self
309    }
310
311    /// Registers `kind` as a copy of `base`'s config modified by `customize`.
312    ///
313    /// Later changes to `base` do not affect the variant.
314    pub fn register_variant(
315        &mut self,
316        kind: impl Into<MobKind>,
317        base: impl Into<MobKind>,
318        customize: impl FnOnce(&mut MobConfig),
319    ) -> Result<&mut Self, MobRegistryError> {
320        let base = base.into();
321        let mut config = self
322            .kinds
323            .get(&base)
324            .cloned()
325            .ok_or(MobRegistryError::UnknownBase(base))?;
326        customize(&mut config);
327        Ok(self.register(kind, config))
328    }
329
330    /// Returns the config for `kind`, if registered.
331    pub fn get(&self, kind: &MobKind) -> Option<&MobConfig> {
332        self.kinds.get(kind)
333    }
334
335    /// Returns `true` if `kind` is registered.
336    pub fn contains(&self, kind: &MobKind) -> bool {
337        self.kinds.contains_key(kind)
338    }
339
340    /// Iterates registered kinds in name order.
341    pub fn iter(&self) -> impl Iterator<Item = (&MobKind, &MobConfig)> {
342        self.kinds.iter()
343    }
344
345    /// Number of registered kinds.
346    pub fn len(&self) -> usize {
347        self.kinds.len()
348    }
349
350    /// Returns `true` when no kinds are registered.
351    pub fn is_empty(&self) -> bool {
352        self.kinds.is_empty()
353    }
354}
355
356/// Spawns a mob of a registered `kind` at `position`.
357///
358/// Works like [`spawn_mob`] with a copy of the kind's current [`MobConfig`]
359/// and also inserts the [`MobKind`] component; later registry changes do not
360/// affect mobs already spawned. Returns `None` when `kind` is not registered.
361pub fn spawn_mob_kind(
362    kind: &MobKind,
363    registry: &MobRegistry,
364    position: Vec3,
365    commands: &mut Commands,
366    meshes: &mut Assets<Mesh>,
367    materials: &mut Assets<StandardMaterial>,
368) -> Option<Entity> {
369    let config = registry.get(kind)?.clone();
370    let entity = spawn_mob(position, config, commands, meshes, materials);
371    commands.entity(entity).insert(kind.clone());
372    Some(entity)
373}
374
375// ─── Systems ──────────────────────────────────────────────────────────────────
376
377fn mob_ai_system(
378    player_q: Query<&Transform, With<Player>>,
379    mut mob_q: Query<(&Transform, &mut Mob, &MobConfigComponent)>,
380    time: Res<Time>,
381) {
382    let Ok(player_tf) = player_q.single() else {
383        return;
384    };
385    let player_pos = player_tf.translation;
386    let dt = time.delta_secs();
387
388    for (mob_tf, mut mob, cfg) in mob_q.iter_mut() {
389        let mob_pos = mob_tf.translation;
390        let dist = mob_pos.distance(player_pos);
391        let config = &cfg.0;
392
393        mob.attack_cooldown = (mob.attack_cooldown - dt).max(0.0);
394        mob.patrol_timer += dt;
395
396        match mob.ai_state {
397            MobAiState::Patrol => {
398                if dist < config.detection_radius {
399                    mob.ai_state = MobAiState::Chase;
400                } else {
401                    // Change patrol direction every 3-5 s using timer.
402                    if mob.patrol_timer > 3.0 {
403                        mob.patrol_timer = 0.0;
404                        // Simple hash-based pseudo-random direction.
405                        let t = mob_pos.x * 13.7 + mob_pos.z * 7.3 + time.elapsed_secs() * 2.3;
406                        mob.patrol_dir = Vec3::new(t.sin(), 0.0, t.cos()).normalize_or_zero();
407                        // Stop walking if too far from home.
408                        if mob_pos.distance(mob.home_position) > config.patrol_radius {
409                            let home_dir = (mob.home_position - mob_pos).normalize_or_zero();
410                            mob.patrol_dir = Vec3::new(home_dir.x, 0.0, home_dir.z);
411                        }
412                    }
413                    mob.velocity = mob.patrol_dir * config.patrol_speed;
414                }
415            }
416            MobAiState::Chase => {
417                if dist > config.detection_radius * 1.5 {
418                    mob.ai_state = MobAiState::Patrol;
419                    mob.patrol_dir = Vec3::ZERO;
420                } else if dist < config.attack_range {
421                    mob.ai_state = MobAiState::Attack;
422                    mob.velocity = Vec3::ZERO;
423                } else {
424                    let dir = (player_pos - mob_pos).normalize_or_zero();
425                    mob.velocity = Vec3::new(dir.x, 0.0, dir.z) * config.chase_speed;
426                }
427            }
428            MobAiState::Attack => {
429                if dist > config.attack_range * 1.5 {
430                    mob.ai_state = MobAiState::Chase;
431                }
432                // Slow creep toward player even in attack state.
433                let dir = (player_pos - mob_pos).normalize_or_zero();
434                mob.velocity = Vec3::new(dir.x, 0.0, dir.z) * (config.chase_speed * 0.3);
435            }
436        }
437    }
438}
439
440fn mob_attack_system(
441    player_q: Query<&Transform, With<Player>>,
442    mut mob_q: Query<(&Transform, &mut Mob, &MobConfigComponent)>,
443    mut player_health: ResMut<PlayerHealth>,
444) {
445    let Ok(player_tf) = player_q.single() else {
446        return;
447    };
448    let player_pos = player_tf.translation;
449
450    for (mob_tf, mut mob, cfg) in mob_q.iter_mut() {
451        if mob.ai_state != MobAiState::Attack {
452            continue;
453        }
454        if mob.attack_cooldown > 0.0 {
455            continue;
456        }
457        let dist = mob_tf.translation.distance(player_pos);
458        if dist <= cfg.0.attack_range {
459            player_health.health = (player_health.health - cfg.0.attack_damage).max(0.0);
460            mob.attack_cooldown = cfg.0.attack_cooldown;
461        }
462    }
463}
464
465/// Downward distance probed below a mob's capsule to decide whether it is
466/// standing on something, and the farthest it is snapped down onto the floor.
467/// Small enough that mobs still fall off ledges instead of floating.
468const GROUND_PROBE: f32 = 0.05;
469/// Minimum vertical push-out treated as contact (filters float noise).
470const CONTACT_EPSILON: f32 = 1e-4;
471/// Longest distance a mob moves between two collision passes. Kept below
472/// [`MOB_RADIUS`] so the capsule spine does not end a step inside a voxel,
473/// where the resolver can only guess which face to push out of. Holds for up
474/// to `MAX_STEP * MAX_SUBSTEPS` (11.2) units of travel per tick.
475const MAX_STEP: f32 = MOB_RADIUS * 0.5;
476/// Upper bound on collision passes per tick (a long frame hitch at full speed).
477const MAX_SUBSTEPS: usize = 64;
478/// Fastest a mob falls (m/s); bounds the substep count together with
479/// [`MAX_SUBSTEPS`].
480const TERMINAL_FALL_SPEED: f32 = 40.0;
481
482/// Number of equal substeps needed so `delta` moves at most [`MAX_STEP`] each.
483fn substep_count(delta: Vec3) -> usize {
484    let steps = (delta.abs().max_element() / MAX_STEP).ceil();
485    // `as usize` saturates and maps NaN to 0, so the clamp covers both.
486    (steps as usize).clamp(1, MAX_SUBSTEPS)
487}
488
489/// Advances one physics tick for a single mob and returns its new position.
490///
491/// `resolve` maps a capsule spine `(bottom, top)` to the corrected `bottom`
492/// position, exactly like [`resolve_capsule_collision`]. Keeping the world
493/// lookup behind a closure lets the grounded/zero-g logic be unit-tested
494/// without chunks.
495///
496/// Motion is split into substeps of at most [`MAX_STEP`]. In grounded mode
497/// each substep resolves horizontal motion first, keeping only the horizontal
498/// part of that push, and vertical motion second, keeping only the vertical
499/// part: a wall then never reads as a floor, even though the seam between two
500/// adjacent voxels pushes diagonally. A short downward probe at the end makes a resting mob
501/// report `on_ground == true` on every frame.
502fn mob_physics_step(
503    mob: &mut Mob,
504    mut pos: Vec3,
505    gravity: Option<f32>,
506    dt: f32,
507    mut resolve: impl FnMut(Vec3, Vec3) -> Vec3,
508) -> Vec3 {
509    // A degenerate time step moves nothing and must not corrupt the mob.
510    if !dt.is_finite() || dt <= 0.0 {
511        return pos;
512    }
513    let half = Vec3::Y * MOB_HALF_HEIGHT;
514    let mut push_out = |center: Vec3| resolve(center - half, center + half) - (center - half);
515
516    match gravity {
517        // ── Grounded mode (Minecraft-style) ───────────────────────────────
518        Some(g) => {
519            if !mob.on_ground || mob.vertical_velocity > 0.0 {
520                mob.vertical_velocity = (mob.vertical_velocity - g * dt).max(-TERMINAL_FALL_SPEED);
521            } else {
522                mob.vertical_velocity = 0.0;
523            }
524
525            let delta = (mob.velocity + Vec3::Y * mob.vertical_velocity) * dt;
526            let steps = substep_count(delta);
527            let mut step = delta / steps as f32;
528
529            for _ in 0..steps {
530                // Horizontal pass: walls stop the mob but never lift it.
531                pos.x += step.x;
532                pos.z += step.z;
533                let push = push_out(pos);
534                pos.x += push.x;
535                pos.z += push.z;
536
537                // Vertical pass: floors and ceilings stop the mob but never
538                // shove it sideways. Landing or bumping a ceiling cancels
539                // vertical speed for the rest of the tick.
540                pos.y += step.y;
541                let push = push_out(pos);
542                pos.y += push.y;
543                if (push.y > CONTACT_EPSILON && step.y < 0.0)
544                    || (push.y < -CONTACT_EPSILON && step.y > 0.0)
545                {
546                    mob.vertical_velocity = 0.0;
547                    step.y = 0.0;
548                }
549            }
550
551            // Ground probe: is there solid ground just below the feet?
552            mob.on_ground = false;
553            if mob.vertical_velocity <= 0.0 {
554                let probe = pos - Vec3::Y * GROUND_PROBE;
555                let probe_push = push_out(probe);
556                if probe_push.y > CONTACT_EPSILON {
557                    mob.on_ground = true;
558                    mob.vertical_velocity = 0.0;
559                    // Snap down onto the contact surface.
560                    pos.y = probe.y + probe_push.y;
561                }
562            }
563        }
564        // ── Zero-gravity mode (space / FreeFlight) ────────────────────────
565        None => {
566            // No gravity, no ground-snap. The AI velocity drives motion in
567            // full 3D. `vertical_velocity` stays at 0 and `on_ground` is
568            // meaningless here. Collision still runs so mobs cannot tunnel.
569            mob.vertical_velocity = 0.0;
570            mob.on_ground = false;
571            let delta = mob.velocity * dt;
572            let steps = substep_count(delta);
573            let step = delta / steps as f32;
574            for _ in 0..steps {
575                pos += step;
576                pos += push_out(pos);
577            }
578        }
579    }
580    pos
581}
582
583/// Returns `true` when the chunks holding the ground under a mob are loaded.
584///
585/// Checks the chunk just below the capsule's feet and the one `fall` units
586/// further down (how far the mob can drop this tick). The centre's chunk is
587/// not enough: a mob standing on a floor whose top face lies on a chunk
588/// boundary sits in the chunk above the one that holds the floor.
589fn mob_ground_loaded(pos: Vec3, fall: f32, is_loaded: impl Fn(IVec3) -> bool) -> bool {
590    let feet = pos - Vec3::Y * (MOB_HALF_HEIGHT + MOB_RADIUS + GROUND_PROBE);
591    is_loaded(world_to_chunk_coord(feet))
592        && is_loaded(world_to_chunk_coord(feet - Vec3::Y * fall.max(0.0)))
593}
594
595fn mob_physics_system<V: VoxelType>(
596    mut mob_q: Query<(&mut Transform, &mut Mob, &MobConfigComponent)>,
597    manager: Res<ChunkManager>,
598    chunks: Query<&Chunk<V>>,
599    time: Res<Time>,
600) {
601    let dt = time.delta_secs();
602    for (mut tf, mut mob, cfg) in mob_q.iter_mut() {
603        // Freeze mobs with gravity while the ground under them is not loaded
604        // yet so they don't fall through terrain that is still streaming in.
605        // Same rule as the player, whose gravity waits for the feet chunk.
606        if let Some(g) = cfg.0.gravity {
607            let fall = (g * dt - mob.vertical_velocity).clamp(0.0, TERMINAL_FALL_SPEED) * dt;
608            if !mob_ground_loaded(tf.translation, fall, |coord| manager.is_loaded(coord)) {
609                continue;
610            }
611        }
612        tf.translation = mob_physics_step(
613            &mut mob,
614            tf.translation,
615            cfg.0.gravity,
616            dt,
617            |bottom, top| {
618                resolve_capsule_collision::<V, ()>(bottom, top, MOB_RADIUS, &manager, &chunks)
619            },
620        );
621    }
622}
623
624fn mob_death_system(
625    mob_q: Query<(Entity, &Transform, &Mob)>,
626    mut commands: Commands,
627    mut died_writer: bevy::ecs::message::MessageWriter<MobDied>,
628) {
629    for (entity, tf, mob) in mob_q.iter() {
630        if mob.health <= 0.0 {
631            died_writer.write(MobDied {
632                position: tf.translation,
633            });
634            commands.entity(entity).despawn();
635        }
636    }
637}
638
639/// Despawns mobs farther than their `despawn_distance` from every player.
640fn mob_despawn_system(
641    mob_q: Query<(Entity, &Transform, &MobConfigComponent)>,
642    player_q: Query<&Transform, With<Player>>,
643    mut commands: Commands,
644) {
645    // Without players there is nothing to measure against; keep the mobs.
646    if player_q.is_empty() {
647        return;
648    }
649    for (entity, tf, cfg) in mob_q.iter() {
650        let nearest = player_q
651            .iter()
652            .map(|player| player.translation.distance(tf.translation))
653            .fold(f32::INFINITY, f32::min);
654        if nearest > cfg.0.despawn_distance {
655            // Another system may despawn the same mob this frame.
656            commands.entity(entity).try_despawn();
657        }
658    }
659}
660
661// ─── Plugin ───────────────────────────────────────────────────────────────────
662
663/// Plugin that wires up all mob systems for voxel type `V`.
664///
665/// Initializes an empty [`MobRegistry`]. Add [`MobPlugin`] after your core
666/// voxel plugin. It relies on
667/// [`crate::world::ChunkManager`], [`crate::player::Player`], and
668/// [`crate::player::PlayerHealth`] being present.
669///
670/// # Example
671///
672/// ```no_run
673/// use bevy::prelude::*;
674/// use voxel_framework::VoxelPlugin;
675/// use voxel_framework::mobs::MobPlugin;
676/// use voxel_framework::voxel::DefaultTerrainVoxel;
677///
678/// App::new()
679///     .add_plugins(DefaultPlugins)
680///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
681///     .add_plugins(MobPlugin::<DefaultTerrainVoxel>::new())
682///     .run();
683/// ```
684pub struct MobPlugin<V: VoxelType> {
685    _m: std::marker::PhantomData<V>,
686}
687
688impl<V: VoxelType> MobPlugin<V> {
689    /// Creates a new [`MobPlugin`] for voxel type `V`.
690    pub fn new() -> Self {
691        Self {
692            _m: std::marker::PhantomData,
693        }
694    }
695}
696
697impl<V: VoxelType> Default for MobPlugin<V> {
698    fn default() -> Self {
699        Self::new()
700    }
701}
702
703impl<V: VoxelType> Plugin for MobPlugin<V> {
704    fn build(&self, app: &mut App) {
705        app.add_message::<MobDied>();
706        app.init_resource::<MobRegistry>();
707        app.add_systems(
708            Update,
709            (
710                mob_ai_system,
711                mob_attack_system,
712                mob_physics_system::<V>,
713                mob_death_system,
714                mob_despawn_system,
715            ),
716        );
717    }
718}
719
720// ─── Tests ────────────────────────────────────────────────────────────────────
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725    use crate::test_support::{filled_chunk, world_with_chunks};
726    use crate::voxel::DefaultVoxel;
727    use bevy::ecs::system::{RunSystemOnce, SystemState};
728
729    const DT: f32 = 1.0 / 60.0;
730
731    /// Collision stand-in for a flat floor whose top surface is at `y = 0`
732    /// (everything below is solid). Returns the corrected capsule `bottom`
733    /// like [`resolve_capsule_collision`].
734    fn flat_floor(bottom: Vec3, _top: Vec3) -> Vec3 {
735        Vec3::new(bottom.x, bottom.y.max(MOB_RADIUS), bottom.z)
736    }
737
738    /// No collision at all (empty space).
739    fn empty(bottom: Vec3, _top: Vec3) -> Vec3 {
740        bottom
741    }
742
743    /// Height of a mob's centre when resting on [`flat_floor`].
744    const REST_Y: f32 = MOB_RADIUS + MOB_HALF_HEIGHT;
745
746    fn make_mob(velocity: Vec3) -> Mob {
747        Mob {
748            health: 20.0,
749            ai_state: MobAiState::Patrol,
750            velocity,
751            vertical_velocity: 0.0,
752            on_ground: false,
753            attack_cooldown: 0.0,
754            patrol_timer: 0.0,
755            patrol_dir: Vec3::ZERO,
756            home_position: Vec3::ZERO,
757        }
758    }
759
760    #[test]
761    fn mob_default_has_gravity_enabled() {
762        // Grounded behaviour is preserved as the default — existing games
763        // built against MobConfig::default() keep falling under gravity.
764        assert_eq!(MobConfig::default().gravity, Some(20.0));
765    }
766
767    #[test]
768    fn mob_zero_gravity_does_not_fall() {
769        let mut mob = make_mob(Vec3::ZERO);
770        let mut pos = Vec3::new(0.0, 100.0, 0.0);
771        for _ in 0..100 {
772            pos = mob_physics_step(&mut mob, pos, None, 0.1, empty);
773        }
774        assert_eq!(pos.y, 100.0, "zero-g mob must not fall");
775        assert_eq!(mob.vertical_velocity, 0.0);
776        assert!(!mob.on_ground);
777    }
778
779    #[test]
780    fn mob_zero_gravity_drifts_with_velocity() {
781        let mut mob = make_mob(Vec3::new(2.0, 0.0, 0.0));
782        let mut pos = Vec3::new(0.0, 100.0, 0.0);
783        // 10 ticks × 0.1 s × 2 m/s = 2.0 m drift.
784        for _ in 0..10 {
785            pos = mob_physics_step(&mut mob, pos, None, 0.1, empty);
786        }
787        assert!((pos.x - 2.0).abs() < 1e-4, "x drift = {}", pos.x);
788        assert_eq!(pos.y, 100.0, "y must not change in zero-g");
789    }
790
791    #[test]
792    fn mob_with_gravity_falls_in_empty_space() {
793        let mut mob = make_mob(Vec3::ZERO);
794        let mut pos = Vec3::new(0.0, 100.0, 0.0);
795        for _ in 0..10 {
796            pos = mob_physics_step(&mut mob, pos, Some(20.0), 0.1, empty);
797        }
798        assert!(pos.y < 100.0, "grounded mob must fall (got y={})", pos.y);
799        assert!(mob.vertical_velocity < 0.0);
800        assert!(!mob.on_ground);
801    }
802
803    #[test]
804    fn collision_moves_mob_by_push_out_not_by_absolute_position() {
805        // Regression: the physics system used to add the *resolved bottom
806        // position* to the translation, teleporting mobs far away. A mob
807        // resting on the floor at a large coordinate must stay put.
808        let mut mob = make_mob(Vec3::ZERO);
809        let start = Vec3::new(500.0, REST_Y, -300.0);
810        let pos = mob_physics_step(&mut mob, start, Some(20.0), DT, flat_floor);
811        assert!(pos.distance(start) < 0.01, "mob moved to {pos}");
812    }
813
814    #[test]
815    fn standing_mob_stays_grounded_every_frame() {
816        // Regression: a resting mob used to flip `on_ground` every frame.
817        for dt in [1.0 / 30.0, 1.0 / 60.0, 1.0 / 144.0, 1.0 / 1000.0] {
818            let mut mob = make_mob(Vec3::ZERO);
819            let mut pos = Vec3::new(0.0, 3.0, 0.0);
820            // Fall and land.
821            for _ in 0..((2.0 / dt) as usize) {
822                pos = mob_physics_step(&mut mob, pos, Some(20.0), dt, flat_floor);
823            }
824            for frame in 0..200 {
825                pos = mob_physics_step(&mut mob, pos, Some(20.0), dt, flat_floor);
826                assert!(mob.on_ground, "dt={dt}: lost ground on frame {frame}");
827                assert_eq!(mob.vertical_velocity, 0.0);
828                assert!((pos.y - REST_Y).abs() < 1e-3, "dt={dt}: y={}", pos.y);
829            }
830        }
831    }
832
833    #[test]
834    fn walking_mob_stays_grounded_on_flat_floor() {
835        let mut mob = make_mob(Vec3::new(1.2, 0.0, 0.0));
836        mob.on_ground = true;
837        let mut pos = Vec3::new(0.0, REST_Y, 0.0);
838        for _ in 0..120 {
839            pos = mob_physics_step(&mut mob, pos, Some(20.0), DT, flat_floor);
840            assert!(mob.on_ground);
841        }
842        assert!((pos.x - 2.4).abs() < 1e-3, "x={}", pos.x);
843    }
844
845    #[test]
846    fn mob_walks_off_a_ledge_and_falls() {
847        // Floor only where x < 0.
848        let ledge = |bottom: Vec3, _top: Vec3| {
849            if bottom.x < 0.0 {
850                flat_floor(bottom, _top)
851            } else {
852                bottom
853            }
854        };
855        let mut mob = make_mob(Vec3::new(2.0, 0.0, 0.0));
856        mob.on_ground = true;
857        let mut pos = Vec3::new(-1.0, REST_Y, 0.0);
858        for _ in 0..90 {
859            pos = mob_physics_step(&mut mob, pos, Some(20.0), DT, ledge);
860        }
861        assert!(!mob.on_ground);
862        assert!(
863            pos.y < REST_Y - 0.5,
864            "mob must fall past the ledge, y={}",
865            pos.y
866        );
867    }
868
869    // ── Real voxel collision ──────────────────────────────────────────────
870    //
871    // The closure stand-ins above cannot reproduce per-voxel artifacts of
872    // `resolve_capsule_collision` (seams between stacked voxels, the
873    // inside-AABB branch), so these tests run against real chunks.
874
875    /// Top surface of the solid chunk used by [`floor_world`].
876    const FLOOR_TOP: f32 = 16.0;
877
878    /// Solid chunk at the origin with a loaded, empty chunk above it.
879    fn floor_world() -> World {
880        world_with_chunks([
881            (IVec3::ZERO, filled_chunk(DefaultVoxel::Rock)),
882            (IVec3::Y, Chunk::<DefaultVoxel>::new()),
883        ])
884    }
885
886    /// Runs `f` with a resolver backed by the chunks in `world`.
887    fn with_real_collision<R>(
888        world: &mut World,
889        f: impl FnOnce(&mut dyn FnMut(Vec3, Vec3) -> Vec3) -> R,
890    ) -> R {
891        let mut state: SystemState<(Res<ChunkManager>, Query<&Chunk<DefaultVoxel>>)> =
892            SystemState::new(world);
893        let (manager, chunks) = state.get(world);
894        let mut resolve = |bottom: Vec3, top: Vec3| {
895            resolve_capsule_collision::<DefaultVoxel, ()>(
896                bottom, top, MOB_RADIUS, &manager, &chunks,
897            )
898        };
899        f(&mut resolve)
900    }
901
902    #[test]
903    fn falling_mob_pressed_against_a_wall_keeps_falling() {
904        // Regression: the seam between two stacked wall voxels returns a
905        // diagonal push with a small +y component. Treating it as a landing
906        // left a chasing mob hanging on the wall in mid-air.
907        let mut wall = Chunk::<DefaultVoxel>::new();
908        for x in 8..16 {
909            for y in 0..16 {
910                for z in 0..16 {
911                    wall.set(x, y, z, DefaultVoxel::Rock);
912                }
913            }
914        }
915        let mut world = world_with_chunks([(IVec3::ZERO, wall)]);
916        with_real_collision(&mut world, |resolve| {
917            let mut mob = make_mob(Vec3::new(3.5, 0.0, 0.0));
918            let start = Vec3::new(8.0 - MOB_RADIUS, 12.0, 8.5);
919            let mut pos = start;
920            // 0.5 s of free fall is 2.5 units.
921            for _ in 0..30 {
922                pos = mob_physics_step(&mut mob, pos, Some(20.0), DT, &mut *resolve);
923                assert!(!mob.on_ground, "a wall is not ground (y={})", pos.y);
924            }
925            assert!(pos.y < start.y - 2.0, "mob hung on the wall at y={}", pos.y);
926            assert!(pos.x <= start.x + 1e-3, "mob entered the wall, x={}", pos.x);
927        });
928    }
929
930    #[test]
931    fn fast_falling_mob_lands_on_top_of_the_floor() {
932        // Regression: one big step could put the capsule spine inside a floor
933        // voxel, where the resolver pushes along the nearest face (often
934        // sideways) and the mob kept sinking.
935        let mut world = floor_world();
936        with_real_collision(&mut world, |resolve| {
937            for x in [8.02, 8.5, 8.98] {
938                for fall_speed in [15.0, 30.0, TERMINAL_FALL_SPEED] {
939                    let mut mob = make_mob(Vec3::ZERO);
940                    mob.vertical_velocity = -fall_speed;
941                    let mut pos = Vec3::new(x, FLOOR_TOP + REST_Y + 0.5, 8.5);
942                    for _ in 0..30 {
943                        pos =
944                            mob_physics_step(&mut mob, pos, Some(20.0), 1.0 / 30.0, &mut *resolve);
945                    }
946                    assert!(
947                        mob.on_ground,
948                        "x={x} v={fall_speed}: not grounded, y={}",
949                        pos.y
950                    );
951                    assert!(
952                        (pos.y - (FLOOR_TOP + REST_Y)).abs() < 1e-2,
953                        "x={x} v={fall_speed}: rests at y={}",
954                        pos.y
955                    );
956                    assert!(
957                        (pos.x - x).abs() < 1e-2,
958                        "x={x} v={fall_speed}: pushed to {}",
959                        pos.x
960                    );
961                }
962            }
963        });
964    }
965
966    #[test]
967    fn mob_bumping_a_ceiling_loses_upward_speed() {
968        // Solid everywhere above y = 2 (capsule top sphere stops at 2).
969        let ceiling = |bottom: Vec3, top: Vec3| {
970            let limit = 2.0 - MOB_RADIUS;
971            bottom - Vec3::Y * (top.y - limit).max(0.0)
972        };
973        let mut mob = make_mob(Vec3::ZERO);
974        mob.vertical_velocity = 8.0;
975        let mut pos = Vec3::new(0.0, 1.0, 0.0);
976        for _ in 0..10 {
977            pos = mob_physics_step(&mut mob, pos, Some(20.0), DT, ceiling);
978            assert!(pos.y + MOB_HALF_HEIGHT + MOB_RADIUS <= 2.0 + 1e-4);
979        }
980        assert!(mob.vertical_velocity <= 0.0, "v={}", mob.vertical_velocity);
981        assert!(!mob.on_ground);
982    }
983
984    #[test]
985    fn upward_speed_lifts_a_grounded_mob() {
986        // A game that sets `vertical_velocity` on a grounded mob (a jump) must
987        // not have it cancelled by the ground probe.
988        let mut mob = make_mob(Vec3::ZERO);
989        mob.on_ground = true;
990        mob.vertical_velocity = 6.0;
991        let pos = mob_physics_step(
992            &mut mob,
993            Vec3::new(0.0, REST_Y, 0.0),
994            Some(20.0),
995            DT,
996            flat_floor,
997        );
998        assert!(pos.y > REST_Y + 0.05, "y={}", pos.y);
999        assert!(!mob.on_ground);
1000        assert!(mob.vertical_velocity > 0.0);
1001    }
1002
1003    #[test]
1004    fn degenerate_time_steps_leave_the_mob_untouched() {
1005        let start = Vec3::new(0.0, 5.0, 0.0);
1006        for dt in [0.0, -1.0, f32::NAN, f32::INFINITY] {
1007            let mut mob = make_mob(Vec3::new(1.0, 0.0, 0.0));
1008            let pos = mob_physics_step(&mut mob, start, Some(20.0), dt, empty);
1009            assert_eq!(pos, start, "dt={dt}");
1010            assert_eq!(mob.vertical_velocity, 0.0, "dt={dt}");
1011        }
1012        assert_eq!(substep_count(Vec3::splat(f32::NAN)), 1);
1013        assert_eq!(substep_count(Vec3::splat(f32::INFINITY)), MAX_SUBSTEPS);
1014        assert_eq!(substep_count(Vec3::ZERO), 1);
1015    }
1016
1017    #[test]
1018    fn falling_speed_is_capped() {
1019        let mut mob = make_mob(Vec3::ZERO);
1020        let mut pos = Vec3::new(0.0, 1000.0, 0.0);
1021        for _ in 0..600 {
1022            pos = mob_physics_step(&mut mob, pos, Some(20.0), DT, empty);
1023        }
1024        assert_eq!(mob.vertical_velocity, -TERMINAL_FALL_SPEED);
1025    }
1026
1027    #[test]
1028    fn ground_is_loaded_only_when_the_chunk_under_the_feet_is() {
1029        // Mob resting on a floor whose top face is the chunk boundary y = 16:
1030        // its centre is in chunk (0, 1, 0), the floor in chunk (0, 0, 0).
1031        let pos = Vec3::new(8.0, FLOOR_TOP + REST_Y, 8.0);
1032        let air = IVec3::Y;
1033        let floor = IVec3::ZERO;
1034        assert!(mob_ground_loaded(pos, 0.0, |c| c == floor));
1035        assert!(!mob_ground_loaded(pos, 0.0, |c| c == air));
1036        // A mob falling toward the boundary needs the chunk it will reach.
1037        let above = pos + Vec3::Y * 0.5;
1038        assert!(mob_ground_loaded(above, 0.0, |c| c == air));
1039        assert!(!mob_ground_loaded(above, 0.6, |c| c == air));
1040        assert!(mob_ground_loaded(above, 0.6, |c| c == air || c == floor));
1041    }
1042
1043    /// Spawns a bare mob (no mesh) and returns its entity.
1044    fn spawn_bare_mob(world: &mut World, pos: Vec3, config: MobConfig) -> Entity {
1045        world
1046            .spawn((
1047                Transform::from_translation(pos),
1048                make_mob(Vec3::ZERO),
1049                MobConfigComponent(config),
1050            ))
1051            .id()
1052    }
1053
1054    fn run_physics_frames(world: &mut World, frames: usize) {
1055        for _ in 0..frames {
1056            world
1057                .resource_mut::<Time>()
1058                .advance_by(std::time::Duration::from_secs_f32(DT));
1059            world
1060                .run_system_once(mob_physics_system::<DefaultVoxel>)
1061                .unwrap();
1062        }
1063    }
1064
1065    #[test]
1066    fn physics_system_rests_mob_on_real_floor_far_from_origin() {
1067        // End-to-end regression for the position-vs-offset bug: the system
1068        // itself, the real resolver, and a chunk away from the origin.
1069        let base = IVec3::new(20, 3, -15);
1070        let mut world = world_with_chunks([
1071            (base, filled_chunk(DefaultVoxel::Rock)),
1072            (base + IVec3::Y, Chunk::<DefaultVoxel>::new()),
1073        ]);
1074        world.insert_resource(Time::<()>::default());
1075        let top = (base.y + 1) as f32 * 16.0;
1076        let start = Vec3::new(
1077            base.x as f32 * 16.0 + 8.5,
1078            top + REST_Y + 1.0,
1079            base.z as f32 * 16.0 + 8.5,
1080        );
1081        let entity = spawn_bare_mob(&mut world, start, MobConfig::default());
1082
1083        run_physics_frames(&mut world, 120);
1084
1085        let pos = world.get::<Transform>(entity).unwrap().translation;
1086        assert!((pos.y - (top + REST_Y)).abs() < 1e-2, "y={}", pos.y);
1087        assert!(
1088            (pos.x - start.x).abs() < 1e-3 && (pos.z - start.z).abs() < 1e-3,
1089            "pos={pos}"
1090        );
1091        assert!(world.get::<Mob>(entity).unwrap().on_ground);
1092    }
1093
1094    #[test]
1095    fn physics_system_freezes_mob_until_its_floor_chunk_loads() {
1096        // Only the air chunk is loaded; the floor chunk below is not.
1097        let mut world = world_with_chunks([(IVec3::Y, Chunk::<DefaultVoxel>::new())]);
1098        world.insert_resource(Time::<()>::default());
1099        let start = Vec3::new(8.5, FLOOR_TOP + REST_Y, 8.5);
1100        let entity = spawn_bare_mob(&mut world, start, MobConfig::default());
1101
1102        run_physics_frames(&mut world, 30);
1103        assert_eq!(world.get::<Transform>(entity).unwrap().translation, start);
1104
1105        // Once the floor arrives the mob stands on it.
1106        let floor = world.spawn(filled_chunk(DefaultVoxel::Rock)).id();
1107        world
1108            .resource_mut::<ChunkManager>()
1109            .register(IVec3::ZERO, floor);
1110        run_physics_frames(&mut world, 30);
1111        let pos = world.get::<Transform>(entity).unwrap().translation;
1112        assert!((pos.y - start.y).abs() < 1e-2, "y={}", pos.y);
1113        assert!(world.get::<Mob>(entity).unwrap().on_ground);
1114    }
1115
1116    #[test]
1117    fn physics_system_stops_a_falling_mob_above_an_unloaded_floor_chunk() {
1118        // The mob must freeze before entering the unloaded chunk, not one
1119        // tick of fall inside it (where the floor will appear around it).
1120        let mut world = world_with_chunks([(IVec3::Y, Chunk::<DefaultVoxel>::new())]);
1121        world.insert_resource(Time::<()>::default());
1122        let entity = spawn_bare_mob(
1123            &mut world,
1124            Vec3::new(8.2, FLOOR_TOP + 6.0, 8.5),
1125            MobConfig::default(),
1126        );
1127        world.get_mut::<Mob>(entity).unwrap().vertical_velocity = -25.0;
1128
1129        run_physics_frames(&mut world, 60);
1130
1131        let pos = world.get::<Transform>(entity).unwrap().translation;
1132        assert!(pos.y >= FLOOR_TOP + REST_Y, "sank to y={}", pos.y);
1133    }
1134
1135    #[test]
1136    fn physics_system_moves_mobs_on_a_world_with_no_chunk_above() {
1137        // A finite world: one solid chunk and nothing registered above it.
1138        let mut world = world_with_chunks([(IVec3::ZERO, filled_chunk(DefaultVoxel::Rock))]);
1139        world.insert_resource(Time::<()>::default());
1140        let entity = spawn_bare_mob(
1141            &mut world,
1142            Vec3::new(8.5, FLOOR_TOP + REST_Y + 0.02, 8.5),
1143            MobConfig::default(),
1144        );
1145        world.get_mut::<Mob>(entity).unwrap().velocity = Vec3::new(1.0, 0.0, 0.0);
1146
1147        run_physics_frames(&mut world, 60);
1148
1149        let pos = world.get::<Transform>(entity).unwrap().translation;
1150        assert!((pos.x - 9.5).abs() < 1e-2, "x={}", pos.x);
1151        assert!(world.get::<Mob>(entity).unwrap().on_ground);
1152    }
1153
1154    #[test]
1155    fn physics_system_lets_zero_gravity_mobs_drift_without_chunks() {
1156        let mut world = world_with_chunks::<DefaultVoxel>([]);
1157        world.insert_resource(Time::<()>::default());
1158        let config = MobConfig {
1159            gravity: None,
1160            ..Default::default()
1161        };
1162        let entity = spawn_bare_mob(&mut world, Vec3::ZERO, config);
1163        world.get_mut::<Mob>(entity).unwrap().velocity = Vec3::new(0.0, 2.0, 0.0);
1164
1165        run_physics_frames(&mut world, 60);
1166
1167        let pos = world.get::<Transform>(entity).unwrap().translation;
1168        assert!((pos.y - 2.0).abs() < 1e-2, "y={}", pos.y);
1169    }
1170
1171    #[test]
1172    fn registry_variant_derives_from_base() {
1173        let mut registry = MobRegistry::default();
1174        registry.register("slime", MobConfig::default());
1175        registry
1176            .register_variant("night_slime", "slime", |c| c.chase_speed = 6.0)
1177            .unwrap();
1178
1179        let base = registry.get(&"slime".into()).unwrap();
1180        let variant = registry.get(&"night_slime".into()).unwrap();
1181        assert_eq!(variant.chase_speed, 6.0);
1182        assert_eq!(variant.max_health, base.max_health);
1183        assert_eq!(base.chase_speed, MobConfig::default().chase_speed);
1184        assert_eq!(registry.len(), 2);
1185    }
1186
1187    #[test]
1188    fn registry_iterates_in_name_order_and_replaces_on_reregister() {
1189        let mut registry = MobRegistry::default();
1190        for name in ["slime", "bat", "zombie"] {
1191            registry.register(name, MobConfig::default());
1192        }
1193        let names: Vec<&str> = registry.iter().map(|(kind, _)| kind.as_str()).collect();
1194        assert_eq!(names, ["bat", "slime", "zombie"]);
1195
1196        registry.register(
1197            "slime",
1198            MobConfig {
1199                chase_speed: 9.0,
1200                ..Default::default()
1201            },
1202        );
1203        assert_eq!(registry.len(), 3);
1204        assert_eq!(registry.get(&"slime".into()).unwrap().chase_speed, 9.0);
1205    }
1206
1207    #[test]
1208    fn mob_plugin_initializes_an_empty_registry() {
1209        let mut app = App::new();
1210        app.add_plugins(MobPlugin::<DefaultVoxel>::new());
1211        assert!(app.world().resource::<MobRegistry>().is_empty());
1212    }
1213
1214    #[test]
1215    fn mobs_despawn_by_distance_to_the_nearest_player() {
1216        let mut world = World::new();
1217        let config = MobConfig {
1218            despawn_distance: 10.0,
1219            ..Default::default()
1220        };
1221        let near_a = spawn_bare_mob(&mut world, Vec3::new(5.0, 0.0, 0.0), config.clone());
1222        let near_b = spawn_bare_mob(&mut world, Vec3::new(105.0, 0.0, 0.0), config.clone());
1223        let stranded = spawn_bare_mob(&mut world, Vec3::new(50.0, 0.0, 0.0), config);
1224
1225        // No players: nothing is despawned.
1226        world.run_system_once(mob_despawn_system).unwrap();
1227        assert!(world.get_entity(stranded).is_ok());
1228
1229        world.spawn((Player::default(), Transform::from_xyz(0.0, 0.0, 0.0)));
1230        world.spawn((Player::default(), Transform::from_xyz(100.0, 0.0, 0.0)));
1231        world.run_system_once(mob_despawn_system).unwrap();
1232
1233        assert!(world.get_entity(near_a).is_ok());
1234        assert!(world.get_entity(near_b).is_ok());
1235        assert!(world.get_entity(stranded).is_err());
1236    }
1237
1238    #[test]
1239    fn registry_variant_of_unknown_base_fails() {
1240        let mut registry = MobRegistry::default();
1241        let err = registry
1242            .register_variant("ghost", "slime", |_| {})
1243            .unwrap_err();
1244        assert_eq!(err, MobRegistryError::UnknownBase("slime".into()));
1245        assert!(!registry.contains(&"ghost".into()));
1246    }
1247
1248    #[test]
1249    fn spawn_mob_kind_inserts_kind_component() {
1250        let mut app = App::new();
1251        app.add_plugins(MinimalPlugins)
1252            .init_resource::<Assets<Mesh>>()
1253            .init_resource::<Assets<StandardMaterial>>();
1254        let mut registry = MobRegistry::default();
1255        registry.register("slime", MobConfig::default());
1256        app.insert_resource(registry);
1257
1258        let spawned = app
1259            .world_mut()
1260            .run_system_once(
1261                |mut commands: Commands,
1262                 registry: Res<MobRegistry>,
1263                 mut meshes: ResMut<Assets<Mesh>>,
1264                 mut materials: ResMut<Assets<StandardMaterial>>| {
1265                    let slime = spawn_mob_kind(
1266                        &"slime".into(),
1267                        &registry,
1268                        Vec3::ZERO,
1269                        &mut commands,
1270                        &mut meshes,
1271                        &mut materials,
1272                    );
1273                    let unknown = spawn_mob_kind(
1274                        &"ghost".into(),
1275                        &registry,
1276                        Vec3::ZERO,
1277                        &mut commands,
1278                        &mut meshes,
1279                        &mut materials,
1280                    );
1281                    (slime, unknown)
1282                },
1283            )
1284            .unwrap();
1285
1286        assert!(spawned.1.is_none());
1287        let entity = spawned.0.expect("registered kind spawns");
1288        let kind = app.world().get::<MobKind>(entity).unwrap();
1289        assert_eq!(kind.as_str(), "slime");
1290    }
1291}