voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Optional progress overlay drawn on the voxel being mined.
//!
//! [`MiningOverlayPlugin`] reads [`MiningState`] after the game's `Update`
//! systems and keeps one overlay entity on the targeted voxel while mining is
//! in progress. The overlay is its own entity with its own mesh and material:
//! the chunk mesh, its vertex format and the chunk material are not touched.
//!
//! The framework ships no artwork. The game supplies one material per damage
//! stage in [`MiningOverlayConfig::stages`]; with the default (empty) list
//! nothing is drawn. Progress is split evenly across the stages by
//! [`mining_overlay_stage`].
//!
//! The plugin is a Default Implementation plugin. It is not part of
//! `VoxelCorePlugin` or `VoxelPlugin`; add it explicitly.
//!
//! # Integration
//!
//! ```no_run
//! use bevy::prelude::*;
//! use voxel_framework::world::mining_overlay::{
//!     MiningOverlayConfig, MiningOverlayPlugin, MiningOverlayStage,
//! };
//!
//! fn setup_overlay(
//!     mut config: ResMut<MiningOverlayConfig>,
//!     mut materials: ResMut<Assets<StandardMaterial>>,
//! ) {
//!     // Three stages, each a darker translucent tint. A game would normally
//!     // use its own textures here.
//!     config.stages = [0.15, 0.3, 0.45]
//!         .into_iter()
//!         .map(|alpha| {
//!             MiningOverlayStage::new(materials.add(StandardMaterial {
//!                 base_color: Color::srgba(0.0, 0.0, 0.0, alpha),
//!                 alpha_mode: AlphaMode::Blend,
//!                 unlit: true,
//!                 ..default()
//!             }))
//!         })
//!         .collect();
//! }
//!
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_plugins(MiningOverlayPlugin)
//!     .add_systems(Startup, setup_overlay)
//!     .run();
//! ```

use bevy::camera::visibility::VisibilitySystems;
use bevy::prelude::*;
use bevy::transform::TransformSystems;

use crate::chunk::CHUNK_SIZE;

use super::mining::MiningState;

// ─── Resources ───────────────────────────────────────────────────────────────

/// One damage stage of the mining overlay.
///
/// Stages are ordered from the least to the most damaged. See
/// [`MiningOverlayConfig::stages`].
#[derive(Debug, Clone)]
pub struct MiningOverlayStage {
    /// Material drawn while this stage is active.
    pub material: Handle<StandardMaterial>,
    /// Mesh drawn while this stage is active.
    ///
    /// `None` (the default from [`MiningOverlayStage::new`]) uses
    /// [`MiningOverlayConfig::mesh`].
    pub mesh: Option<Handle<Mesh>>,
}

impl MiningOverlayStage {
    /// Creates a stage that draws `material` on the shared overlay mesh.
    pub fn new(material: Handle<StandardMaterial>) -> Self {
        Self {
            material,
            mesh: None,
        }
    }

    /// Returns the stage with its own mesh instead of the shared one.
    pub fn with_mesh(mut self, mesh: Handle<Mesh>) -> Self {
        self.mesh = Some(mesh);
        self
    }
}

/// Configuration for [`MiningOverlayPlugin`].
///
/// Initialized with defaults by the plugin unless the game inserted it
/// earlier. It is read every frame, so it can be changed at runtime.
///
/// The default draws nothing, because it has no stages.
#[derive(Resource, Debug, Clone)]
pub struct MiningOverlayConfig {
    /// Whether the overlay is drawn at all. **Default: `true`.**
    ///
    /// Setting it to `false` removes the overlay entity.
    pub visible: bool,
    /// Damage stages, from the least to the most damaged. **Default: empty.**
    ///
    /// Progress in `[0.0, 1.0]` is split evenly across the stages: with four
    /// stages the first one covers `[0.0, 0.25)` and the last one
    /// `[0.75, 1.0]`. With no stages nothing is drawn. See
    /// [`mining_overlay_stage`].
    pub stages: Vec<MiningOverlayStage>,
    /// Mesh shared by every stage that does not set its own.
    /// **Default: `None`.**
    ///
    /// `None` uses a cube one voxel wide, centered on its origin, created by
    /// the plugin the first time it is needed (this requires `Assets<Mesh>`).
    /// A custom mesh should also be one voxel wide and centered on its
    /// origin: it is placed at the center of the targeted voxel.
    pub mesh: Option<Handle<Mesh>>,
    /// Uniform scale applied to the overlay mesh. **Default: `1.002`.**
    ///
    /// A value slightly above `1.0` keeps the overlay just outside the faces
    /// of the voxel so both do not fight for the same depth. Values that are
    /// not finite and positive count as `1.0`.
    pub scale: f32,
}

impl Default for MiningOverlayConfig {
    fn default() -> Self {
        Self {
            visible: true,
            stages: Vec::new(),
            mesh: None,
            scale: 1.002,
        }
    }
}

// ─── Components ──────────────────────────────────────────────────────────────

/// Marker and state of the mining overlay entity.
///
/// The plugin keeps at most one entity with this component. It exists only
/// while a voxel is being mined and a stage can be drawn, and it also carries
/// `Mesh3d`, `MeshMaterial3d<StandardMaterial>` and `Transform`.
///
/// A game can add its own components to the overlay (for example a render
/// layer or a shadow setting) from a system that queries
/// `Added<MiningOverlay>`.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
pub struct MiningOverlay {
    /// Chunk-grid coordinate of the chunk that contains the targeted voxel.
    pub chunk_coord: IVec3,
    /// Local voxel index `(x, y, z)` of the targeted voxel within its chunk.
    pub local: (usize, usize, usize),
    /// Index into [`MiningOverlayConfig::stages`] of the stage being drawn.
    pub stage: usize,
}

/// System set of the system that updates the mining overlay.
///
/// It runs in `PostUpdate`, before transform propagation, so it sees the
/// [`MiningState`] left by the game's `Update` systems in the same frame.
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
pub struct MiningOverlaySystems;

// ─── Pure functions ──────────────────────────────────────────────────────────

/// Maps normalised mining progress to a stage index.
///
/// Progress is clamped to `[0.0, 1.0]` and split evenly across `stage_count`
/// stages; `1.0` belongs to the last stage. Returns `None` when there are no
/// stages or `progress` is NaN.
///
/// # Examples
///
/// ```
/// use voxel_framework::world::mining_overlay::mining_overlay_stage;
///
/// assert_eq!(mining_overlay_stage(0.0, 4), Some(0));
/// assert_eq!(mining_overlay_stage(0.5, 4), Some(2));
/// assert_eq!(mining_overlay_stage(1.0, 4), Some(3));
/// assert_eq!(mining_overlay_stage(0.5, 0), None);
/// ```
pub fn mining_overlay_stage(progress: f32, stage_count: usize) -> Option<usize> {
    if stage_count == 0 || progress.is_nan() {
        return None;
    }
    let clamped = progress.clamp(0.0, 1.0);
    let index = (clamped * stage_count as f32) as usize;
    Some(index.min(stage_count - 1))
}

/// Returns the transform of an overlay on the voxel at `local` in the chunk
/// at `chunk_coord`: centered on the voxel, not rotated, scaled by `scale`.
///
/// A `scale` that is not finite and positive counts as `1.0`.
///
/// # Examples
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::world::mining_overlay::mining_overlay_transform;
///
/// let transform = mining_overlay_transform(IVec3::new(1, 0, -1), (2, 3, 4), 1.0);
/// assert_eq!(transform.translation, Vec3::new(18.5, 3.5, -11.5));
/// ```
pub fn mining_overlay_transform(
    chunk_coord: IVec3,
    local: (usize, usize, usize),
    scale: f32,
) -> Transform {
    let scale = if scale.is_finite() && scale > 0.0 {
        scale
    } else {
        1.0
    };
    let center = chunk_coord.as_vec3() * CHUNK_SIZE as f32
        + Vec3::new(
            local.0 as f32 + 0.5,
            local.1 as f32 + 0.5,
            local.2 as f32 + 0.5,
        );
    Transform::from_translation(center).with_scale(Vec3::splat(scale))
}

/// Returns what the overlay should show for the given mining state, or `None`
/// when nothing should be drawn.
fn desired_overlay(state: &MiningState, config: &MiningOverlayConfig) -> Option<MiningOverlay> {
    if !config.visible {
        return None;
    }
    let (chunk_coord, local) = state.target?;
    let stage = mining_overlay_stage(state.progress, config.stages.len())?;
    Some(MiningOverlay {
        chunk_coord,
        local,
        stage,
    })
}

// ─── Systems ─────────────────────────────────────────────────────────────────

/// Keeps the overlay entity in step with [`MiningState`].
///
/// Added by [`MiningOverlayPlugin`] in `PostUpdate`. While a voxel is being
/// mined and a stage can be drawn, exactly one [`MiningOverlay`] entity
/// exists; it is moved when the target changes and its material (and mesh)
/// is swapped when the stage changes. It is despawned when mining stops, when
/// the voxel breaks, or when the overlay is hidden.
#[allow(clippy::type_complexity)]
pub fn update_mining_overlay(
    mut commands: Commands,
    state: Option<Res<MiningState>>,
    config: Res<MiningOverlayConfig>,
    meshes: Option<ResMut<Assets<Mesh>>>,
    mut default_mesh: Local<Option<Handle<Mesh>>>,
    mut overlays: Query<(
        Entity,
        &mut MiningOverlay,
        &mut Transform,
        &mut Mesh3d,
        &mut MeshMaterial3d<StandardMaterial>,
    )>,
) {
    let desired = state
        .as_deref()
        .and_then(|state| desired_overlay(state, &config));

    // Resolve the handles for the desired stage. No mesh available means
    // nothing can be drawn, which is handled like "no overlay".
    let resolved = desired.and_then(|overlay| {
        let stage = config.stages.get(overlay.stage)?;
        let mesh = match stage.mesh.clone().or_else(|| config.mesh.clone()) {
            Some(mesh) => mesh,
            None => {
                if default_mesh.is_none() {
                    let mut meshes = meshes?;
                    *default_mesh = Some(meshes.add(Cuboid::new(1.0, 1.0, 1.0)));
                }
                (*default_mesh).clone()?
            }
        };
        Some((overlay, mesh, stage.material.clone()))
    });

    let Some((overlay, mesh, material)) = resolved else {
        for (entity, ..) in &overlays {
            commands.entity(entity).despawn();
        }
        return;
    };

    let transform = mining_overlay_transform(overlay.chunk_coord, overlay.local, config.scale);

    let mut existing = overlays.iter_mut();
    let Some((_, mut current, mut current_transform, mut current_mesh, mut current_material)) =
        existing.next()
    else {
        commands.spawn((overlay, Mesh3d(mesh), MeshMaterial3d(material), transform));
        return;
    };

    // Write only what differs, so change detection stays quiet between stages.
    if *current != overlay {
        *current = overlay;
    }
    if *current_transform != transform {
        *current_transform = transform;
    }
    if current_mesh.0 != mesh {
        current_mesh.0 = mesh;
    }
    if current_material.0 != material {
        current_material.0 = material;
    }

    // The plugin never spawns a second overlay; remove any duplicate.
    for (entity, ..) in existing {
        commands.entity(entity).despawn();
    }
}

// ─── Plugin ──────────────────────────────────────────────────────────────────

/// Draws a staged progress overlay on the voxel being mined.
///
/// Default Implementation plugin. Adds:
///
/// - [`MiningOverlayConfig`] (defaults, unless the game inserted it earlier);
/// - [`update_mining_overlay`] in `PostUpdate`, in [`MiningOverlaySystems`],
///   before transform and visibility propagation.
///
/// It only reads [`MiningState`], which
/// [`MiningPlugin`](super::mining::MiningPlugin) initializes and
/// [`tick_mining`](super::mining::tick_mining) /
/// [`stop_mining`](super::mining::stop_mining) update. Without that resource
/// the plugin does nothing. It needs `Assets<Mesh>` only when no mesh is
/// configured.
///
/// With the default config nothing is drawn: the game must supply at least
/// one [`MiningOverlayStage`]. See the [module documentation](crate::world::mining_overlay) for an
/// example.
///
/// While the target cannot be broken (hardness `0.0`) progress stays at zero
/// and the first stage is shown for as long as [`MiningState::target`] is
/// set.
pub struct MiningOverlayPlugin;

impl Plugin for MiningOverlayPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<MiningOverlayConfig>().add_systems(
            PostUpdate,
            update_mining_overlay
                .in_set(MiningOverlaySystems)
                .before(TransformSystems::Propagate)
                .before(VisibilitySystems::VisibilityPropagate)
                .before(VisibilitySystems::CalculateBounds),
        );
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    const TARGET_A: (IVec3, (usize, usize, usize)) = (IVec3::ZERO, (1, 2, 3));
    const TARGET_B: (IVec3, (usize, usize, usize)) = (IVec3::new(-1, 2, 0), (15, 0, 7));

    // ── mining_overlay_stage ─────────────────────────────────────────────────

    #[test]
    fn stage_is_none_without_stages() {
        assert_eq!(mining_overlay_stage(0.0, 0), None);
        assert_eq!(mining_overlay_stage(0.5, 0), None);
        assert_eq!(mining_overlay_stage(1.0, 0), None);
    }

    #[test]
    fn stage_is_none_for_nan_progress() {
        assert_eq!(mining_overlay_stage(f32::NAN, 4), None);
    }

    #[test]
    fn stage_splits_progress_evenly() {
        assert_eq!(mining_overlay_stage(0.0, 4), Some(0));
        assert_eq!(mining_overlay_stage(0.24, 4), Some(0));
        assert_eq!(mining_overlay_stage(0.25, 4), Some(1));
        assert_eq!(mining_overlay_stage(0.49, 4), Some(1));
        assert_eq!(mining_overlay_stage(0.5, 4), Some(2));
        assert_eq!(mining_overlay_stage(0.75, 4), Some(3));
        assert_eq!(mining_overlay_stage(0.99, 4), Some(3));
    }

    #[test]
    fn full_progress_is_the_last_stage() {
        for count in 1..=16 {
            assert_eq!(mining_overlay_stage(1.0, count), Some(count - 1));
        }
    }

    #[test]
    fn stage_clamps_out_of_range_progress() {
        assert_eq!(mining_overlay_stage(-0.5, 4), Some(0));
        assert_eq!(mining_overlay_stage(1.5, 4), Some(3));
        assert_eq!(mining_overlay_stage(f32::NEG_INFINITY, 4), Some(0));
        assert_eq!(mining_overlay_stage(f32::INFINITY, 4), Some(3));
    }

    #[test]
    fn single_stage_covers_all_progress() {
        for progress in [0.0, 0.3, 0.999, 1.0] {
            assert_eq!(mining_overlay_stage(progress, 1), Some(0));
        }
    }

    #[test]
    fn stage_never_decreases_and_stays_in_range() {
        for count in [1usize, 2, 3, 5, 10] {
            let mut previous = 0;
            for step in 0..=1000 {
                let progress = step as f32 / 1000.0;
                let stage = mining_overlay_stage(progress, count).unwrap();
                assert!(stage < count);
                assert!(stage >= previous);
                previous = stage;
            }
            assert_eq!(previous, count - 1);
        }
    }

    // ── mining_overlay_transform ─────────────────────────────────────────────

    #[test]
    fn transform_is_centered_on_the_voxel() {
        let transform = mining_overlay_transform(IVec3::ZERO, (0, 0, 0), 1.0);
        assert_eq!(transform.translation, Vec3::splat(0.5));
        assert_eq!(transform.rotation, Quat::IDENTITY);
        assert_eq!(transform.scale, Vec3::ONE);

        let transform = mining_overlay_transform(IVec3::new(1, 0, -1), (2, 3, 4), 1.5);
        assert_eq!(transform.translation, Vec3::new(18.5, 3.5, -11.5));
        assert_eq!(transform.scale, Vec3::splat(1.5));
    }

    #[test]
    fn transform_ignores_invalid_scale() {
        for scale in [0.0, -1.0, f32::NAN, f32::INFINITY] {
            let transform = mining_overlay_transform(IVec3::ZERO, (0, 0, 0), scale);
            assert_eq!(transform.scale, Vec3::ONE);
        }
    }

    // ── desired_overlay ──────────────────────────────────────────────────────

    fn mining(target: (IVec3, (usize, usize, usize)), progress: f32) -> MiningState {
        MiningState {
            target: Some(target),
            progress,
            ..Default::default()
        }
    }

    fn config_with_default_handles(stages: usize) -> MiningOverlayConfig {
        MiningOverlayConfig {
            stages: (0..stages)
                .map(|_| MiningOverlayStage::new(Handle::default()))
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn default_config_draws_nothing() {
        let config = MiningOverlayConfig::default();
        assert!(config.visible);
        assert!(config.stages.is_empty());
        assert!(config.mesh.is_none());
        assert_eq!(config.scale, 1.002);
        assert_eq!(desired_overlay(&mining(TARGET_A, 0.5), &config), None);
    }

    #[test]
    fn desired_overlay_follows_target_and_progress() {
        let config = config_with_default_handles(4);
        assert_eq!(desired_overlay(&MiningState::default(), &config), None);
        assert_eq!(
            desired_overlay(&mining(TARGET_B, 0.6), &config),
            Some(MiningOverlay {
                chunk_coord: TARGET_B.0,
                local: TARGET_B.1,
                stage: 2,
            })
        );
    }

    #[test]
    fn hidden_config_draws_nothing() {
        let config = MiningOverlayConfig {
            visible: false,
            ..config_with_default_handles(4)
        };
        assert_eq!(desired_overlay(&mining(TARGET_A, 0.5), &config), None);
    }

    // ── system ───────────────────────────────────────────────────────────────

    fn app() -> App {
        let mut app = App::new();
        app.init_resource::<Assets<Mesh>>()
            .init_resource::<Assets<StandardMaterial>>()
            .init_resource::<MiningState>()
            .add_plugins(MiningOverlayPlugin);
        app
    }

    fn add_stages(app: &mut App, count: usize) -> Vec<Handle<StandardMaterial>> {
        let materials: Vec<_> = (0..count)
            .map(|_| {
                app.world_mut()
                    .resource_mut::<Assets<StandardMaterial>>()
                    .add(StandardMaterial::default())
            })
            .collect();
        app.world_mut().resource_mut::<MiningOverlayConfig>().stages = materials
            .iter()
            .cloned()
            .map(MiningOverlayStage::new)
            .collect();
        materials
    }

    fn set_mining(app: &mut App, target: Option<(IVec3, (usize, usize, usize))>, progress: f32) {
        let mut state = app.world_mut().resource_mut::<MiningState>();
        state.target = target;
        state.progress = progress;
    }

    type OverlaySnapshot = (
        Entity,
        MiningOverlay,
        Transform,
        Handle<Mesh>,
        Handle<StandardMaterial>,
    );

    fn overlays(app: &mut App) -> Vec<OverlaySnapshot> {
        let world = app.world_mut();
        let mut query = world.query::<(
            Entity,
            &MiningOverlay,
            &Transform,
            &Mesh3d,
            &MeshMaterial3d<StandardMaterial>,
        )>();
        query
            .iter(world)
            .map(|(entity, overlay, transform, mesh, material)| {
                (
                    entity,
                    *overlay,
                    *transform,
                    mesh.0.clone(),
                    material.0.clone(),
                )
            })
            .collect()
    }

    #[test]
    fn no_overlay_without_stages() {
        let mut app = app();
        set_mining(&mut app, Some(TARGET_A), 0.5);
        app.update();
        assert!(overlays(&mut app).is_empty());
    }

    #[test]
    fn no_overlay_while_idle() {
        let mut app = app();
        add_stages(&mut app, 3);
        app.update();
        assert!(overlays(&mut app).is_empty());
    }

    #[test]
    fn overlay_appears_on_the_target_with_the_stage_material() {
        let mut app = app();
        let materials = add_stages(&mut app, 4);
        set_mining(&mut app, Some(TARGET_A), 0.0);
        app.update();

        let found = overlays(&mut app);
        assert_eq!(found.len(), 1);
        let (_, overlay, transform, _, material) = &found[0];
        assert_eq!(overlay.chunk_coord, TARGET_A.0);
        assert_eq!(overlay.local, TARGET_A.1);
        assert_eq!(overlay.stage, 0);
        assert_eq!(*material, materials[0]);
        assert_eq!(transform.translation, Vec3::new(1.5, 2.5, 3.5));
        assert_eq!(transform.scale, Vec3::splat(1.002));
    }

    #[test]
    fn stage_change_swaps_material_on_the_same_entity() {
        let mut app = app();
        let materials = add_stages(&mut app, 4);
        set_mining(&mut app, Some(TARGET_A), 0.1);
        app.update();
        let first = overlays(&mut app);

        set_mining(&mut app, Some(TARGET_A), 0.8);
        app.update();
        let second = overlays(&mut app);

        assert_eq!(second.len(), 1);
        assert_eq!(second[0].0, first[0].0, "the overlay entity is reused");
        assert_eq!(second[0].1.stage, 3);
        assert_eq!(second[0].4, materials[3]);
        assert_eq!(second[0].3, first[0].3, "the shared mesh is kept");
    }

    #[test]
    fn target_change_moves_the_overlay() {
        let mut app = app();
        let materials = add_stages(&mut app, 2);
        set_mining(&mut app, Some(TARGET_A), 0.9);
        app.update();
        let first = overlays(&mut app);

        // tick_mining resets progress when the target changes.
        set_mining(&mut app, Some(TARGET_B), 0.0);
        app.update();
        let second = overlays(&mut app);

        assert_eq!(second.len(), 1);
        assert_eq!(second[0].0, first[0].0);
        assert_eq!(second[0].1.chunk_coord, TARGET_B.0);
        assert_eq!(second[0].1.local, TARGET_B.1);
        assert_eq!(second[0].1.stage, 0);
        assert_eq!(second[0].4, materials[0]);
        assert_eq!(second[0].2.translation, Vec3::new(-0.5, 32.5, 7.5));
    }

    #[test]
    fn overlay_is_removed_when_mining_stops() {
        let mut app = app();
        add_stages(&mut app, 2);
        set_mining(&mut app, Some(TARGET_A), 0.5);
        app.update();
        assert_eq!(overlays(&mut app).len(), 1);

        crate::world::mining::stop_mining(&mut app.world_mut().resource_mut::<MiningState>());
        app.update();
        assert!(overlays(&mut app).is_empty());
    }

    #[test]
    fn overlay_is_removed_when_hidden_or_stages_are_cleared() {
        let mut app = app();
        add_stages(&mut app, 2);
        set_mining(&mut app, Some(TARGET_A), 0.5);
        app.update();
        assert_eq!(overlays(&mut app).len(), 1);

        app.world_mut()
            .resource_mut::<MiningOverlayConfig>()
            .visible = false;
        app.update();
        assert!(overlays(&mut app).is_empty());

        app.world_mut()
            .resource_mut::<MiningOverlayConfig>()
            .visible = true;
        app.update();
        assert_eq!(overlays(&mut app).len(), 1);

        app.world_mut()
            .resource_mut::<MiningOverlayConfig>()
            .stages
            .clear();
        app.update();
        assert!(overlays(&mut app).is_empty());
    }

    #[test]
    fn stage_mesh_overrides_shared_mesh() {
        let mut app = app();
        add_stages(&mut app, 2);
        let (shared, special) = {
            let mut meshes = app.world_mut().resource_mut::<Assets<Mesh>>();
            (
                meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
                meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
            )
        };
        {
            let mut config = app.world_mut().resource_mut::<MiningOverlayConfig>();
            config.mesh = Some(shared.clone());
            config.stages[1].mesh = Some(special.clone());
        }

        set_mining(&mut app, Some(TARGET_A), 0.1);
        app.update();
        assert_eq!(overlays(&mut app)[0].3, shared);

        set_mining(&mut app, Some(TARGET_A), 0.9);
        app.update();
        assert_eq!(overlays(&mut app)[0].3, special);
    }

    #[test]
    fn unchanged_state_does_not_touch_the_overlay() {
        let mut app = app();
        add_stages(&mut app, 4);
        set_mining(&mut app, Some(TARGET_A), 0.3);
        app.update();
        let entity = overlays(&mut app)[0].0;

        fn changed_ticks(app: &App, entity: Entity) -> [bevy::ecs::change_detection::Tick; 4] {
            let entity = app.world().entity(entity);
            [
                entity.get_change_ticks::<MiningOverlay>().unwrap().changed,
                entity.get_change_ticks::<Transform>().unwrap().changed,
                entity.get_change_ticks::<Mesh3d>().unwrap().changed,
                entity
                    .get_change_ticks::<MeshMaterial3d<StandardMaterial>>()
                    .unwrap()
                    .changed,
            ]
        }
        let before = changed_ticks(&app, entity);

        // Progress moves inside the same stage: nothing should be rewritten.
        set_mining(&mut app, Some(TARGET_A), 0.4);
        app.update();
        assert_eq!(changed_ticks(&app, entity), before);

        // A new stage rewrites the stage and the material only.
        set_mining(&mut app, Some(TARGET_A), 0.6);
        app.update();
        let after = changed_ticks(&app, entity);
        assert_ne!(after[0], before[0]);
        assert_eq!(after[1], before[1]);
        assert_eq!(after[2], before[2]);
        assert_ne!(after[3], before[3]);
    }

    #[test]
    fn missing_mining_state_is_not_an_error() {
        let mut app = App::new();
        app.init_resource::<Assets<Mesh>>()
            .add_plugins(MiningOverlayPlugin);
        app.world_mut().resource_mut::<MiningOverlayConfig>().stages =
            vec![MiningOverlayStage::new(Handle::default())];
        app.update();
        assert!(overlays(&mut app).is_empty());
    }

    #[test]
    fn configured_mesh_does_not_need_mesh_assets() {
        // No `Assets<Mesh>`: the default cube cannot be created.
        let mut app = App::new();
        app.init_resource::<MiningState>()
            .add_plugins(MiningOverlayPlugin);
        app.world_mut().resource_mut::<MiningOverlayConfig>().stages =
            vec![MiningOverlayStage::new(Handle::default())];
        set_mining(&mut app, Some(TARGET_A), 0.5);
        app.update();
        assert!(overlays(&mut app).is_empty());

        app.world_mut().resource_mut::<MiningOverlayConfig>().mesh = Some(Handle::default());
        app.update();
        assert_eq!(overlays(&mut app).len(), 1);
    }

    #[test]
    fn game_config_inserted_before_the_plugin_is_kept() {
        let mut app = App::new();
        app.insert_resource(MiningOverlayConfig {
            scale: 1.05,
            ..Default::default()
        })
        .add_plugins(MiningOverlayPlugin);
        assert_eq!(app.world().resource::<MiningOverlayConfig>().scale, 1.05);
    }
}