voxel_framework/world/mining.rs
1//! Voxel mining (block-breaking) API.
2//!
3//! # Design — pure functions, no implicit systems
4//!
5//! All logic lives in free functions ([`tick_mining`], [`stop_mining`]) so
6//! that game code retains full control over when and how mining occurs.
7//! [`MiningPlugin`] only registers the required resources and message types;
8//! it adds **no** systems of its own.
9//!
10//! # Integration pattern
11//!
12//! ```no_run
13//! # use bevy::prelude::*;
14//! # use voxel_framework::world::mining::{MiningPlugin, MiningConfig, MiningState,
15//! # MiningProgress, VoxelBroken, tick_mining, stop_mining};
16//! # use voxel_framework::world::{ChunkManager, ChunkModified};
17//! # use voxel_framework::chunk::Chunk;
18//! # use voxel_framework::voxel::DefaultVoxel;
19//! // 1. Add the plugin once when building the App.
20//! // App::new().add_plugins(MiningPlugin);
21//!
22//! // 2. In your input system, call tick_mining every frame while the
23//! // mine button is held, or stop_mining when it is released.
24//! fn my_mining_system(
25//! mut state: ResMut<MiningState>,
26//! config: Res<MiningConfig>,
27//! manager: Res<ChunkManager>,
28//! mut chunks: Query<&mut Chunk<DefaultVoxel>>,
29//! mut broken: MessageWriter<VoxelBroken>,
30//! mut progress: MessageWriter<MiningProgress>,
31//! mut modified: MessageWriter<ChunkModified>,
32//! time: Res<Time>,
33//! ) {
34//! let mining = true; // replace with real input check
35//! if mining {
36//! tick_mining(
37//! IVec3::ZERO, (8, 8, 8),
38//! time.delta_secs(),
39//! &mut state, &config, &manager,
40//! &mut chunks, &mut broken, &mut progress, &mut modified,
41//! );
42//! } else {
43//! stop_mining(&mut state);
44//! }
45//! }
46//! ```
47
48use 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};
60
61// ─── Resources ───────────────────────────────────────────────────────────────
62
63/// Configuration for the mining system.
64///
65/// Insert this resource before adding [`MiningPlugin`], or mutate it at
66/// runtime to adjust difficulty.
67#[derive(Resource, Debug, Clone)]
68pub struct MiningConfig {
69 /// Time in seconds required to break a single voxel.
70 ///
71 /// Must be greater than zero. **Default: `1.5` seconds.**
72 pub break_time: f32,
73}
74
75impl Default for MiningConfig {
76 fn default() -> Self {
77 Self { break_time: 1.5 }
78 }
79}
80
81/// Runtime state for the mining system.
82///
83/// Tracks which voxel is currently being mined and how much time has
84/// accumulated toward breaking it. There is at most one active target at a
85/// time; switching targets resets elapsed time automatically inside
86/// [`tick_mining`].
87///
88/// Call [`stop_mining`] whenever the mine button is released — failing to do
89/// so leaves stale progress that will carry over to the next target.
90#[derive(Resource, Debug)]
91pub struct MiningState {
92 /// The chunk coordinate and local voxel index `(x, y, z)` currently being
93 /// mined, or `None` when no mining is in progress.
94 pub target: Option<(IVec3, (usize, usize, usize))>,
95 /// Accumulated break time in seconds, in the range `[0.0, effective_break_time]`.
96 pub elapsed: f32,
97 /// Normalised break progress in the range `[0.0, 1.0]`.
98 ///
99 /// Equals `elapsed / effective_break_time`. Reaches `1.0` when the voxel breaks.
100 pub progress: f32,
101 /// Cached effective break time for the current target, in seconds.
102 ///
103 /// Computed once per target as `config.break_time * voxel.hardness()`.
104 /// Initialised to `1.0` until the first mining target is set.
105 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/// Active-tool statistics derived from the hotbar selection each frame.
120///
121#[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 /// Minimum tool level required to mine a voxel.
132 ///
133 /// Matched against [`crate::voxel::VoxelType::mining_level`]:
134 /// if `tool_level < voxel.mining_level()`, mining makes no progress.
135 pub tool_level: u8,
136 /// Mining speed multiplier for the active tool.
137 ///
138 /// The effective break time is divided by this value (`2.0` = twice as fast).
139 pub tool_speed: f32,
140}
141
142impl ToolStats {
143 /// Resets stats to bare-hands defaults (level 0, speed 1.0).
144 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// ─── Messages ────────────────────────────────────────────────────────────────
160
161/// Message fired once when a voxel's break time is fully elapsed.
162///
163/// Emitted by [`tick_mining`] in the same frame the voxel is destroyed.
164/// Systems that react to block destruction (e.g. particle effects, inventory
165/// updates) should read this message.
166#[derive(Message, Debug, Clone)]
167pub struct VoxelBroken {
168 /// Chunk-grid coordinate of the chunk that contained the broken voxel.
169 pub chunk_coord: IVec3,
170 /// Local voxel index `(x, y, z)` within the chunk. Each component is in
171 /// `[0, CHUNK_SIZE)`.
172 pub local: (usize, usize, usize),
173 /// World-space center of the broken voxel.
174 pub world_pos: Vec3,
175 /// Stable byte id of the voxel that was destroyed.
176 ///
177 /// Captured before the voxel is replaced with [`VoxelType::air`], so
178 /// content and drop systems can map the destroyed block to author-defined
179 /// item drops without guessing from position.
180 pub voxel_byte: u8,
181}
182
183/// Message sent every frame while a voxel is being mined.
184///
185/// Useful for driving crack-overlay animations, progress bars, or audio
186/// feedback. Emitted by [`tick_mining`] on every frame where mining is
187/// active, including the frame the voxel breaks (where `progress` is `1.0`).
188#[derive(Message, Debug, Clone)]
189pub struct MiningProgress {
190 /// Normalised break progress in `[0.0, 1.0]`.
191 ///
192 /// `0.0` on the first frame, `1.0` on the frame the voxel breaks.
193 pub progress: f32,
194 /// World-space center of the voxel being mined.
195 pub world_pos: Vec3,
196}
197
198// ─── Free functions ───────────────────────────────────────────────────────────
199
200/// Breaks a single voxel at world-voxel coordinates `world_voxel` if it is
201/// solid and its chunk is loaded. Emits [`VoxelBroken`], [`ChunkModified`],
202/// and border-neighbor notifications.
203fn break_voxel<V: VoxelType>(
204 world_voxel: IVec3,
205 manager: &ChunkManager,
206 chunks: &mut Query<&mut Chunk<V>>,
207 broken: &mut MessageWriter<VoxelBroken>,
208 modified: &mut MessageWriter<ChunkModified>,
209) {
210 use crate::chunk::CHUNK_SIZE;
211 let cs = CHUNK_SIZE as i32;
212 let chunk_coord = IVec3::new(
213 world_voxel.x.div_euclid(cs),
214 world_voxel.y.div_euclid(cs),
215 world_voxel.z.div_euclid(cs),
216 );
217 let local = (
218 world_voxel.x.rem_euclid(cs) as usize,
219 world_voxel.y.rem_euclid(cs) as usize,
220 world_voxel.z.rem_euclid(cs) as usize,
221 );
222
223 let Some(entity) = manager.get_entity(chunk_coord) else {
224 return;
225 };
226 let Ok(mut chunk) = chunks.get_mut(entity) else {
227 return;
228 };
229 let voxel = chunk.get(local.0, local.1, local.2);
230 if !voxel.is_solid() {
231 return;
232 }
233 let voxel_byte = voxel.to_byte();
234 chunk.set(local.0, local.1, local.2, V::air());
235 drop(chunk);
236
237 let wp = voxel_world_pos(chunk_coord, local);
238 broken.write(VoxelBroken {
239 chunk_coord,
240 local,
241 world_pos: wp,
242 voxel_byte,
243 });
244 modified.write(ChunkModified(chunk_coord));
245 notify_border_neighbors(chunk_coord, local, modified);
246}
247
248/// Returns the three extra world-voxel offsets that form a 2×2 square on the
249/// hit face together with the primary voxel.
250///
251/// The two tangent axes are determined by `face_normal`. For each axis the
252/// sign of the offset is chosen so that the 2×2 quad lies in the quadrant
253/// where the ray actually entered the face (using `hit_point` vs
254/// `voxel_center`).
255fn quad_offsets(face_normal: Vec3, hit_point: Vec3, voxel_center: Vec3) -> [IVec3; 3] {
256 let sign = |coord: f32, center: f32| -> i32 { if coord >= center { 1 } else { -1 } };
257 let (du, dv) = if face_normal.x.abs() > 0.5 {
258 // X face → perpendicular plane is YZ
259 (
260 IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
261 IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
262 )
263 } else if face_normal.y.abs() > 0.5 {
264 // Y face → perpendicular plane is XZ
265 (
266 IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
267 IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
268 )
269 } else {
270 // Z face (or zero normal) → perpendicular plane is XY
271 (
272 IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
273 IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
274 )
275 };
276 [du, dv, du + dv]
277}
278
279/// Sends [`ChunkModified`] for any neighboring chunks whose border shares the
280/// face of the voxel at `local` within `chunk_coord`.
281///
282/// When a voxel on the edge of a chunk is added or removed, the adjacent
283/// chunk's mesh must also be regenerated — its border faces were previously
284/// culled by this voxel and are now exposed (or vice versa for placement).
285fn notify_border_neighbors(
286 chunk_coord: IVec3,
287 local: (usize, usize, usize),
288 modified: &mut MessageWriter<ChunkModified>,
289) {
290 use crate::chunk::CHUNK_SIZE;
291 let (x, y, z) = local;
292 let offsets: [(usize, IVec3); 6] = [
293 (x, IVec3::NEG_X),
294 (CHUNK_SIZE - 1 - x, IVec3::X),
295 (y, IVec3::NEG_Y),
296 (CHUNK_SIZE - 1 - y, IVec3::Y),
297 (z, IVec3::NEG_Z),
298 (CHUNK_SIZE - 1 - z, IVec3::Z),
299 ];
300 for (dist, dir) in offsets {
301 if dist == 0 {
302 modified.write(ChunkModified(chunk_coord + dir));
303 }
304 }
305}
306
307/// Compute the world-space center of a voxel given its chunk coord and local index.
308fn voxel_world_pos(chunk_coord: IVec3, local: (usize, usize, usize)) -> Vec3 {
309 let chunk_origin = chunk_coord.as_vec3() * crate::chunk::CHUNK_SIZE as f32;
310 chunk_origin
311 + Vec3::new(
312 local.0 as f32 + 0.5,
313 local.1 as f32 + 0.5,
314 local.2 as f32 + 0.5,
315 )
316}
317
318/// Advance mining by one frame toward breaking the target voxel.
319///
320/// Call this **every frame** while the mine button is held. When the
321/// accumulated time reaches `config.break_time` the function:
322///
323/// 1. Sets the target voxel to air (if the chunk is loaded).
324/// 2. Writes a [`VoxelBroken`] message.
325/// 3. Writes a [`ChunkModified`] message to trigger remeshing.
326/// 4. Resets `state` so a new target can start fresh.
327///
328/// A [`MiningProgress`] message is written on **every** call, including the
329/// break frame.
330///
331/// If `target_chunk` / `target_local` differs from the previous frame, elapsed
332/// time is reset to zero automatically — no need to call [`stop_mining`] when
333/// switching targets mid-frame.
334///
335/// # Parameters
336///
337/// - `target_chunk` — Chunk-grid coordinate of the chunk containing the target
338/// voxel.
339/// - `target_local` — Local `(x, y, z)` voxel index within the chunk.
340/// - `delta_secs` — Frame delta time in seconds (typically `time.delta_secs()`).
341/// - `state` — Mutable reference to the shared [`MiningState`] resource.
342/// - `config` — Read-only mining configuration (break time).
343/// - `manager` — Chunk registry used to look up the chunk entity.
344/// - `chunks` — Mutable query used to set voxels to air on break.
345/// - `broken` — Message writer for [`VoxelBroken`].
346/// - `progress_writer` — Message writer for [`MiningProgress`].
347/// - `modified` — Message writer for [`crate::world::ChunkModified`].
348///
349/// # Examples
350///
351/// ```no_run
352/// # use bevy::prelude::*;
353/// # use voxel_framework::world::mining::{MiningConfig, MiningState, MiningProgress, VoxelBroken, tick_mining};
354/// # use voxel_framework::world::{ChunkManager, ChunkModified};
355/// # use voxel_framework::chunk::Chunk;
356/// # use voxel_framework::voxel::DefaultVoxel;
357/// fn my_system(
358/// mut state: ResMut<MiningState>,
359/// config: Res<MiningConfig>,
360/// manager: Res<ChunkManager>,
361/// mut chunks: Query<&mut Chunk<DefaultVoxel>>,
362/// mut broken: MessageWriter<VoxelBroken>,
363/// mut progress: MessageWriter<MiningProgress>,
364/// mut modified: MessageWriter<ChunkModified>,
365/// time: Res<Time>,
366/// ) {
367/// tick_mining(
368/// IVec3::ZERO, (4, 0, 4),
369/// time.delta_secs(),
370/// &mut state, &config, &manager,
371/// &mut chunks, &mut broken, &mut progress, &mut modified,
372/// );
373/// }
374/// ```
375#[allow(clippy::too_many_arguments)]
376pub fn tick_mining<V: VoxelType>(
377 target_chunk: IVec3,
378 target_local: (usize, usize, usize),
379 delta_secs: f32,
380 state: &mut MiningState,
381 config: &MiningConfig,
382 manager: &ChunkManager,
383 chunks: &mut Query<&mut Chunk<V>>,
384 broken: &mut MessageWriter<VoxelBroken>,
385 progress_writer: &mut MessageWriter<MiningProgress>,
386 modified: &mut MessageWriter<ChunkModified>,
387) {
388 // Reset elapsed when target changes and sample the new voxel's hardness.
389 if state.target != Some((target_chunk, target_local)) {
390 let hardness = manager
391 .get_entity(target_chunk)
392 .and_then(|e| chunks.get(e).ok())
393 .map(|chunk| {
394 let (x, y, z) = target_local;
395 chunk.get(x, y, z).hardness()
396 })
397 .unwrap_or(1.0);
398
399 // Hardness 0.0 means unbreakable — use a very large break time.
400 state.effective_break_time = if hardness > 0.0 {
401 config.break_time * hardness
402 } else {
403 f32::MAX
404 };
405 state.elapsed = 0.0;
406 state.progress = 0.0;
407 state.target = Some((target_chunk, target_local));
408 }
409
410 state.elapsed += delta_secs;
411 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
412
413 let world_pos = voxel_world_pos(target_chunk, target_local);
414
415 progress_writer.write(MiningProgress {
416 progress: state.progress,
417 world_pos,
418 });
419
420 if state.progress >= 1.0 && state.effective_break_time < f32::MAX {
421 // Destroy the voxel if the chunk is loaded.
422 let mut voxel_byte = V::air().to_byte();
423 if let Some(entity) = manager.get_entity(target_chunk) {
424 if let Ok(mut chunk) = chunks.get_mut(entity) {
425 let (x, y, z) = target_local;
426 voxel_byte = chunk.get(x, y, z).to_byte();
427 chunk.set(x, y, z, V::air());
428 }
429 }
430
431 broken.write(VoxelBroken {
432 chunk_coord: target_chunk,
433 local: target_local,
434 world_pos,
435 voxel_byte,
436 });
437
438 modified.write(ChunkModified(target_chunk));
439 notify_border_neighbors(target_chunk, target_local, modified);
440
441 // Reset state.
442 state.target = None;
443 state.elapsed = 0.0;
444 state.progress = 0.0;
445 }
446}
447
448/// Stop mining and reset all accumulated progress.
449///
450/// Call this whenever the mine button is released. Failing to call
451/// `stop_mining` means any partial progress persists, and the next target
452/// will appear to start partially broken.
453///
454/// # Examples
455///
456/// ```no_run
457/// # use voxel_framework::world::mining::{MiningState, stop_mining};
458/// fn on_button_release(mut state: bevy::prelude::ResMut<MiningState>) {
459/// stop_mining(&mut state);
460/// }
461/// ```
462pub fn stop_mining(state: &mut MiningState) {
463 state.target = None;
464 state.elapsed = 0.0;
465 state.progress = 0.0;
466}
467
468// ─── Plugin ───────────────────────────────────────────────────────────────────
469
470/// Bevy plugin that registers the mining subsystem.
471///
472/// Adds the following to the [`bevy::prelude::App`]:
473///
474/// - [`MiningConfig`] resource (initialised with defaults — `break_time: 1.5 s`)
475/// - [`MiningState`] resource (initialised at default / idle)
476/// - [`VoxelBroken`] message type
477/// - [`MiningProgress`] message type
478///
479/// Does **not** add any systems. Game code is responsible for calling
480/// [`tick_mining`] and [`stop_mining`] from its own update systems.
481pub struct MiningPlugin;
482
483impl Plugin for MiningPlugin {
484 fn build(&self, app: &mut App) {
485 app.init_resource::<MiningConfig>();
486 app.init_resource::<MiningState>();
487 app.add_message::<VoxelBroken>();
488 app.add_message::<MiningProgress>();
489 }
490}
491
492// ─── MiningInputPlugin ────────────────────────────────────────────────────────
493//
494// `MiningInputPlugin` and its companion `hotbar_to_tool_system` are gated on the
495// `items` feature because they require `ItemType`, `HotbarState`,
496// `ContainerComponent`, and `PrimaryContainer` — all of which live in
497// `crate::items`. Disabling the feature compiles them out cleanly.
498
499/// Convenience plugin that wires mouse input to the mining API automatically.
500///
501/// `MiningInputPlugin<V, I>` adds two [`Update`] systems:
502///
503/// 1. `hotbar_to_tool_system` — reads the active hotbar slot from [`Inventory<I>`](crate::items::Inventory)
504/// and updates [`ToolStats`] with the slot's tool level and speed each frame.
505/// 2. `mining_input_system` — raycasts from the active [`Camera3d`] (max
506/// `6.0` world units). While the **left mouse button** is held and the ray
507/// hits a solid voxel whose [`crate::voxel::VoxelType::mining_level`] is
508/// satisfied by the current [`ToolStats::tool_level`], calls [`tick_mining`]
509/// to accumulate break progress. When the button is released (or no voxel is
510/// hit, or the tool level is too low), calls [`stop_mining`].
511///
512/// # Prerequisites
513///
514/// [`MiningPlugin`] must be added **before** this plugin so that the required
515/// resources ([`MiningState`], [`MiningConfig`]) and message channels
516/// ([`VoxelBroken`], [`MiningProgress`]) are already registered.
517///
518/// A player entity with [`crate::items::inventory::ContainerComponent<I>`] and
519/// [`crate::items::inventory::PrimaryContainer`] must be present (typically spawned
520/// in a `Startup` system).
521///
522/// # Example
523///
524/// ```no_run
525/// use bevy::prelude::*;
526/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
527/// use voxel_framework::world::mining::MiningInputPlugin;
528/// use voxel_framework::voxel::DefaultTerrainVoxel;
529/// use voxel_framework::items::DefaultItem;
530///
531/// App::new()
532/// .add_plugins(DefaultPlugins)
533/// .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
534/// .add_plugins(MiningInputPlugin::<DefaultTerrainVoxel, DefaultItem>::new())
535/// .run();
536/// ```
537#[cfg(feature = "items")]
538pub struct MiningInputPlugin<V: VoxelType, I: ItemType> {
539 _m: std::marker::PhantomData<(V, I)>,
540}
541
542#[cfg(feature = "items")]
543impl<V: VoxelType, I: ItemType> MiningInputPlugin<V, I> {
544 /// Creates a new [`MiningInputPlugin`] for voxel type `V` and item type `I`.
545 pub fn new() -> Self {
546 Self {
547 _m: std::marker::PhantomData,
548 }
549 }
550}
551
552#[cfg(feature = "items")]
553impl<V: VoxelType, I: ItemType> Default for MiningInputPlugin<V, I> {
554 fn default() -> Self {
555 Self::new()
556 }
557}
558
559#[cfg(feature = "items")]
560impl<V: VoxelType, I: ItemType> Plugin for MiningInputPlugin<V, I> {
561 fn build(&self, app: &mut App) {
562 app.init_resource::<ToolStats>();
563 app.add_systems(
564 Update,
565 (hotbar_to_tool_system::<I>, mining_input_system::<V>).chain(),
566 );
567 }
568}
569
570/// Updates [`ToolStats`] from the active hotbar slot each frame.
571///
572/// Reads the [`ContainerComponent`] on the [`PrimaryContainer`] entity.
573/// If no such entity exists, resets to bare-hands stats silently.
574///
575/// Added automatically by [`MiningInputPlugin`] — do not add manually.
576#[cfg(feature = "items")]
577pub fn hotbar_to_tool_system<I: ItemType>(
578 hotbar: Res<HotbarState>,
579 container_query: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
580 mut tool_stats: ResMut<ToolStats>,
581 applied: Option<Res<AppliedEffectModifiers>>,
582) {
583 let Ok(container) = container_query.single() else {
584 tool_stats.reset();
585 return;
586 };
587 let active_slot = hotbar.selected;
588 if let Some(slot) = container.0.slots.get(active_slot).and_then(|s| s.as_ref()) {
589 tool_stats.tool_level = slot.item.tool_level();
590 tool_stats.tool_speed = slot.item.tool_speed()
591 * applied
592 .as_deref()
593 .map(|a| a.0.mining_speed_mult)
594 .unwrap_or(1.0);
595 } else {
596 tool_stats.reset();
597 }
598}
599
600#[cfg_attr(feature = "items", doc = "System added by [`MiningInputPlugin`].")]
601#[cfg_attr(
602 not(feature = "items"),
603 doc = "Mining input system; its automatic plugin adapter requires the `items` feature."
604)]
605///
606/// Raycasts from the camera and drives [`tick_mining`] / [`stop_mining`] based
607/// on left-mouse-button state and [`ToolStats`].
608#[cfg_attr(
609 feature = "items",
610 doc = "Added automatically by [`MiningInputPlugin`] — do not add this system manually when using that plugin."
611)]
612#[cfg_attr(
613 not(feature = "items"),
614 doc = "Without the `items` feature, add this system explicitly and initialize or supply [`ToolStats`] from game-owned code."
615)]
616pub fn mining_input_system<V: VoxelType>(
617 buttons: Res<ButtonInput<MouseButton>>,
618 camera_q: Query<&GlobalTransform, With<Camera3d>>,
619 manager: Res<ChunkManager>,
620 mut chunks: Query<&mut crate::chunk::Chunk<V>>,
621 mut state: ResMut<MiningState>,
622 config: Res<MiningConfig>,
623 tool_stats: Res<ToolStats>,
624 mut broken: MessageWriter<VoxelBroken>,
625 mut progress: MessageWriter<MiningProgress>,
626 mut modified: MessageWriter<ChunkModified>,
627 time: Res<Time>,
628) {
629 if !buttons.pressed(MouseButton::Left) {
630 stop_mining(&mut state);
631 return;
632 }
633
634 let Ok(cam_tf) = camera_q.single() else {
635 return;
636 };
637
638 let origin = cam_tf.translation();
639 let direction = cam_tf.forward().as_vec3();
640
641 // `transmute_lens` gives a read-only view without a second conflicting query.
642 let mut lens = chunks.transmute_lens::<&crate::chunk::Chunk<V>>();
643 let Some(hit) = super::raycast::raycast(origin, direction, 6.0, &manager, &lens.query()) else {
644 stop_mining(&mut state);
645 return;
646 };
647
648 // Check that the active tool can mine this voxel type.
649 let voxel_mining_level = lens
650 .query()
651 .get(
652 manager
653 .get_entity(hit.chunk_coord)
654 .unwrap_or(Entity::PLACEHOLDER),
655 )
656 .map(|chunk| {
657 let (x, y, z) = hit.local;
658 chunk.get(x, y, z).mining_level()
659 })
660 .unwrap_or(0);
661
662 if tool_stats.tool_level < voxel_mining_level {
663 stop_mining(&mut state);
664 return;
665 }
666
667 // Apply tool speed to the effective delta — faster tools reduce break time.
668 let effective_delta = time.delta_secs() * tool_stats.tool_speed;
669
670 // Snapshot before tick so we can detect the break event below.
671 let was_mining = state.target.is_some();
672
673 tick_mining(
674 hit.chunk_coord,
675 hit.local,
676 effective_delta,
677 &mut state,
678 &config,
679 &manager,
680 &mut chunks,
681 &mut broken,
682 &mut progress,
683 &mut modified,
684 );
685
686 // If the primary block just broke, also break the 3 adjacent blocks that
687 // form a 2×2 square on the struck face.
688 if was_mining && state.target.is_none() {
689 use crate::chunk::CHUNK_SIZE;
690 let cs = CHUNK_SIZE as i32;
691 let vx = hit.chunk_coord.x * cs + hit.local.0 as i32;
692 let vy = hit.chunk_coord.y * cs + hit.local.1 as i32;
693 let vz = hit.chunk_coord.z * cs + hit.local.2 as i32;
694 let primary = IVec3::new(vx, vy, vz);
695 let center = Vec3::new(vx as f32 + 0.5, vy as f32 + 0.5, vz as f32 + 0.5);
696 let hit_pt = origin + hit.distance * direction.normalize();
697
698 for offset in quad_offsets(hit.face_normal, hit_pt, center) {
699 break_voxel(
700 primary + offset,
701 &manager,
702 &mut chunks,
703 &mut broken,
704 &mut modified,
705 );
706 }
707 }
708}
709
710// ─── Tests ────────────────────────────────────────────────────────────────────
711
712#[cfg(test)]
713mod tests {
714 use super::*;
715
716 fn default_config() -> MiningConfig {
717 MiningConfig { break_time: 1.5 }
718 }
719
720 // ── stop_mining ──────────────────────────────────────────────────────────
721
722 #[test]
723 fn stop_mining_resets_state() {
724 let mut state = MiningState {
725 target: Some((IVec3::ZERO, (1, 2, 3))),
726 elapsed: 0.8,
727 progress: 0.5,
728 effective_break_time: 1.0,
729 };
730 stop_mining(&mut state);
731 assert!(state.target.is_none());
732 assert_eq!(state.elapsed, 0.0);
733 assert_eq!(state.progress, 0.0);
734 }
735
736 // ── progress calculation ──────────────────────────────────────────────────
737
738 #[test]
739 fn test_mining_progress_accumulates() {
740 let config = default_config();
741 let mut state = MiningState::default();
742
743 // Manually simulate two ticks without Bevy context.
744 let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
745
746 // First tick: set target and advance elapsed.
747 if state.target != Some(target) {
748 state.elapsed = 0.0;
749 state.progress = 0.0;
750 state.target = Some(target);
751 }
752 state.elapsed += 0.3;
753 state.progress = (state.elapsed / config.break_time).min(1.0);
754
755 assert!((state.elapsed - 0.3).abs() < f32::EPSILON);
756
757 // Second tick: same target, keep accumulating.
758 state.elapsed += 0.4;
759 state.progress = (state.elapsed / config.break_time).min(1.0);
760
761 assert!((state.elapsed - 0.7).abs() < f32::EPSILON);
762 assert!(state.progress > 0.0 && state.progress < 1.0);
763 }
764
765 #[test]
766 fn test_mining_resets_on_target_change() {
767 let config = default_config();
768 let mut state = MiningState::default();
769
770 let target_a = (IVec3::ZERO, (0usize, 0usize, 0usize));
771 let target_b = (IVec3::ONE, (1usize, 1usize, 1usize));
772
773 // Mine target A for a bit.
774 state.target = Some(target_a);
775 state.elapsed += 0.5;
776 state.progress = (state.elapsed / config.break_time).min(1.0);
777
778 assert!(state.elapsed > 0.0);
779
780 // Switch to target B — should reset.
781 if state.target != Some(target_b) {
782 state.elapsed = 0.0;
783 state.progress = 0.0;
784 state.target = Some(target_b);
785 }
786
787 assert_eq!(state.elapsed, 0.0);
788 assert_eq!(state.progress, 0.0);
789 assert_eq!(state.target, Some(target_b));
790 }
791
792 #[test]
793 fn test_mining_completes_at_break_time() {
794 let config = default_config();
795 let mut state = MiningState::default();
796
797 // Simulate ticks until elapsed >= break_time.
798 let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
799 state.target = Some(target);
800
801 let mut completed = false;
802 let tick = 0.5_f32;
803 for _ in 0..10 {
804 state.elapsed += tick;
805 state.progress = (state.elapsed / config.break_time).min(1.0);
806 if state.progress >= 1.0 {
807 completed = true;
808 break;
809 }
810 }
811
812 assert!(completed, "mining should complete within 10 ticks of 0.5s");
813 assert_eq!(state.progress, 1.0);
814 }
815
816 #[test]
817 fn progress_is_clamped_to_one() {
818 let config = default_config();
819 let mut state = MiningState::default();
820
821 // Way more elapsed than break_time.
822 state.elapsed = 99.0;
823 state.progress = (state.elapsed / config.break_time).min(1.0);
824
825 assert_eq!(state.progress, 1.0);
826 }
827
828 // Mirrors the production formula at `tick_mining` (mining.rs:376-388).
829 fn compute_effective_break_time(break_time: f32, hardness: f32) -> f32 {
830 if hardness > 0.0 {
831 break_time * hardness
832 } else {
833 f32::MAX
834 }
835 }
836
837 // Mirrors the gating + tool-speed multiplier at `mining_input_system`
838 // (mining.rs:615-621). Returns the per-call delta passed into `tick_mining`,
839 // or `None` if the tool level gate blocks progress.
840 fn gated_effective_delta(
841 delta: f32,
842 tool_level: u8,
843 tool_speed: f32,
844 voxel_mining_level: u8,
845 ) -> Option<f32> {
846 if tool_level < voxel_mining_level {
847 None
848 } else {
849 Some(delta * tool_speed)
850 }
851 }
852
853 #[test]
854 fn hardness_zero_is_unbreakable() {
855 let config = default_config();
856 let hardness = 0.0;
857 let effective = compute_effective_break_time(config.break_time, hardness);
858
859 assert_eq!(effective, f32::MAX);
860
861 let mut state = MiningState {
862 target: Some((IVec3::ZERO, (0, 0, 0))),
863 elapsed: 0.0,
864 progress: 0.0,
865 effective_break_time: effective,
866 };
867
868 // Simulate a long delta — progress must remain effectively zero.
869 for _ in 0..1_000 {
870 state.elapsed += 10.0;
871 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
872 }
873
874 assert!(state.progress < 1.0);
875 assert!(state.progress < f32::EPSILON * 1_000.0);
876 // Production code at mining.rs:397 only emits VoxelBroken when
877 // `effective_break_time < f32::MAX`, so the unbreakable branch
878 // never reaches the break message.
879 assert_eq!(state.effective_break_time, f32::MAX);
880 }
881
882 #[test]
883 fn hardness_scales_break_time() {
884 let break_time = 1.5_f32;
885 let hardness = 3.0_f32;
886 let effective = compute_effective_break_time(break_time, hardness);
887 assert!((effective - 4.5).abs() < f32::EPSILON);
888 }
889
890 #[test]
891 fn tool_level_below_mining_level_blocks_progress() {
892 let delta = gated_effective_delta(0.1, 1, 1.0, 2);
893 assert!(
894 delta.is_none(),
895 "tool_level=1 must not mine voxel with mining_level=2"
896 );
897
898 // Confirm `stop_mining` semantics — state resets when gate trips.
899 let mut state = MiningState {
900 target: Some((IVec3::ZERO, (0, 0, 0))),
901 elapsed: 0.4,
902 progress: 0.2,
903 effective_break_time: 1.5,
904 };
905 stop_mining(&mut state);
906 assert!(state.target.is_none());
907 assert_eq!(state.elapsed, 0.0);
908 assert_eq!(state.progress, 0.0);
909 }
910
911 #[test]
912 fn tool_level_meets_requirement_progresses() {
913 let config = default_config();
914 let delta = gated_effective_delta(0.1, 1, 1.0, 1)
915 .expect("tool_level=1 must satisfy mining_level=1 gate");
916 assert!((delta - 0.1).abs() < f32::EPSILON);
917
918 let hardness = 1.0_f32;
919 let effective = compute_effective_break_time(config.break_time, hardness);
920 let mut state = MiningState {
921 target: Some((IVec3::ZERO, (0, 0, 0))),
922 elapsed: 0.0,
923 progress: 0.0,
924 effective_break_time: effective,
925 };
926
927 for _ in 0..3 {
928 state.elapsed += delta;
929 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
930 }
931
932 assert!(state.progress > 0.0);
933 assert!(state.progress < 1.0);
934 }
935
936 #[test]
937 fn tool_speed_scales_delta() {
938 let break_time = 1.5_f32;
939 let hardness = 1.0_f32;
940 let tool_speed = 2.0_f32;
941 let frame_delta = 0.1_f32;
942
943 let effective_delta = gated_effective_delta(frame_delta, 0, tool_speed, 0)
944 .expect("level-0 voxel is breakable by bare hands");
945 assert!(
946 (effective_delta - 0.2).abs() < f32::EPSILON,
947 "tool_speed=2.0 must double the per-call delta"
948 );
949
950 let effective_break_time = compute_effective_break_time(break_time, hardness);
951 let mut state = MiningState {
952 target: Some((IVec3::ZERO, (0, 0, 0))),
953 elapsed: 0.0,
954 progress: 0.0,
955 effective_break_time,
956 };
957
958 // Simulate ~0.75 s of real time at frame_delta = 0.1.
959 let frames_for_half_time = (0.75 / frame_delta).ceil() as usize;
960 for _ in 0..frames_for_half_time {
961 state.elapsed += effective_delta;
962 state.progress = (state.elapsed / state.effective_break_time).min(1.0);
963 }
964
965 assert!(
966 state.progress >= 1.0,
967 "tool_speed=2.0 must reach progress=1.0 at ~half the nominal break time \
968 (expected >=1.0, got {})",
969 state.progress
970 );
971 }
972}