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};
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
238    let wp = voxel_world_pos(chunk_coord, local);
239    broken.write(VoxelBroken {
240        chunk_coord,
241        local,
242        world_pos: wp,
243        voxel_byte,
244    });
245    modified.write(ChunkModified(chunk_coord));
246    notify_border_neighbors(chunk_coord, local, modified);
247}
248
249/// Returns the three extra world-voxel offsets that form a 2×2 square on the
250/// hit face together with the primary voxel.
251///
252/// The two tangent axes are determined by `face_normal`.  For each axis the
253/// sign of the offset is chosen so that the 2×2 quad lies in the quadrant
254/// where the ray actually entered the face (using `hit_point` vs
255/// `voxel_center`).
256fn quad_offsets(face_normal: Vec3, hit_point: Vec3, voxel_center: Vec3) -> [IVec3; 3] {
257    let sign = |coord: f32, center: f32| -> i32 { if coord >= center { 1 } else { -1 } };
258    let (du, dv) = if face_normal.x.abs() > 0.5 {
259        // X face → perpendicular plane is YZ
260        (
261            IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
262            IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
263        )
264    } else if face_normal.y.abs() > 0.5 {
265        // Y face → perpendicular plane is XZ
266        (
267            IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
268            IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
269        )
270    } else {
271        // Z face (or zero normal) → perpendicular plane is XY
272        (
273            IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
274            IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
275        )
276    };
277    [du, dv, du + dv]
278}
279
280/// Sends [`ChunkModified`] for any neighboring chunks whose border shares the
281/// face of the voxel at `local` within `chunk_coord`.
282///
283/// When a voxel on the edge of a chunk is added or removed, the adjacent
284/// chunk's mesh must also be regenerated — its border faces were previously
285/// culled by this voxel and are now exposed (or vice versa for placement).
286fn notify_border_neighbors(
287    chunk_coord: IVec3,
288    local: (usize, usize, usize),
289    modified: &mut MessageWriter<ChunkModified>,
290) {
291    use crate::chunk::CHUNK_SIZE;
292    let (x, y, z) = local;
293    let offsets: [(usize, IVec3); 6] = [
294        (x, IVec3::NEG_X),
295        (CHUNK_SIZE - 1 - x, IVec3::X),
296        (y, IVec3::NEG_Y),
297        (CHUNK_SIZE - 1 - y, IVec3::Y),
298        (z, IVec3::NEG_Z),
299        (CHUNK_SIZE - 1 - z, IVec3::Z),
300    ];
301    for (dist, dir) in offsets {
302        if dist == 0 {
303            modified.write(ChunkModified(chunk_coord + dir));
304        }
305    }
306}
307
308/// Compute the world-space center of a voxel given its chunk coord and local index.
309fn voxel_world_pos(chunk_coord: IVec3, local: (usize, usize, usize)) -> Vec3 {
310    let chunk_origin = chunk_coord.as_vec3() * crate::chunk::CHUNK_SIZE as f32;
311    chunk_origin
312        + Vec3::new(
313            local.0 as f32 + 0.5,
314            local.1 as f32 + 0.5,
315            local.2 as f32 + 0.5,
316        )
317}
318
319/// Advance mining by one frame toward breaking the target voxel.
320///
321/// Call this **every frame** while the mine button is held.  When the
322/// accumulated time reaches `config.break_time` the function:
323///
324/// 1. Sets the target voxel to air (if the chunk is loaded).
325/// 2. Writes a [`VoxelBroken`] message.
326/// 3. Writes a [`ChunkModified`] message to trigger remeshing.
327/// 4. Resets `state` so a new target can start fresh.
328///
329/// A [`MiningProgress`] message is written on **every** call, including the
330/// break frame.
331///
332/// If `target_chunk` / `target_local` differs from the previous frame, elapsed
333/// time is reset to zero automatically — no need to call [`stop_mining`] when
334/// switching targets mid-frame.
335///
336/// # Parameters
337///
338/// - `target_chunk` — Chunk-grid coordinate of the chunk containing the target
339///   voxel.
340/// - `target_local` — Local `(x, y, z)` voxel index within the chunk.
341/// - `delta_secs` — Frame delta time in seconds (typically `time.delta_secs()`).
342/// - `state` — Mutable reference to the shared [`MiningState`] resource.
343/// - `config` — Read-only mining configuration (break time).
344/// - `manager` — Chunk registry used to look up the chunk entity.
345/// - `chunks` — Mutable query used to set voxels to air on break.
346/// - `broken` — Message writer for [`VoxelBroken`].
347/// - `progress_writer` — Message writer for [`MiningProgress`].
348/// - `modified` — Message writer for [`crate::world::ChunkModified`].
349///
350/// # Examples
351///
352/// ```no_run
353/// # use bevy::prelude::*;
354/// # use voxel_framework::world::mining::{MiningConfig, MiningState, MiningProgress, VoxelBroken, tick_mining};
355/// # use voxel_framework::world::{ChunkManager, ChunkModified};
356/// # use voxel_framework::chunk::Chunk;
357/// # use voxel_framework::voxel::DefaultVoxel;
358/// fn my_system(
359///     mut state:    ResMut<MiningState>,
360///     config:       Res<MiningConfig>,
361///     manager:      Res<ChunkManager>,
362///     mut chunks:   Query<&mut Chunk<DefaultVoxel>>,
363///     mut broken:   MessageWriter<VoxelBroken>,
364///     mut progress: MessageWriter<MiningProgress>,
365///     mut modified: MessageWriter<ChunkModified>,
366///     time:         Res<Time>,
367/// ) {
368///     tick_mining(
369///         IVec3::ZERO, (4, 0, 4),
370///         time.delta_secs(),
371///         &mut state, &config, &manager,
372///         &mut chunks, &mut broken, &mut progress, &mut modified,
373///     );
374/// }
375/// ```
376#[allow(clippy::too_many_arguments)]
377pub fn tick_mining<V: VoxelType>(
378    target_chunk: IVec3,
379    target_local: (usize, usize, usize),
380    delta_secs: f32,
381    state: &mut MiningState,
382    config: &MiningConfig,
383    manager: &ChunkManager,
384    chunks: &mut Query<&mut Chunk<V>>,
385    broken: &mut MessageWriter<VoxelBroken>,
386    progress_writer: &mut MessageWriter<MiningProgress>,
387    modified: &mut MessageWriter<ChunkModified>,
388) {
389    // Reset elapsed when target changes and sample the new voxel's hardness.
390    if state.target != Some((target_chunk, target_local)) {
391        let hardness = manager
392            .get_entity(target_chunk)
393            .and_then(|e| chunks.get(e).ok())
394            .map(|chunk| {
395                let (x, y, z) = target_local;
396                chunk.get(x, y, z).hardness()
397            })
398            .unwrap_or(1.0);
399
400        // Hardness 0.0 means unbreakable — use a very large break time.
401        state.effective_break_time = if hardness > 0.0 {
402            config.break_time * hardness
403        } else {
404            f32::MAX
405        };
406        state.elapsed = 0.0;
407        state.progress = 0.0;
408        state.target = Some((target_chunk, target_local));
409    }
410
411    state.elapsed += delta_secs;
412    state.progress = (state.elapsed / state.effective_break_time).min(1.0);
413
414    let world_pos = voxel_world_pos(target_chunk, target_local);
415
416    progress_writer.write(MiningProgress {
417        progress: state.progress,
418        world_pos,
419    });
420
421    if state.progress >= 1.0 && state.effective_break_time < f32::MAX {
422        // Destroy the voxel if the chunk is loaded.
423        let mut voxel_byte = V::air().to_byte();
424        if let Some(entity) = manager.get_entity(target_chunk) {
425            if let Ok(mut chunk) = chunks.get_mut(entity) {
426                let (x, y, z) = target_local;
427                voxel_byte = chunk.get(x, y, z).to_byte();
428                chunk.set(x, y, z, V::air());
429            }
430        }
431
432        broken.write(VoxelBroken {
433            chunk_coord: target_chunk,
434            local: target_local,
435            world_pos,
436            voxel_byte,
437        });
438
439        modified.write(ChunkModified(target_chunk));
440        notify_border_neighbors(target_chunk, target_local, modified);
441
442        // Reset state.
443        state.target = None;
444        state.elapsed = 0.0;
445        state.progress = 0.0;
446    }
447}
448
449/// Stop mining and reset all accumulated progress.
450///
451/// Call this whenever the mine button is released.  Failing to call
452/// `stop_mining` means any partial progress persists, and the next target
453/// will appear to start partially broken.
454///
455/// # Examples
456///
457/// ```no_run
458/// # use voxel_framework::world::mining::{MiningState, stop_mining};
459/// fn on_button_release(mut state: bevy::prelude::ResMut<MiningState>) {
460///     stop_mining(&mut state);
461/// }
462/// ```
463pub fn stop_mining(state: &mut MiningState) {
464    state.target = None;
465    state.elapsed = 0.0;
466    state.progress = 0.0;
467}
468
469// ─── Plugin ───────────────────────────────────────────────────────────────────
470
471/// Bevy plugin that registers the mining subsystem.
472///
473/// Adds the following to the [`bevy::prelude::App`]:
474///
475/// - [`MiningConfig`] resource (initialised with defaults — `break_time: 1.5 s`)
476/// - [`MiningState`] resource (initialised at default / idle)
477/// - [`VoxelBroken`] message type
478/// - [`MiningProgress`] message type
479///
480/// Does **not** add any systems.  Game code is responsible for calling
481/// [`tick_mining`] and [`stop_mining`] from its own update systems.
482pub struct MiningPlugin;
483
484impl Plugin for MiningPlugin {
485    fn build(&self, app: &mut App) {
486        app.init_resource::<MiningConfig>();
487        app.init_resource::<MiningState>();
488        app.add_message::<VoxelBroken>();
489        app.add_message::<MiningProgress>();
490    }
491}
492
493// ─── MiningInputPlugin ────────────────────────────────────────────────────────
494//
495// `MiningInputPlugin` and its companion `hotbar_to_tool_system` are gated on the
496// `items` feature because they require `ItemType`, `HotbarState`,
497// `ContainerComponent`, and `PrimaryContainer` — all of which live in
498// `crate::items`. Disabling the feature compiles them out cleanly.
499
500/// Convenience plugin that wires mouse input to the mining API automatically.
501///
502/// `MiningInputPlugin<V, I>` adds two [`Update`] systems:
503///
504/// 1. `hotbar_to_tool_system` — reads the active hotbar slot from [`Inventory<I>`](crate::items::Inventory)
505///    and updates [`ToolStats`] with the slot's tool level and speed each frame.
506/// 2. `mining_input_system` — raycasts from the active [`Camera3d`] (max
507///    `6.0` world units). While the **left mouse button** is held and the ray
508///    hits a solid voxel whose [`crate::voxel::VoxelType::mining_level`] is
509///    satisfied by the current [`ToolStats::tool_level`], calls [`tick_mining`]
510///    to accumulate break progress. When the button is released (or no voxel is
511///    hit, or the tool level is too low), calls [`stop_mining`].
512///
513/// # Prerequisites
514///
515/// [`MiningPlugin`] must be added **before** this plugin so that the required
516/// resources ([`MiningState`], [`MiningConfig`]) and message channels
517/// ([`VoxelBroken`], [`MiningProgress`]) are already registered.
518///
519/// A player entity with [`crate::items::inventory::ContainerComponent<I>`] and
520/// [`crate::items::inventory::PrimaryContainer`] must be present (typically spawned
521/// in a `Startup` system).
522///
523/// # Example
524///
525/// ```no_run
526/// use bevy::prelude::*;
527/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
528/// use voxel_framework::world::mining::MiningInputPlugin;
529/// use voxel_framework::voxel::DefaultTerrainVoxel;
530/// use voxel_framework::items::DefaultItem;
531///
532/// App::new()
533///     .add_plugins(DefaultPlugins)
534///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
535///     .add_plugins(MiningInputPlugin::<DefaultTerrainVoxel, DefaultItem>::new())
536///     .run();
537/// ```
538#[cfg(feature = "items")]
539pub struct MiningInputPlugin<V: VoxelType, I: ItemType> {
540    _m: std::marker::PhantomData<(V, I)>,
541}
542
543#[cfg(feature = "items")]
544impl<V: VoxelType, I: ItemType> MiningInputPlugin<V, I> {
545    /// Creates a new [`MiningInputPlugin`] for voxel type `V` and item type `I`.
546    pub fn new() -> Self {
547        Self {
548            _m: std::marker::PhantomData,
549        }
550    }
551}
552
553#[cfg(feature = "items")]
554impl<V: VoxelType, I: ItemType> Default for MiningInputPlugin<V, I> {
555    fn default() -> Self {
556        Self::new()
557    }
558}
559
560#[cfg(feature = "items")]
561impl<V: VoxelType, I: ItemType> Plugin for MiningInputPlugin<V, I> {
562    fn build(&self, app: &mut App) {
563        app.init_resource::<ToolStats>();
564        app.add_systems(
565            Update,
566            (hotbar_to_tool_system::<I>, mining_input_system::<V>).chain(),
567        );
568    }
569}
570
571/// Updates [`ToolStats`] from the active hotbar slot each frame.
572///
573/// Reads the [`ContainerComponent`] on the [`PrimaryContainer`] entity.
574/// If no such entity exists, resets to bare-hands stats silently.
575///
576/// Added automatically by [`MiningInputPlugin`] — do not add manually.
577#[cfg(feature = "items")]
578pub fn hotbar_to_tool_system<I: ItemType>(
579    hotbar: Res<HotbarState>,
580    container_query: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
581    mut tool_stats: ResMut<ToolStats>,
582    applied: Option<Res<AppliedEffectModifiers>>,
583) {
584    let Ok(container) = container_query.single() else {
585        tool_stats.reset();
586        return;
587    };
588    let active_slot = hotbar.selected;
589    if let Some(slot) = container.0.slots.get(active_slot).and_then(|s| s.as_ref()) {
590        tool_stats.tool_level = slot.item.tool_level();
591        tool_stats.tool_speed = slot.item.tool_speed()
592            * applied
593                .as_deref()
594                .map(|a| a.0.mining_speed_mult)
595                .unwrap_or(1.0);
596    } else {
597        tool_stats.reset();
598    }
599}
600
601#[cfg_attr(feature = "items", doc = "System added by [`MiningInputPlugin`].")]
602#[cfg_attr(
603    not(feature = "items"),
604    doc = "Mining input system; its automatic plugin adapter requires the `items` feature."
605)]
606///
607/// Raycasts from the camera and drives [`tick_mining`] / [`stop_mining`] based
608/// on left-mouse-button state and [`ToolStats`].
609#[cfg_attr(
610    feature = "items",
611    doc = "Added automatically by [`MiningInputPlugin`] — do not add this system manually when using that plugin."
612)]
613#[cfg_attr(
614    not(feature = "items"),
615    doc = "Without the `items` feature, add this system explicitly and initialize or supply [`ToolStats`] from game-owned code."
616)]
617/// Every neighbor of the 2×2 face patch must independently satisfy the active
618/// tool level before mutation or break notifications.
619pub fn mining_input_system<V: VoxelType>(
620    buttons: Res<ButtonInput<MouseButton>>,
621    camera_q: Query<&GlobalTransform, With<Camera3d>>,
622    manager: Res<ChunkManager>,
623    mut chunks: Query<&mut crate::chunk::Chunk<V>>,
624    mut state: ResMut<MiningState>,
625    config: Res<MiningConfig>,
626    tool_stats: Res<ToolStats>,
627    mut broken: MessageWriter<VoxelBroken>,
628    mut progress: MessageWriter<MiningProgress>,
629    mut modified: MessageWriter<ChunkModified>,
630    time: Res<Time>,
631) {
632    if !buttons.pressed(MouseButton::Left) {
633        stop_mining(&mut state);
634        return;
635    }
636
637    let Ok(cam_tf) = camera_q.single() else {
638        return;
639    };
640
641    let origin = cam_tf.translation();
642    let direction = cam_tf.forward().as_vec3();
643
644    // `transmute_lens` gives a read-only view without a second conflicting query.
645    let mut lens = chunks.transmute_lens::<&crate::chunk::Chunk<V>>();
646    let Some(hit) = super::raycast::raycast(origin, direction, 6.0, &manager, &lens.query()) else {
647        stop_mining(&mut state);
648        return;
649    };
650
651    // Check that the active tool can mine this voxel type.
652    let voxel_mining_level = lens
653        .query()
654        .get(
655            manager
656                .get_entity(hit.chunk_coord)
657                .unwrap_or(Entity::PLACEHOLDER),
658        )
659        .map(|chunk| {
660            let (x, y, z) = hit.local;
661            chunk.get(x, y, z).mining_level()
662        })
663        .unwrap_or(0);
664
665    if tool_stats.tool_level < voxel_mining_level {
666        stop_mining(&mut state);
667        return;
668    }
669
670    // Apply tool speed to the effective delta — faster tools reduce break time.
671    let effective_delta = time.delta_secs() * tool_stats.tool_speed;
672
673    // Snapshot before tick so we can detect the break event below.
674    let was_mining = state.target.is_some();
675
676    tick_mining(
677        hit.chunk_coord,
678        hit.local,
679        effective_delta,
680        &mut state,
681        &config,
682        &manager,
683        &mut chunks,
684        &mut broken,
685        &mut progress,
686        &mut modified,
687    );
688
689    // If the primary block just broke, also break the 3 adjacent blocks that
690    // form a 2×2 square on the struck face, checking each neighbor's mining level.
691    if was_mining && state.target.is_none() {
692        use crate::chunk::CHUNK_SIZE;
693        let cs = CHUNK_SIZE as i32;
694        let vx = hit.chunk_coord.x * cs + hit.local.0 as i32;
695        let vy = hit.chunk_coord.y * cs + hit.local.1 as i32;
696        let vz = hit.chunk_coord.z * cs + hit.local.2 as i32;
697        let primary = IVec3::new(vx, vy, vz);
698        let center = Vec3::new(vx as f32 + 0.5, vy as f32 + 0.5, vz as f32 + 0.5);
699        let hit_pt = origin + hit.distance * direction.normalize();
700
701        for offset in quad_offsets(hit.face_normal, hit_pt, center) {
702            break_voxel(
703                primary + offset,
704                tool_stats.tool_level,
705                &manager,
706                &mut chunks,
707                &mut broken,
708                &mut modified,
709            );
710        }
711    }
712}
713
714// ─── Tests ────────────────────────────────────────────────────────────────────
715
716#[cfg(test)]
717mod tests {
718    use super::*;
719
720    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
721    enum PatchVoxel {
722        #[default]
723        Air,
724        Soft,
725        Ore,
726    }
727    impl VoxelType for PatchVoxel {
728        fn name(&self) -> &'static str {
729            "patch voxel"
730        }
731        fn is_solid(&self) -> bool {
732            *self != Self::Air
733        }
734        fn color(&self) -> [f32; 4] {
735            [1.0; 4]
736        }
737        fn to_byte(&self) -> u8 {
738            *self as u8
739        }
740        fn from_byte(byte: u8) -> Self {
741            match byte {
742                1 => Self::Soft,
743                2 => Self::Ore,
744                _ => Self::Air,
745            }
746        }
747        fn mining_level(&self) -> u8 {
748            if *self == Self::Ore { 2 } else { 0 }
749        }
750    }
751
752    #[test]
753    fn patch_respects_each_voxel_tool_level_and_drop_events() {
754        for tool_level in [0, 2] {
755            let mut app = App::new();
756            app.add_plugins(MiningPlugin)
757                .init_resource::<Time>()
758                .init_resource::<ButtonInput<MouseButton>>()
759                .insert_resource(ChunkManager::new(32.0, 48.0))
760                .insert_resource(ToolStats {
761                    tool_level,
762                    tool_speed: 1.0,
763                })
764                .insert_resource(MiningConfig { break_time: 1.0 })
765                .add_message::<ChunkModified>()
766                .add_systems(Update, mining_input_system::<PatchVoxel>);
767            #[cfg(feature = "items")]
768            {
769                use crate::items::{DefaultItem, DropTable, DropsPlugin};
770                app.add_plugins(DropsPlugin::<DefaultItem>::new());
771                let mut table = app.world_mut().resource_mut::<DropTable<DefaultItem>>();
772                table.register(1, DefaultItem::RockFragment, 1, 1);
773                table.register(2, DefaultItem::RareMineral, 1, 1);
774            }
775            let mut chunk = Chunk::<PatchVoxel>::new();
776            for (x, y) in [(4, 4), (4, 5), (5, 5), (6, 5)] {
777                chunk.set(x, y, 4, PatchVoxel::Soft);
778            }
779            chunk.set(5, 4, 4, PatchVoxel::Ore);
780            let entity = app.world_mut().spawn(chunk).id();
781            app.world_mut()
782                .resource_mut::<ChunkManager>()
783                .register(IVec3::ZERO, entity);
784            app.world_mut().spawn((
785                Camera3d::default(),
786                GlobalTransform::from_translation(Vec3::new(4.75, 4.75, 8.0)),
787            ));
788            app.world_mut()
789                .resource_mut::<ButtonInput<MouseButton>>()
790                .press(MouseButton::Left);
791            for _ in 0..2 {
792                app.world_mut()
793                    .resource_mut::<Time>()
794                    .advance_by(std::time::Duration::from_millis(500));
795                app.update();
796            }
797            let chunk = app.world().get::<Chunk<PatchVoxel>>(entity).unwrap();
798            for (x, y) in [(4, 4), (4, 5), (5, 5)] {
799                assert_eq!(chunk.get(x, y, 4), PatchVoxel::Air);
800            }
801            assert_eq!(
802                chunk.get(5, 4, 4),
803                if tool_level == 0 {
804                    PatchVoxel::Ore
805                } else {
806                    PatchVoxel::Air
807                }
808            );
809            assert_eq!(
810                chunk.get(6, 5, 4),
811                PatchVoxel::Soft,
812                "outside patch must remain intact"
813            );
814            let messages = app.world().resource::<Messages<VoxelBroken>>();
815            let mut cursor = messages.get_cursor();
816            let events: Vec<_> = cursor.read(messages).collect();
817            assert_eq!(events.len(), if tool_level == 0 { 3 } else { 4 });
818            assert_eq!(
819                events.iter().filter(|e| e.voxel_byte == 2).count(),
820                usize::from(tool_level == 2)
821            );
822            app.world_mut()
823                .resource_mut::<ButtonInput<MouseButton>>()
824                .clear();
825            app.update();
826            #[cfg(feature = "items")]
827            {
828                use crate::items::{DefaultItem, DroppedItem};
829                let mut query = app.world_mut().query::<&DroppedItem<DefaultItem>>();
830                let drops: Vec<_> = query.iter(app.world()).collect();
831                assert_eq!(drops.len(), if tool_level == 0 { 3 } else { 4 });
832                assert_eq!(
833                    drops
834                        .iter()
835                        .filter(|d| d.item == DefaultItem::RareMineral)
836                        .count(),
837                    usize::from(tool_level == 2)
838                );
839            }
840        }
841    }
842
843    fn default_config() -> MiningConfig {
844        MiningConfig { break_time: 1.5 }
845    }
846
847    // ── stop_mining ──────────────────────────────────────────────────────────
848
849    #[test]
850    fn stop_mining_resets_state() {
851        let mut state = MiningState {
852            target: Some((IVec3::ZERO, (1, 2, 3))),
853            elapsed: 0.8,
854            progress: 0.5,
855            effective_break_time: 1.0,
856        };
857        stop_mining(&mut state);
858        assert!(state.target.is_none());
859        assert_eq!(state.elapsed, 0.0);
860        assert_eq!(state.progress, 0.0);
861    }
862
863    // ── progress calculation ──────────────────────────────────────────────────
864
865    #[test]
866    fn test_mining_progress_accumulates() {
867        let config = default_config();
868        let mut state = MiningState::default();
869
870        // Manually simulate two ticks without Bevy context.
871        let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
872
873        // First tick: set target and advance elapsed.
874        if state.target != Some(target) {
875            state.elapsed = 0.0;
876            state.progress = 0.0;
877            state.target = Some(target);
878        }
879        state.elapsed += 0.3;
880        state.progress = (state.elapsed / config.break_time).min(1.0);
881
882        assert!((state.elapsed - 0.3).abs() < f32::EPSILON);
883
884        // Second tick: same target, keep accumulating.
885        state.elapsed += 0.4;
886        state.progress = (state.elapsed / config.break_time).min(1.0);
887
888        assert!((state.elapsed - 0.7).abs() < f32::EPSILON);
889        assert!(state.progress > 0.0 && state.progress < 1.0);
890    }
891
892    #[test]
893    fn test_mining_resets_on_target_change() {
894        let config = default_config();
895        let mut state = MiningState::default();
896
897        let target_a = (IVec3::ZERO, (0usize, 0usize, 0usize));
898        let target_b = (IVec3::ONE, (1usize, 1usize, 1usize));
899
900        // Mine target A for a bit.
901        state.target = Some(target_a);
902        state.elapsed += 0.5;
903        state.progress = (state.elapsed / config.break_time).min(1.0);
904
905        assert!(state.elapsed > 0.0);
906
907        // Switch to target B — should reset.
908        if state.target != Some(target_b) {
909            state.elapsed = 0.0;
910            state.progress = 0.0;
911            state.target = Some(target_b);
912        }
913
914        assert_eq!(state.elapsed, 0.0);
915        assert_eq!(state.progress, 0.0);
916        assert_eq!(state.target, Some(target_b));
917    }
918
919    #[test]
920    fn test_mining_completes_at_break_time() {
921        let config = default_config();
922        let mut state = MiningState::default();
923
924        // Simulate ticks until elapsed >= break_time.
925        let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
926        state.target = Some(target);
927
928        let mut completed = false;
929        let tick = 0.5_f32;
930        for _ in 0..10 {
931            state.elapsed += tick;
932            state.progress = (state.elapsed / config.break_time).min(1.0);
933            if state.progress >= 1.0 {
934                completed = true;
935                break;
936            }
937        }
938
939        assert!(completed, "mining should complete within 10 ticks of 0.5s");
940        assert_eq!(state.progress, 1.0);
941    }
942
943    #[test]
944    fn progress_is_clamped_to_one() {
945        let config = default_config();
946        let mut state = MiningState::default();
947
948        // Way more elapsed than break_time.
949        state.elapsed = 99.0;
950        state.progress = (state.elapsed / config.break_time).min(1.0);
951
952        assert_eq!(state.progress, 1.0);
953    }
954
955    // Mirrors the production formula at `tick_mining` (mining.rs:376-388).
956    fn compute_effective_break_time(break_time: f32, hardness: f32) -> f32 {
957        if hardness > 0.0 {
958            break_time * hardness
959        } else {
960            f32::MAX
961        }
962    }
963
964    // Mirrors the gating + tool-speed multiplier at `mining_input_system`
965    // (mining.rs:615-621). Returns the per-call delta passed into `tick_mining`,
966    // or `None` if the tool level gate blocks progress.
967    fn gated_effective_delta(
968        delta: f32,
969        tool_level: u8,
970        tool_speed: f32,
971        voxel_mining_level: u8,
972    ) -> Option<f32> {
973        if tool_level < voxel_mining_level {
974            None
975        } else {
976            Some(delta * tool_speed)
977        }
978    }
979
980    #[test]
981    fn hardness_zero_is_unbreakable() {
982        let config = default_config();
983        let hardness = 0.0;
984        let effective = compute_effective_break_time(config.break_time, hardness);
985
986        assert_eq!(effective, f32::MAX);
987
988        let mut state = MiningState {
989            target: Some((IVec3::ZERO, (0, 0, 0))),
990            elapsed: 0.0,
991            progress: 0.0,
992            effective_break_time: effective,
993        };
994
995        // Simulate a long delta — progress must remain effectively zero.
996        for _ in 0..1_000 {
997            state.elapsed += 10.0;
998            state.progress = (state.elapsed / state.effective_break_time).min(1.0);
999        }
1000
1001        assert!(state.progress < 1.0);
1002        assert!(state.progress < f32::EPSILON * 1_000.0);
1003        // Production code at mining.rs:397 only emits VoxelBroken when
1004        // `effective_break_time < f32::MAX`, so the unbreakable branch
1005        // never reaches the break message.
1006        assert_eq!(state.effective_break_time, f32::MAX);
1007    }
1008
1009    #[test]
1010    fn hardness_scales_break_time() {
1011        let break_time = 1.5_f32;
1012        let hardness = 3.0_f32;
1013        let effective = compute_effective_break_time(break_time, hardness);
1014        assert!((effective - 4.5).abs() < f32::EPSILON);
1015    }
1016
1017    #[test]
1018    fn tool_level_below_mining_level_blocks_progress() {
1019        let delta = gated_effective_delta(0.1, 1, 1.0, 2);
1020        assert!(
1021            delta.is_none(),
1022            "tool_level=1 must not mine voxel with mining_level=2"
1023        );
1024
1025        // Confirm `stop_mining` semantics — state resets when gate trips.
1026        let mut state = MiningState {
1027            target: Some((IVec3::ZERO, (0, 0, 0))),
1028            elapsed: 0.4,
1029            progress: 0.2,
1030            effective_break_time: 1.5,
1031        };
1032        stop_mining(&mut state);
1033        assert!(state.target.is_none());
1034        assert_eq!(state.elapsed, 0.0);
1035        assert_eq!(state.progress, 0.0);
1036    }
1037
1038    #[test]
1039    fn tool_level_meets_requirement_progresses() {
1040        let config = default_config();
1041        let delta = gated_effective_delta(0.1, 1, 1.0, 1)
1042            .expect("tool_level=1 must satisfy mining_level=1 gate");
1043        assert!((delta - 0.1).abs() < f32::EPSILON);
1044
1045        let hardness = 1.0_f32;
1046        let effective = compute_effective_break_time(config.break_time, hardness);
1047        let mut state = MiningState {
1048            target: Some((IVec3::ZERO, (0, 0, 0))),
1049            elapsed: 0.0,
1050            progress: 0.0,
1051            effective_break_time: effective,
1052        };
1053
1054        for _ in 0..3 {
1055            state.elapsed += delta;
1056            state.progress = (state.elapsed / state.effective_break_time).min(1.0);
1057        }
1058
1059        assert!(state.progress > 0.0);
1060        assert!(state.progress < 1.0);
1061    }
1062
1063    #[test]
1064    fn tool_speed_scales_delta() {
1065        let break_time = 1.5_f32;
1066        let hardness = 1.0_f32;
1067        let tool_speed = 2.0_f32;
1068        let frame_delta = 0.1_f32;
1069
1070        let effective_delta = gated_effective_delta(frame_delta, 0, tool_speed, 0)
1071            .expect("level-0 voxel is breakable by bare hands");
1072        assert!(
1073            (effective_delta - 0.2).abs() < f32::EPSILON,
1074            "tool_speed=2.0 must double the per-call delta"
1075        );
1076
1077        let effective_break_time = compute_effective_break_time(break_time, hardness);
1078        let mut state = MiningState {
1079            target: Some((IVec3::ZERO, (0, 0, 0))),
1080            elapsed: 0.0,
1081            progress: 0.0,
1082            effective_break_time,
1083        };
1084
1085        // Simulate ~0.75 s of real time at frame_delta = 0.1.
1086        let frames_for_half_time = (0.75 / frame_delta).ceil() as usize;
1087        for _ in 0..frames_for_half_time {
1088            state.elapsed += effective_delta;
1089            state.progress = (state.elapsed / state.effective_break_time).min(1.0);
1090        }
1091
1092        assert!(
1093            state.progress >= 1.0,
1094            "tool_speed=2.0 must reach progress=1.0 at ~half the nominal break time \
1095             (expected >=1.0, got {})",
1096            state.progress
1097        );
1098    }
1099}