1use 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
51pub const MOB_HALF_HEIGHT: f32 = 0.5;
55pub const MOB_RADIUS: f32 = 0.35;
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum MobAiState {
63 Patrol,
65 Chase,
67 Attack,
69}
70
71#[derive(Component)]
73pub struct Mob {
74 pub health: f32,
76 pub ai_state: MobAiState,
78 pub velocity: Vec3,
80 pub vertical_velocity: f32,
82 pub on_ground: bool,
84 pub attack_cooldown: f32,
86 pub patrol_timer: f32,
88 pub patrol_dir: Vec3,
90 pub home_position: Vec3,
92}
93
94#[derive(Clone, Debug)]
101pub struct MobConfig {
102 pub max_health: f32,
104 pub chase_speed: f32,
106 pub patrol_speed: f32,
108 pub detection_radius: f32,
110 pub attack_range: f32,
112 pub attack_damage: f32,
114 pub attack_cooldown: f32,
116 pub patrol_radius: f32,
118 pub despawn_distance: f32,
120 pub gravity: Option<f32>,
131 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#[derive(bevy::ecs::message::Message, Debug, Clone)]
159pub struct MobDied {
160 pub position: Vec3,
162}
163
164pub 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#[derive(Component)]
211pub struct MobConfigComponent(pub MobConfig);
212
213#[derive(Component, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
221pub struct MobKind(String);
222
223impl MobKind {
224 pub fn new(name: impl Into<String>) -> Self {
226 Self(name.into())
227 }
228
229 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#[derive(Clone, Debug, PartialEq, Eq)]
261pub enum MobRegistryError {
262 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#[derive(Resource, Clone, Debug, Default)]
300pub struct MobRegistry {
301 kinds: BTreeMap<MobKind, MobConfig>,
302}
303
304impl MobRegistry {
305 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 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 pub fn get(&self, kind: &MobKind) -> Option<&MobConfig> {
332 self.kinds.get(kind)
333 }
334
335 pub fn contains(&self, kind: &MobKind) -> bool {
337 self.kinds.contains_key(kind)
338 }
339
340 pub fn iter(&self) -> impl Iterator<Item = (&MobKind, &MobConfig)> {
342 self.kinds.iter()
343 }
344
345 pub fn len(&self) -> usize {
347 self.kinds.len()
348 }
349
350 pub fn is_empty(&self) -> bool {
352 self.kinds.is_empty()
353 }
354}
355
356pub 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
375fn 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 if mob.patrol_timer > 3.0 {
403 mob.patrol_timer = 0.0;
404 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 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 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
465const GROUND_PROBE: f32 = 0.05;
469const CONTACT_EPSILON: f32 = 1e-4;
471const MAX_STEP: f32 = MOB_RADIUS * 0.5;
476const MAX_SUBSTEPS: usize = 64;
478const TERMINAL_FALL_SPEED: f32 = 40.0;
481
482fn substep_count(delta: Vec3) -> usize {
484 let steps = (delta.abs().max_element() / MAX_STEP).ceil();
485 (steps as usize).clamp(1, MAX_SUBSTEPS)
487}
488
489fn 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 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 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 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 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 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 pos.y = probe.y + probe_push.y;
561 }
562 }
563 }
564 None => {
566 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
583fn 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 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
639fn mob_despawn_system(
641 mob_q: Query<(Entity, &Transform, &MobConfigComponent)>,
642 player_q: Query<&Transform, With<Player>>,
643 mut commands: Commands,
644) {
645 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 commands.entity(entity).try_despawn();
657 }
658 }
659}
660
661pub struct MobPlugin<V: VoxelType> {
685 _m: std::marker::PhantomData<V>,
686}
687
688impl<V: VoxelType> MobPlugin<V> {
689 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#[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 fn flat_floor(bottom: Vec3, _top: Vec3) -> Vec3 {
735 Vec3::new(bottom.x, bottom.y.max(MOB_RADIUS), bottom.z)
736 }
737
738 fn empty(bottom: Vec3, _top: Vec3) -> Vec3 {
740 bottom
741 }
742
743 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 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 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 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 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 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 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 const FLOOR_TOP: f32 = 16.0;
877
878 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 ®istry,
1268 Vec3::ZERO,
1269 &mut commands,
1270 &mut meshes,
1271 &mut materials,
1272 );
1273 let unknown = spawn_mob_kind(
1274 &"ghost".into(),
1275 ®istry,
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}