Skip to main content

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, record_voxel_edit};
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, its chunk is loaded, and the active tool meets its mining level. Emits [`VoxelBroken`], [`ChunkModified`],
202/// and border-neighbor notifications.
203fn 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
258/// Returns the three extra world-voxel offsets that form a 2×2 square on the
259/// hit face together with the primary voxel.
260///
261/// The two tangent axes are determined by `face_normal`.  For each axis the
262/// sign of the offset is chosen so that the 2×2 quad lies in the quadrant
263/// where the ray actually entered the face (using `hit_point` vs
264/// `voxel_center`).
265fn 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        // X face → perpendicular plane is YZ
269        (
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        // Y face → perpendicular plane is XZ
275        (
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        // Z face (or zero normal) → perpendicular plane is XY
281        (
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
289/// Sends [`ChunkModified`] for any neighboring chunks whose border shares the
290/// face of the voxel at `local` within `chunk_coord`.
291///
292/// When a voxel on the edge of a chunk is added or removed, the adjacent
293/// chunk's mesh must also be regenerated — its border faces were previously
294/// culled by this voxel and are now exposed (or vice versa for placement).
295fn 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
317/// Compute the world-space center of a voxel given its chunk coord and local index.
318fn 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/// Advance mining by one frame toward breaking the target voxel.
329///
330/// Call this **every frame** while the mine button is held.  When the
331/// accumulated time reaches `config.break_time` the function:
332///
333/// 1. Sets the target voxel to air (if the chunk is loaded).
334/// 2. Writes a [`VoxelBroken`] message.
335/// 3. Writes a [`ChunkModified`] message to trigger remeshing.
336/// 4. Resets `state` so a new target can start fresh.
337///
338/// A [`MiningProgress`] message is written on **every** call, including the
339/// break frame.
340///
341/// If `target_chunk` / `target_local` differs from the previous frame, elapsed
342/// time is reset to zero automatically — no need to call [`stop_mining`] when
343/// switching targets mid-frame.
344///
345/// # Parameters
346///
347/// - `target_chunk` — Chunk-grid coordinate of the chunk containing the target
348///   voxel.
349/// - `target_local` — Local `(x, y, z)` voxel index within the chunk.
350/// - `delta_secs` — Frame delta time in seconds (typically `time.delta_secs()`).
351/// - `state` — Mutable reference to the shared [`MiningState`] resource.
352/// - `config` — Read-only mining configuration (break time).
353/// - `manager` — Chunk registry used to look up the chunk entity.
354/// - `chunks` — Mutable query used to set voxels to air on break.
355/// - `broken` — Message writer for [`VoxelBroken`].
356/// - `progress_writer` — Message writer for [`MiningProgress`].
357/// - `modified` — Message writer for [`crate::world::ChunkModified`].
358///
359/// # Examples
360///
361/// ```no_run
362/// # use bevy::prelude::*;
363/// # use voxel_framework::world::mining::{MiningConfig, MiningState, MiningProgress, VoxelBroken, tick_mining};
364/// # use voxel_framework::world::{ChunkManager, ChunkModified};
365/// # use voxel_framework::chunk::Chunk;
366/// # use voxel_framework::voxel::DefaultVoxel;
367/// fn my_system(
368///     mut state:    ResMut<MiningState>,
369///     config:       Res<MiningConfig>,
370///     manager:      Res<ChunkManager>,
371///     mut chunks:   Query<&mut Chunk<DefaultVoxel>>,
372///     mut broken:   MessageWriter<VoxelBroken>,
373///     mut progress: MessageWriter<MiningProgress>,
374///     mut modified: MessageWriter<ChunkModified>,
375///     time:         Res<Time>,
376/// ) {
377///     tick_mining(
378///         IVec3::ZERO, (4, 0, 4),
379///         time.delta_secs(),
380///         &mut state, &config, &manager,
381///         &mut chunks, &mut broken, &mut progress, &mut modified,
382///     );
383/// }
384/// ```
385#[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    // Reset elapsed when target changes and sample the new voxel's hardness.
399    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        // Hardness 0.0 means unbreakable — use a very large break time.
410        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        // Destroy the voxel if the chunk is loaded.
432        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        // Reset state.
463        state.target = None;
464        state.elapsed = 0.0;
465        state.progress = 0.0;
466    }
467}
468
469/// Stop mining and reset all accumulated progress.
470///
471/// Call this whenever the mine button is released.  Failing to call
472/// `stop_mining` means any partial progress persists, and the next target
473/// will appear to start partially broken.
474///
475/// # Examples
476///
477/// ```no_run
478/// # use voxel_framework::world::mining::{MiningState, stop_mining};
479/// fn on_button_release(mut state: bevy::prelude::ResMut<MiningState>) {
480///     stop_mining(&mut state);
481/// }
482/// ```
483pub fn stop_mining(state: &mut MiningState) {
484    state.target = None;
485    state.elapsed = 0.0;
486    state.progress = 0.0;
487}
488
489// ─── Plugin ───────────────────────────────────────────────────────────────────
490
491/// Bevy plugin that registers the mining subsystem.
492///
493/// Adds the following to the [`bevy::prelude::App`]:
494///
495/// - [`MiningConfig`] resource (initialised with defaults — `break_time: 1.5 s`)
496/// - [`MiningState`] resource (initialised at default / idle)
497/// - [`VoxelBroken`] message type
498/// - [`MiningProgress`] message type
499///
500/// Does **not** add any systems.  Game code is responsible for calling
501/// [`tick_mining`] and [`stop_mining`] from its own update systems.
502pub 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// ─── MiningInputPlugin ────────────────────────────────────────────────────────
514//
515// `MiningInputPlugin` and its companion `hotbar_to_tool_system` are gated on the
516// `items` feature because they require `ItemType`, `HotbarState`,
517// `ContainerComponent`, and `PrimaryContainer` — all of which live in
518// `crate::items`. Disabling the feature compiles them out cleanly.
519
520/// Convenience plugin that wires mouse input to the mining API automatically.
521///
522/// `MiningInputPlugin<V, I>` adds two [`Update`] systems:
523///
524/// 1. `hotbar_to_tool_system` — reads the active hotbar slot from [`Inventory<I>`](crate::items::Inventory)
525///    and updates [`ToolStats`] with the slot's tool level and speed each frame.
526/// 2. `mining_input_system` — raycasts from the active [`Camera3d`] (max
527///    `6.0` world units). While the **left mouse button** is held and the ray
528///    hits a solid voxel whose [`crate::voxel::VoxelType::mining_level`] is
529///    satisfied by the current [`ToolStats::tool_level`], calls [`tick_mining`]
530///    to accumulate break progress. When the button is released (or no voxel is
531///    hit, or the tool level is too low), calls [`stop_mining`].
532///
533/// # Prerequisites
534///
535/// [`MiningPlugin`] must be added **before** this plugin so that the required
536/// resources ([`MiningState`], [`MiningConfig`]) and message channels
537/// ([`VoxelBroken`], [`MiningProgress`]) are already registered.
538///
539/// A player entity with [`crate::items::inventory::ContainerComponent<I>`] and
540/// [`crate::items::inventory::PrimaryContainer`] must be present (typically spawned
541/// in a `Startup` system).
542///
543/// # Example
544///
545/// ```no_run
546/// use bevy::prelude::*;
547/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
548/// use voxel_framework::world::mining::MiningInputPlugin;
549/// use voxel_framework::voxel::DefaultTerrainVoxel;
550/// use voxel_framework::items::DefaultItem;
551///
552/// App::new()
553///     .add_plugins(DefaultPlugins)
554///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
555///     .add_plugins(MiningInputPlugin::<DefaultTerrainVoxel, DefaultItem>::new())
556///     .run();
557/// ```
558#[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    /// Creates a new [`MiningInputPlugin`] for voxel type `V` and item type `I`.
566    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/// Updates [`ToolStats`] from the active hotbar slot each frame.
592///
593/// Reads the [`ContainerComponent`] on the [`PrimaryContainer`] entity.
594/// If no such entity exists, resets to bare-hands stats silently.
595///
596/// Added automatically by [`MiningInputPlugin`] — do not add manually.
597#[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///
627/// Raycasts from the camera and drives [`tick_mining`] / [`stop_mining`] based
628/// on left-mouse-button state and [`ToolStats`].
629#[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)]
637/// Every neighbor of the 2×2 face patch must independently satisfy the active
638/// tool level before mutation or break notifications.
639pub 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    // `transmute_lens` gives a read-only view without a second conflicting query.
665    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    // Check that the active tool can mine this voxel type.
672    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    // Apply tool speed to the effective delta — faster tools reduce break time.
691    let effective_delta = time.delta_secs() * tool_stats.tool_speed;
692
693    // Snapshot before tick so we can detect the break event below.
694    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 the primary block just broke, also break the 3 adjacent blocks that
710    // form a 2×2 square on the struck face, checking each neighbor's mining level.
711    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// ─── Tests ────────────────────────────────────────────────────────────────────
735
736#[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    // ── stop_mining ──────────────────────────────────────────────────────────
868
869    #[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    // ── progress calculation ──────────────────────────────────────────────────
884
885    #[test]
886    fn test_mining_progress_accumulates() {
887        let config = default_config();
888        let mut state = MiningState::default();
889
890        // Manually simulate two ticks without Bevy context.
891        let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
892
893        // First tick: set target and advance elapsed.
894        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        // Second tick: same target, keep accumulating.
905        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        // Mine target A for a bit.
921        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        // Switch to target B — should reset.
928        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        // Simulate ticks until elapsed >= break_time.
945        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        // Way more elapsed than break_time.
969        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    // Mirrors the production formula at `tick_mining` (mining.rs:376-388).
976    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    // Mirrors the gating + tool-speed multiplier at `mining_input_system`
985    // (mining.rs:615-621). Returns the per-call delta passed into `tick_mining`,
986    // or `None` if the tool level gate blocks progress.
987    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        // Simulate a long delta — progress must remain effectively zero.
1016        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        // Production code at mining.rs:397 only emits VoxelBroken when
1024        // `effective_break_time < f32::MAX`, so the unbreakable branch
1025        // never reaches the break message.
1026        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        // Confirm `stop_mining` semantics — state resets when gate trips.
1046        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        // Simulate ~0.75 s of real time at frame_delta = 0.1.
1106        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}