1use bevy::prelude::*;
49
50use crate::chunk::Chunk;
51#[cfg(feature = "items")]
52use crate::items::inventory::{ContainerComponent, PrimaryContainer};
53#[cfg(feature = "items")]
54use crate::items::{HotbarState, ItemType};
55#[cfg(feature = "items")]
56use crate::player::effects::AppliedEffectModifiers;
57use crate::voxel::VoxelType;
58
59use super::{ChunkManager, ChunkModified, record_voxel_edit};
60
61#[derive(Resource, Debug, Clone)]
68pub struct MiningConfig {
69 pub break_time: f32,
73}
74
75impl Default for MiningConfig {
76 fn default() -> Self {
77 Self { break_time: 1.5 }
78 }
79}
80
81#[derive(Resource, Debug)]
91pub struct MiningState {
92 pub target: Option<(IVec3, (usize, usize, usize))>,
95 pub elapsed: f32,
97 pub progress: f32,
101 pub(crate) effective_break_time: f32,
106}
107
108impl Default for MiningState {
109 fn default() -> Self {
110 Self {
111 target: None,
112 elapsed: 0.0,
113 progress: 0.0,
114 effective_break_time: 1.0,
115 }
116 }
117}
118
119#[cfg_attr(
122 feature = "items",
123 doc = "[`MiningInputPlugin`] keeps this resource up to date via `hotbar_to_tool_system`. Game code that calls [`tick_mining`] directly can read or override it as needed."
124)]
125#[cfg_attr(
126 not(feature = "items"),
127 doc = "Game code that calls [`tick_mining`] directly can read or override this resource as needed. The automatic input adapter requires the `items` feature."
128)]
129#[derive(Resource, Debug, Clone)]
130pub struct ToolStats {
131 pub tool_level: u8,
136 pub tool_speed: f32,
140}
141
142impl ToolStats {
143 pub fn reset(&mut self) {
145 self.tool_level = 0;
146 self.tool_speed = 1.0;
147 }
148}
149
150impl Default for ToolStats {
151 fn default() -> Self {
152 Self {
153 tool_level: 0,
154 tool_speed: 1.0,
155 }
156 }
157}
158
159#[derive(Message, Debug, Clone)]
167pub struct VoxelBroken {
168 pub chunk_coord: IVec3,
170 pub local: (usize, usize, usize),
173 pub world_pos: Vec3,
175 pub voxel_byte: u8,
181}
182
183#[derive(Message, Debug, Clone)]
189pub struct MiningProgress {
190 pub progress: f32,
194 pub world_pos: Vec3,
196}
197
198fn break_voxel<V: VoxelType>(
204 world_voxel: IVec3,
205 tool_level: u8,
206 manager: &ChunkManager,
207 chunks: &mut Query<&mut Chunk<V>>,
208 broken: &mut MessageWriter<VoxelBroken>,
209 modified: &mut MessageWriter<ChunkModified>,
210) {
211 use crate::chunk::CHUNK_SIZE;
212 let cs = CHUNK_SIZE as i32;
213 let chunk_coord = IVec3::new(
214 world_voxel.x.div_euclid(cs),
215 world_voxel.y.div_euclid(cs),
216 world_voxel.z.div_euclid(cs),
217 );
218 let local = (
219 world_voxel.x.rem_euclid(cs) as usize,
220 world_voxel.y.rem_euclid(cs) as usize,
221 world_voxel.z.rem_euclid(cs) as usize,
222 );
223
224 let Some(entity) = manager.get_entity(chunk_coord) else {
225 return;
226 };
227 let Ok(mut chunk) = chunks.get_mut(entity) else {
228 return;
229 };
230 let voxel = chunk.get(local.0, local.1, local.2);
231 if !voxel.is_solid() || tool_level < voxel.mining_level() {
232 return;
233 }
234 let voxel_byte = voxel.to_byte();
235 chunk.set(local.0, local.1, local.2, V::air());
236 drop(chunk);
237 record_voxel_edit(
238 chunk_coord,
239 local,
240 voxel,
241 V::air(),
242 manager,
243 chunks,
244 modified,
245 );
246
247 let wp = voxel_world_pos(chunk_coord, local);
248 broken.write(VoxelBroken {
249 chunk_coord,
250 local,
251 world_pos: wp,
252 voxel_byte,
253 });
254 modified.write(ChunkModified(chunk_coord));
255 notify_border_neighbors(chunk_coord, local, modified);
256}
257
258fn quad_offsets(face_normal: Vec3, hit_point: Vec3, voxel_center: Vec3) -> [IVec3; 3] {
266 let sign = |coord: f32, center: f32| -> i32 { if coord >= center { 1 } else { -1 } };
267 let (du, dv) = if face_normal.x.abs() > 0.5 {
268 (
270 IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
271 IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
272 )
273 } else if face_normal.y.abs() > 0.5 {
274 (
276 IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
277 IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
278 )
279 } else {
280 (
282 IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
283 IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
284 )
285 };
286 [du, dv, du + dv]
287}
288
289fn notify_border_neighbors(
296 chunk_coord: IVec3,
297 local: (usize, usize, usize),
298 modified: &mut MessageWriter<ChunkModified>,
299) {
300 use crate::chunk::CHUNK_SIZE;
301 let (x, y, z) = local;
302 let offsets: [(usize, IVec3); 6] = [
303 (x, IVec3::NEG_X),
304 (CHUNK_SIZE - 1 - x, IVec3::X),
305 (y, IVec3::NEG_Y),
306 (CHUNK_SIZE - 1 - y, IVec3::Y),
307 (z, IVec3::NEG_Z),
308 (CHUNK_SIZE - 1 - z, IVec3::Z),
309 ];
310 for (dist, dir) in offsets {
311 if dist == 0 {
312 modified.write(ChunkModified(chunk_coord + dir));
313 }
314 }
315}
316
317fn voxel_world_pos(chunk_coord: IVec3, local: (usize, usize, usize)) -> Vec3 {
319 let chunk_origin = chunk_coord.as_vec3() * crate::chunk::CHUNK_SIZE as f32;
320 chunk_origin
321 + Vec3::new(
322 local.0 as f32 + 0.5,
323 local.1 as f32 + 0.5,
324 local.2 as f32 + 0.5,
325 )
326}
327
328#[allow(clippy::too_many_arguments)]
386pub fn tick_mining<V: VoxelType>(
387 target_chunk: IVec3,
388 target_local: (usize, usize, usize),
389 delta_secs: f32,
390 state: &mut MiningState,
391 config: &MiningConfig,
392 manager: &ChunkManager,
393 chunks: &mut Query<&mut Chunk<V>>,
394 broken: &mut MessageWriter<VoxelBroken>,
395 progress_writer: &mut MessageWriter<MiningProgress>,
396 modified: &mut MessageWriter<ChunkModified>,
397) {
398 if state.target != Some((target_chunk, target_local)) {
400 let hardness = manager
401 .get_entity(target_chunk)
402 .and_then(|e| chunks.get(e).ok())
403 .map(|chunk| {
404 let (x, y, z) = target_local;
405 chunk.get(x, y, z).hardness()
406 })
407 .unwrap_or(1.0);
408
409 state.effective_break_time = if hardness > 0.0 {
411 config.break_time * hardness
412 } else {
413 f32::MAX
414 };
415 state.elapsed = 0.0;
416 state.progress = 0.0;
417 state.target = Some((target_chunk, target_local));
418 }
419
420 state.elapsed += delta_secs;
421 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
422
423 let world_pos = voxel_world_pos(target_chunk, target_local);
424
425 progress_writer.write(MiningProgress {
426 progress: state.progress,
427 world_pos,
428 });
429
430 if state.progress >= 1.0 && state.effective_break_time < f32::MAX {
431 let mut voxel_byte = V::air().to_byte();
433 if let Some(entity) = manager.get_entity(target_chunk) {
434 if let Ok(mut chunk) = chunks.get_mut(entity) {
435 let (x, y, z) = target_local;
436 let voxel = chunk.get(x, y, z);
437 voxel_byte = voxel.to_byte();
438 chunk.set(x, y, z, V::air());
439 drop(chunk);
440 record_voxel_edit(
441 target_chunk,
442 target_local,
443 voxel,
444 V::air(),
445 manager,
446 chunks,
447 modified,
448 );
449 }
450 }
451
452 broken.write(VoxelBroken {
453 chunk_coord: target_chunk,
454 local: target_local,
455 world_pos,
456 voxel_byte,
457 });
458
459 modified.write(ChunkModified(target_chunk));
460 notify_border_neighbors(target_chunk, target_local, modified);
461
462 state.target = None;
464 state.elapsed = 0.0;
465 state.progress = 0.0;
466 }
467}
468
469pub fn stop_mining(state: &mut MiningState) {
484 state.target = None;
485 state.elapsed = 0.0;
486 state.progress = 0.0;
487}
488
489pub struct MiningPlugin;
503
504impl Plugin for MiningPlugin {
505 fn build(&self, app: &mut App) {
506 app.init_resource::<MiningConfig>();
507 app.init_resource::<MiningState>();
508 app.add_message::<VoxelBroken>();
509 app.add_message::<MiningProgress>();
510 }
511}
512
513#[cfg(feature = "items")]
559pub struct MiningInputPlugin<V: VoxelType, I: ItemType> {
560 _m: std::marker::PhantomData<(V, I)>,
561}
562
563#[cfg(feature = "items")]
564impl<V: VoxelType, I: ItemType> MiningInputPlugin<V, I> {
565 pub fn new() -> Self {
567 Self {
568 _m: std::marker::PhantomData,
569 }
570 }
571}
572
573#[cfg(feature = "items")]
574impl<V: VoxelType, I: ItemType> Default for MiningInputPlugin<V, I> {
575 fn default() -> Self {
576 Self::new()
577 }
578}
579
580#[cfg(feature = "items")]
581impl<V: VoxelType, I: ItemType> Plugin for MiningInputPlugin<V, I> {
582 fn build(&self, app: &mut App) {
583 app.init_resource::<ToolStats>();
584 app.add_systems(
585 Update,
586 (hotbar_to_tool_system::<I>, mining_input_system::<V>).chain(),
587 );
588 }
589}
590
591#[cfg(feature = "items")]
598pub fn hotbar_to_tool_system<I: ItemType>(
599 hotbar: Res<HotbarState>,
600 container_query: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
601 mut tool_stats: ResMut<ToolStats>,
602 applied: Option<Res<AppliedEffectModifiers>>,
603) {
604 let Ok(container) = container_query.single() else {
605 tool_stats.reset();
606 return;
607 };
608 let active_slot = hotbar.selected;
609 if let Some(slot) = container.0.slots.get(active_slot).and_then(|s| s.as_ref()) {
610 tool_stats.tool_level = slot.item.tool_level();
611 tool_stats.tool_speed = slot.item.tool_speed()
612 * applied
613 .as_deref()
614 .map(|a| a.0.mining_speed_mult)
615 .unwrap_or(1.0);
616 } else {
617 tool_stats.reset();
618 }
619}
620
621#[cfg_attr(feature = "items", doc = "System added by [`MiningInputPlugin`].")]
622#[cfg_attr(
623 not(feature = "items"),
624 doc = "Mining input system; its automatic plugin adapter requires the `items` feature."
625)]
626#[cfg_attr(
630 feature = "items",
631 doc = "Added automatically by [`MiningInputPlugin`] — do not add this system manually when using that plugin."
632)]
633#[cfg_attr(
634 not(feature = "items"),
635 doc = "Without the `items` feature, add this system explicitly and initialize or supply [`ToolStats`] from game-owned code."
636)]
637pub fn mining_input_system<V: VoxelType>(
640 buttons: Res<ButtonInput<MouseButton>>,
641 camera_q: Query<&GlobalTransform, With<Camera3d>>,
642 manager: Res<ChunkManager>,
643 mut chunks: Query<&mut crate::chunk::Chunk<V>>,
644 mut state: ResMut<MiningState>,
645 config: Res<MiningConfig>,
646 tool_stats: Res<ToolStats>,
647 mut broken: MessageWriter<VoxelBroken>,
648 mut progress: MessageWriter<MiningProgress>,
649 mut modified: MessageWriter<ChunkModified>,
650 time: Res<Time>,
651) {
652 if !buttons.pressed(MouseButton::Left) {
653 stop_mining(&mut state);
654 return;
655 }
656
657 let Ok(cam_tf) = camera_q.single() else {
658 return;
659 };
660
661 let origin = cam_tf.translation();
662 let direction = cam_tf.forward().as_vec3();
663
664 let mut lens = chunks.transmute_lens::<&crate::chunk::Chunk<V>>();
666 let Some(hit) = super::raycast::raycast(origin, direction, 6.0, &manager, &lens.query()) else {
667 stop_mining(&mut state);
668 return;
669 };
670
671 let voxel_mining_level = lens
673 .query()
674 .get(
675 manager
676 .get_entity(hit.chunk_coord)
677 .unwrap_or(Entity::PLACEHOLDER),
678 )
679 .map(|chunk| {
680 let (x, y, z) = hit.local;
681 chunk.get(x, y, z).mining_level()
682 })
683 .unwrap_or(0);
684
685 if tool_stats.tool_level < voxel_mining_level {
686 stop_mining(&mut state);
687 return;
688 }
689
690 let effective_delta = time.delta_secs() * tool_stats.tool_speed;
692
693 let was_mining = state.target.is_some();
695
696 tick_mining(
697 hit.chunk_coord,
698 hit.local,
699 effective_delta,
700 &mut state,
701 &config,
702 &manager,
703 &mut chunks,
704 &mut broken,
705 &mut progress,
706 &mut modified,
707 );
708
709 if was_mining && state.target.is_none() {
712 use crate::chunk::CHUNK_SIZE;
713 let cs = CHUNK_SIZE as i32;
714 let vx = hit.chunk_coord.x * cs + hit.local.0 as i32;
715 let vy = hit.chunk_coord.y * cs + hit.local.1 as i32;
716 let vz = hit.chunk_coord.z * cs + hit.local.2 as i32;
717 let primary = IVec3::new(vx, vy, vz);
718 let center = Vec3::new(vx as f32 + 0.5, vy as f32 + 0.5, vz as f32 + 0.5);
719 let hit_pt = origin + hit.distance * direction.normalize();
720
721 for offset in quad_offsets(hit.face_normal, hit_pt, center) {
722 break_voxel(
723 primary + offset,
724 tool_stats.tool_level,
725 &manager,
726 &mut chunks,
727 &mut broken,
728 &mut modified,
729 );
730 }
731 }
732}
733
734#[cfg(test)]
737mod tests {
738 use super::*;
739
740 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
741 enum PatchVoxel {
742 #[default]
743 Air,
744 Soft,
745 Ore,
746 }
747 impl VoxelType for PatchVoxel {
748 fn name(&self) -> &'static str {
749 "patch voxel"
750 }
751 fn is_solid(&self) -> bool {
752 *self != Self::Air
753 }
754 fn color(&self) -> [f32; 4] {
755 [1.0; 4]
756 }
757 fn to_byte(&self) -> u8 {
758 *self as u8
759 }
760 fn from_byte(byte: u8) -> Self {
761 match byte {
762 1 => Self::Soft,
763 2 => Self::Ore,
764 _ => Self::Air,
765 }
766 }
767 fn mining_level(&self) -> u8 {
768 if *self == Self::Ore { 2 } else { 0 }
769 }
770 }
771
772 #[test]
773 fn patch_respects_each_voxel_tool_level_and_drop_events() {
774 for tool_level in [0, 2] {
775 let mut app = App::new();
776 app.add_plugins(MiningPlugin)
777 .init_resource::<Time>()
778 .init_resource::<ButtonInput<MouseButton>>()
779 .insert_resource(ChunkManager::new(32.0, 48.0))
780 .insert_resource(ToolStats {
781 tool_level,
782 tool_speed: 1.0,
783 })
784 .insert_resource(MiningConfig { break_time: 1.0 })
785 .add_message::<ChunkModified>()
786 .add_systems(Update, mining_input_system::<PatchVoxel>);
787 #[cfg(feature = "items")]
788 {
789 use crate::items::{DefaultItem, DropTable, DropsPlugin};
790 app.add_plugins(DropsPlugin::<DefaultItem>::new());
791 let mut table = app.world_mut().resource_mut::<DropTable<DefaultItem>>();
792 table.register(1, DefaultItem::RockFragment, 1, 1);
793 table.register(2, DefaultItem::RareMineral, 1, 1);
794 }
795 let mut chunk = Chunk::<PatchVoxel>::new();
796 for (x, y) in [(4, 4), (4, 5), (5, 5), (6, 5)] {
797 chunk.set(x, y, 4, PatchVoxel::Soft);
798 }
799 chunk.set(5, 4, 4, PatchVoxel::Ore);
800 let entity = app.world_mut().spawn(chunk).id();
801 app.world_mut()
802 .resource_mut::<ChunkManager>()
803 .register(IVec3::ZERO, entity);
804 app.world_mut().spawn((
805 Camera3d::default(),
806 GlobalTransform::from_translation(Vec3::new(4.75, 4.75, 8.0)),
807 ));
808 app.world_mut()
809 .resource_mut::<ButtonInput<MouseButton>>()
810 .press(MouseButton::Left);
811 for _ in 0..2 {
812 app.world_mut()
813 .resource_mut::<Time>()
814 .advance_by(std::time::Duration::from_millis(500));
815 app.update();
816 }
817 let chunk = app.world().get::<Chunk<PatchVoxel>>(entity).unwrap();
818 for (x, y) in [(4, 4), (4, 5), (5, 5)] {
819 assert_eq!(chunk.get(x, y, 4), PatchVoxel::Air);
820 }
821 assert_eq!(
822 chunk.get(5, 4, 4),
823 if tool_level == 0 {
824 PatchVoxel::Ore
825 } else {
826 PatchVoxel::Air
827 }
828 );
829 assert_eq!(
830 chunk.get(6, 5, 4),
831 PatchVoxel::Soft,
832 "outside patch must remain intact"
833 );
834 let messages = app.world().resource::<Messages<VoxelBroken>>();
835 let mut cursor = messages.get_cursor();
836 let events: Vec<_> = cursor.read(messages).collect();
837 assert_eq!(events.len(), if tool_level == 0 { 3 } else { 4 });
838 assert_eq!(
839 events.iter().filter(|e| e.voxel_byte == 2).count(),
840 usize::from(tool_level == 2)
841 );
842 app.world_mut()
843 .resource_mut::<ButtonInput<MouseButton>>()
844 .clear();
845 app.update();
846 #[cfg(feature = "items")]
847 {
848 use crate::items::{DefaultItem, DroppedItem};
849 let mut query = app.world_mut().query::<&DroppedItem<DefaultItem>>();
850 let drops: Vec<_> = query.iter(app.world()).collect();
851 assert_eq!(drops.len(), if tool_level == 0 { 3 } else { 4 });
852 assert_eq!(
853 drops
854 .iter()
855 .filter(|d| d.item == DefaultItem::RareMineral)
856 .count(),
857 usize::from(tool_level == 2)
858 );
859 }
860 }
861 }
862
863 fn default_config() -> MiningConfig {
864 MiningConfig { break_time: 1.5 }
865 }
866
867 #[test]
870 fn stop_mining_resets_state() {
871 let mut state = MiningState {
872 target: Some((IVec3::ZERO, (1, 2, 3))),
873 elapsed: 0.8,
874 progress: 0.5,
875 effective_break_time: 1.0,
876 };
877 stop_mining(&mut state);
878 assert!(state.target.is_none());
879 assert_eq!(state.elapsed, 0.0);
880 assert_eq!(state.progress, 0.0);
881 }
882
883 #[test]
886 fn test_mining_progress_accumulates() {
887 let config = default_config();
888 let mut state = MiningState::default();
889
890 let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
892
893 if state.target != Some(target) {
895 state.elapsed = 0.0;
896 state.progress = 0.0;
897 state.target = Some(target);
898 }
899 state.elapsed += 0.3;
900 state.progress = (state.elapsed / config.break_time).min(1.0);
901
902 assert!((state.elapsed - 0.3).abs() < f32::EPSILON);
903
904 state.elapsed += 0.4;
906 state.progress = (state.elapsed / config.break_time).min(1.0);
907
908 assert!((state.elapsed - 0.7).abs() < f32::EPSILON);
909 assert!(state.progress > 0.0 && state.progress < 1.0);
910 }
911
912 #[test]
913 fn test_mining_resets_on_target_change() {
914 let config = default_config();
915 let mut state = MiningState::default();
916
917 let target_a = (IVec3::ZERO, (0usize, 0usize, 0usize));
918 let target_b = (IVec3::ONE, (1usize, 1usize, 1usize));
919
920 state.target = Some(target_a);
922 state.elapsed += 0.5;
923 state.progress = (state.elapsed / config.break_time).min(1.0);
924
925 assert!(state.elapsed > 0.0);
926
927 if state.target != Some(target_b) {
929 state.elapsed = 0.0;
930 state.progress = 0.0;
931 state.target = Some(target_b);
932 }
933
934 assert_eq!(state.elapsed, 0.0);
935 assert_eq!(state.progress, 0.0);
936 assert_eq!(state.target, Some(target_b));
937 }
938
939 #[test]
940 fn test_mining_completes_at_break_time() {
941 let config = default_config();
942 let mut state = MiningState::default();
943
944 let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
946 state.target = Some(target);
947
948 let mut completed = false;
949 let tick = 0.5_f32;
950 for _ in 0..10 {
951 state.elapsed += tick;
952 state.progress = (state.elapsed / config.break_time).min(1.0);
953 if state.progress >= 1.0 {
954 completed = true;
955 break;
956 }
957 }
958
959 assert!(completed, "mining should complete within 10 ticks of 0.5s");
960 assert_eq!(state.progress, 1.0);
961 }
962
963 #[test]
964 fn progress_is_clamped_to_one() {
965 let config = default_config();
966 let mut state = MiningState::default();
967
968 state.elapsed = 99.0;
970 state.progress = (state.elapsed / config.break_time).min(1.0);
971
972 assert_eq!(state.progress, 1.0);
973 }
974
975 fn compute_effective_break_time(break_time: f32, hardness: f32) -> f32 {
977 if hardness > 0.0 {
978 break_time * hardness
979 } else {
980 f32::MAX
981 }
982 }
983
984 fn gated_effective_delta(
988 delta: f32,
989 tool_level: u8,
990 tool_speed: f32,
991 voxel_mining_level: u8,
992 ) -> Option<f32> {
993 if tool_level < voxel_mining_level {
994 None
995 } else {
996 Some(delta * tool_speed)
997 }
998 }
999
1000 #[test]
1001 fn hardness_zero_is_unbreakable() {
1002 let config = default_config();
1003 let hardness = 0.0;
1004 let effective = compute_effective_break_time(config.break_time, hardness);
1005
1006 assert_eq!(effective, f32::MAX);
1007
1008 let mut state = MiningState {
1009 target: Some((IVec3::ZERO, (0, 0, 0))),
1010 elapsed: 0.0,
1011 progress: 0.0,
1012 effective_break_time: effective,
1013 };
1014
1015 for _ in 0..1_000 {
1017 state.elapsed += 10.0;
1018 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
1019 }
1020
1021 assert!(state.progress < 1.0);
1022 assert!(state.progress < f32::EPSILON * 1_000.0);
1023 assert_eq!(state.effective_break_time, f32::MAX);
1027 }
1028
1029 #[test]
1030 fn hardness_scales_break_time() {
1031 let break_time = 1.5_f32;
1032 let hardness = 3.0_f32;
1033 let effective = compute_effective_break_time(break_time, hardness);
1034 assert!((effective - 4.5).abs() < f32::EPSILON);
1035 }
1036
1037 #[test]
1038 fn tool_level_below_mining_level_blocks_progress() {
1039 let delta = gated_effective_delta(0.1, 1, 1.0, 2);
1040 assert!(
1041 delta.is_none(),
1042 "tool_level=1 must not mine voxel with mining_level=2"
1043 );
1044
1045 let mut state = MiningState {
1047 target: Some((IVec3::ZERO, (0, 0, 0))),
1048 elapsed: 0.4,
1049 progress: 0.2,
1050 effective_break_time: 1.5,
1051 };
1052 stop_mining(&mut state);
1053 assert!(state.target.is_none());
1054 assert_eq!(state.elapsed, 0.0);
1055 assert_eq!(state.progress, 0.0);
1056 }
1057
1058 #[test]
1059 fn tool_level_meets_requirement_progresses() {
1060 let config = default_config();
1061 let delta = gated_effective_delta(0.1, 1, 1.0, 1)
1062 .expect("tool_level=1 must satisfy mining_level=1 gate");
1063 assert!((delta - 0.1).abs() < f32::EPSILON);
1064
1065 let hardness = 1.0_f32;
1066 let effective = compute_effective_break_time(config.break_time, hardness);
1067 let mut state = MiningState {
1068 target: Some((IVec3::ZERO, (0, 0, 0))),
1069 elapsed: 0.0,
1070 progress: 0.0,
1071 effective_break_time: effective,
1072 };
1073
1074 for _ in 0..3 {
1075 state.elapsed += delta;
1076 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
1077 }
1078
1079 assert!(state.progress > 0.0);
1080 assert!(state.progress < 1.0);
1081 }
1082
1083 #[test]
1084 fn tool_speed_scales_delta() {
1085 let break_time = 1.5_f32;
1086 let hardness = 1.0_f32;
1087 let tool_speed = 2.0_f32;
1088 let frame_delta = 0.1_f32;
1089
1090 let effective_delta = gated_effective_delta(frame_delta, 0, tool_speed, 0)
1091 .expect("level-0 voxel is breakable by bare hands");
1092 assert!(
1093 (effective_delta - 0.2).abs() < f32::EPSILON,
1094 "tool_speed=2.0 must double the per-call delta"
1095 );
1096
1097 let effective_break_time = compute_effective_break_time(break_time, hardness);
1098 let mut state = MiningState {
1099 target: Some((IVec3::ZERO, (0, 0, 0))),
1100 elapsed: 0.0,
1101 progress: 0.0,
1102 effective_break_time,
1103 };
1104
1105 let frames_for_half_time = (0.75 / frame_delta).ceil() as usize;
1107 for _ in 0..frames_for_half_time {
1108 state.elapsed += effective_delta;
1109 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
1110 }
1111
1112 assert!(
1113 state.progress >= 1.0,
1114 "tool_speed=2.0 must reach progress=1.0 at ~half the nominal break time \
1115 (expected >=1.0, got {})",
1116 state.progress
1117 );
1118 }
1119}