voxel-framework 0.13.1

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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
//! Ambient particles kept in a volume around the viewer.
//!
//! [`AmbientParticlesPlugin`] keeps a fixed pool of small unlit meshes around
//! [`ViewerPosition`]. The particles have no gravity and no lifetime: each one
//! rests at a fixed place in the world (or drifts slowly in a straight line),
//! so they stream past when the viewer moves and give a sense of motion where
//! nothing else is nearby.
//!
//! The framework only provides the tool. Count, volume, sizes, color and shape
//! come from [`AmbientParticlesConfig`], which the game owns.
//!
//! # How the volume works
//!
//! The particle field is periodic. Every particle has a deterministic *home*
//! inside a cube whose side is twice [`AmbientParticlesConfig::volume_radius`],
//! and it is drawn at the copy of that home nearest to the viewer. When the
//! viewer moves away from a particle, the particle leaves the volume on one
//! side and is recycled on the opposite side. Nothing is stored per particle
//! besides its index, so the placement is a pure function of
//! `(index, viewer, elapsed time, config)`; see [`ambient_particle_state`].
//!
//! Only the sphere of radius `volume_radius` inside that cube is shown.
//! Particles shrink to nothing as they approach the surface of the sphere
//! ([`AmbientParticlesConfig::edge_fade`]), so recycling is never visible as a
//! pop. A sphere fills a little over half of its bounding cube, so on average
//! slightly more than half of [`AmbientParticlesConfig::count`] is visible at
//! one time.
//!
//! # Pooled assets
//!
//! Like the fragment system, all particles share one [`Mesh`] handle and one
//! unlit [`StandardMaterial`] handle, stored in [`AmbientParticleAssets`]. The
//! mesh has unit size and each particle is scaled through its [`Transform`],
//! so particles of different sizes still share the mesh. Entities are spawned
//! once and reused; recycling a particle only rewrites its transform.
//!
//! # Integration
//!
//! The plugin is not part of any convenience bundle. Add it explicitly and
//! keep [`ViewerPosition`] in sync with your camera, as streaming already
//! requires.
//!
//! ```no_run
//! use bevy::prelude::*;
//! use voxel_framework::particles::{
//!     AmbientParticleShape, AmbientParticlesConfig, AmbientParticlesPlugin,
//! };
//!
//! fn main() {
//!     App::new()
//!         .add_plugins(DefaultPlugins)
//!         .insert_resource(AmbientParticlesConfig {
//!             count: 200,
//!             volume_radius: 30.0,
//!             size_range: (0.02, 0.06),
//!             color: Color::srgb(0.8, 0.85, 1.0),
//!             shape: AmbientParticleShape::Sphere,
//!             ..Default::default()
//!         })
//!         .add_plugins(AmbientParticlesPlugin)
//!         .run();
//! }
//! ```

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

use crate::noise::hash3;
use crate::world::ViewerPosition;

// ─── Configuration ───────────────────────────────────────────────────────────

/// Mesh used for every ambient particle.
///
/// The built-in shapes have unit size (a cube of side 1, a sphere of diameter
/// 1) and are scaled per particle by a size taken from
/// [`AmbientParticlesConfig::size_range`]. A [`Custom`](Self::Custom) mesh is
/// scaled the same way, so author it at unit size.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum AmbientParticleShape {
    /// A cube. The default.
    #[default]
    Cube,
    /// A low-detail sphere.
    Sphere,
    /// A mesh provided by the game, for example a quad or a loaded asset.
    Custom(Handle<Mesh>),
}

/// Controls the ambient particles drawn by [`AmbientParticlesPlugin`].
///
/// Insert a customized instance before or after adding the plugin; the plugin
/// only initializes the resource when the game has not inserted one. Changes
/// made at runtime are applied on the next frame: the pool grows or shrinks to
/// `count`, and the shared mesh and material follow `shape` and `color`.
///
/// Values that cannot be used (a non-finite or non-positive `volume_radius`,
/// a zero `count`, `enabled: false`) produce no particles instead of an error.
#[derive(Resource, Debug, Clone, PartialEq)]
pub struct AmbientParticlesConfig {
    /// Whether particles are shown. When `false` the pool is emptied.
    ///
    /// Default: `true`.
    pub enabled: bool,
    /// Number of pooled particle entities.
    ///
    /// The particles are spread over the cube that bounds the volume and only
    /// the ones inside the sphere are visible, so on average a little over
    /// half of them are visible at once. Default: `96`.
    pub count: u32,
    /// Radius of the sphere around the viewer in which particles are visible,
    /// in world units.
    ///
    /// Default: `24.0`.
    pub volume_radius: f32,
    /// Smallest and largest particle size, in world units.
    ///
    /// Each particle gets a fixed size between the two values. The order of
    /// the two values does not matter. Default: `(0.03, 0.08)`.
    pub size_range: (f32, f32),
    /// Base color of the shared unlit material.
    ///
    /// A color with alpha below 1 is drawn with alpha blending. Default:
    /// opaque white.
    pub color: Color,
    /// Mesh shared by all particles. Default: [`AmbientParticleShape::Cube`].
    pub shape: AmbientParticleShape,
    /// Fraction of `volume_radius`, from the surface of the sphere inward,
    /// over which particles shrink to nothing.
    ///
    /// Clamped to `0.0..=1.0`. With `0.0` particles keep their full size up
    /// to the surface and disappear there. Default: `0.25`.
    pub edge_fade: f32,
    /// Speed, in world units per second, at which each particle drifts along
    /// its own fixed direction.
    ///
    /// `0.0` keeps particles at rest in the world, so they only appear to
    /// move when the viewer moves. Default: `0.0`.
    pub drift_speed: f32,
    /// Seed of the particle field. Two configs that differ only in the seed
    /// place their particles differently.
    ///
    /// Default: `0`.
    pub seed: u32,
}

impl Default for AmbientParticlesConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            count: 96,
            volume_radius: 24.0,
            size_range: (0.03, 0.08),
            color: Color::WHITE,
            shape: AmbientParticleShape::Cube,
            edge_fade: 0.25,
            drift_speed: 0.0,
            seed: 0,
        }
    }
}

impl AmbientParticlesConfig {
    /// Number of particles the pool should hold for this configuration.
    ///
    /// Returns `0` when the config is disabled or its `volume_radius` is not
    /// a finite positive number; otherwise returns `count`.
    ///
    /// ```
    /// use voxel_framework::particles::AmbientParticlesConfig;
    ///
    /// let config = AmbientParticlesConfig::default();
    /// assert_eq!(config.active_count(), config.count);
    ///
    /// let disabled = AmbientParticlesConfig {
    ///     enabled: false,
    ///     ..Default::default()
    /// };
    /// assert_eq!(disabled.active_count(), 0);
    /// ```
    pub fn active_count(&self) -> u32 {
        if self.enabled && self.radius().is_some() {
            self.count
        } else {
            0
        }
    }

    /// The volume radius when it is usable.
    fn radius(&self) -> Option<f32> {
        (self.volume_radius.is_finite() && self.volume_radius > 0.0).then_some(self.volume_radius)
    }
}

// ─── Pure placement logic ────────────────────────────────────────────────────

/// Where and how one ambient particle is drawn at a given moment.
///
/// Returned by [`ambient_particle_state`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AmbientParticleState {
    /// World-space position of the particle.
    pub translation: Vec3,
    /// Uniform scale applied to the unit-size shared mesh, in world units.
    /// Zero when the particle is not visible.
    pub scale: f32,
    /// Whether the particle is inside the visible sphere with a non-zero size.
    pub visible: bool,
}

impl AmbientParticleState {
    /// State of a particle that is not drawn.
    const HIDDEN: Self = Self {
        translation: Vec3::ZERO,
        scale: 0.0,
        visible: false,
    };
}

// Hash channels: one independent value per particle and purpose.
const CHANNEL_HOME_X: i32 = 0;
const CHANNEL_HOME_Y: i32 = 1;
const CHANNEL_HOME_Z: i32 = 2;
const CHANNEL_SIZE: i32 = 3;
const CHANNEL_DRIFT_HEIGHT: i32 = 4;
const CHANNEL_DRIFT_ANGLE: i32 = 5;

/// Deterministic value in `[0, 1]` for one particle and channel.
#[inline]
fn particle_hash(index: u32, channel: i32, seed: u32) -> f32 {
    hash3(index as i32, channel, 0, seed)
}

/// Fixed size of particle `index`, in world units.
///
/// The value lies between the two ends of
/// [`AmbientParticlesConfig::size_range`], whatever their order. Negative and
/// non-finite ends are treated as zero.
///
/// ```
/// use voxel_framework::particles::{AmbientParticlesConfig, ambient_particle_size};
///
/// let config = AmbientParticlesConfig {
///     size_range: (0.1, 0.2),
///     ..Default::default()
/// };
/// let size = ambient_particle_size(7, &config);
/// assert!((0.1..=0.2).contains(&size));
/// ```
pub fn ambient_particle_size(index: u32, config: &AmbientParticlesConfig) -> f32 {
    let sanitize = |value: f32| {
        if value.is_finite() {
            value.max(0.0)
        } else {
            0.0
        }
    };
    let a = sanitize(config.size_range.0);
    let b = sanitize(config.size_range.1);
    let (low, high) = (a.min(b), a.max(b));
    low + (high - low) * particle_hash(index, CHANNEL_SIZE, config.seed)
}

/// Fixed unit direction along which particle `index` drifts.
fn drift_direction(index: u32, seed: u32) -> Vec3 {
    // Uniform on the sphere: uniform height, uniform angle around the axis.
    let height = particle_hash(index, CHANNEL_DRIFT_HEIGHT, seed) * 2.0 - 1.0;
    let angle = particle_hash(index, CHANNEL_DRIFT_ANGLE, seed) * std::f32::consts::TAU;
    let ring = (1.0 - height * height).max(0.0).sqrt();
    Vec3::new(ring * angle.cos(), height, ring * angle.sin())
}

/// Moves `value` by whole periods of `2 * radius` so that it lies within
/// `radius` of `center`.
///
/// The result is `value` plus a whole number of periods, so it does not
/// depend on `center` while the particle stays in the same copy of the field:
/// a resting particle keeps exactly the same world coordinate as the viewer
/// moves around it.
#[inline]
fn wrap_axis(value: f32, center: f32, radius: f32) -> f32 {
    let period = 2.0 * radius;
    value + ((center - value) / period).round() * period
}

/// Computes where particle `index` is drawn for a viewer position and time.
///
/// This is the whole spawn/advance/recycle rule of the ambient particle
/// system, as a pure function: the same arguments always give the same
/// result, on every platform, and no state is kept between calls.
///
/// - The particle's home is hashed from `index` and
///   [`AmbientParticlesConfig::seed`], then moved along its drift direction by
///   `drift_speed * elapsed_secs`.
/// - The result is wrapped, per axis, to the copy nearest to `viewer`. This is
///   the recycling step: a particle further than `volume_radius` along an
///   axis reappears on the opposite side.
/// - Particles outside the sphere of radius `volume_radius` are not visible,
///   and the ones near its surface are scaled down by
///   [`AmbientParticlesConfig::edge_fade`].
///
/// With `drift_speed == 0.0` a particle's world position does not change
/// while it stays inside the volume, so it streams past a moving viewer.
///
/// A config with an unusable `volume_radius`, or a non-finite `viewer`, gives
/// a hidden state.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::particles::{AmbientParticlesConfig, ambient_particle_state};
///
/// let config = AmbientParticlesConfig::default();
/// let viewer = Vec3::new(100.0, 0.0, -40.0);
/// let state = ambient_particle_state(3, viewer, 0.0, &config);
///
/// // Deterministic, and never further than the volume allows on any axis.
/// assert_eq!(state, ambient_particle_state(3, viewer, 0.0, &config));
/// let offset = (state.translation - viewer).abs();
/// assert!(offset.max_element() <= config.volume_radius + 1e-3);
/// ```
pub fn ambient_particle_state(
    index: u32,
    viewer: Vec3,
    elapsed_secs: f32,
    config: &AmbientParticlesConfig,
) -> AmbientParticleState {
    let Some(radius) = config.radius() else {
        return AmbientParticleState::HIDDEN;
    };
    if !viewer.is_finite() {
        return AmbientParticleState::HIDDEN;
    }

    let seed = config.seed;
    let period = 2.0 * radius;
    // `Vec3::is_finite` above keeps the wrap below free of NaN.
    let mut home = Vec3::new(
        particle_hash(index, CHANNEL_HOME_X, seed),
        particle_hash(index, CHANNEL_HOME_Y, seed),
        particle_hash(index, CHANNEL_HOME_Z, seed),
    ) * period;

    let drift = config.drift_speed * elapsed_secs;
    if drift.is_finite() && drift != 0.0 {
        home += drift_direction(index, seed) * drift;
    }

    let translation = Vec3::new(
        wrap_axis(home.x, viewer.x, radius),
        wrap_axis(home.y, viewer.y, radius),
        wrap_axis(home.z, viewer.z, radius),
    );

    let distance = translation.distance(viewer);
    if !distance.is_finite() || distance >= radius {
        return AmbientParticleState {
            translation,
            scale: 0.0,
            visible: false,
        };
    }

    let fade = if config.edge_fade.is_finite() {
        config.edge_fade.clamp(0.0, 1.0)
    } else {
        0.0
    };
    let band = fade * radius;
    let factor = if band > 0.0 {
        ((radius - distance) / band).clamp(0.0, 1.0)
    } else {
        1.0
    };
    let scale = ambient_particle_size(index, config) * factor;

    AmbientParticleState {
        translation,
        scale,
        visible: scale > 0.0,
    }
}

// ─── Components and resources ────────────────────────────────────────────────

/// Marks an entity of the ambient particle pool.
///
/// The plugin owns these entities: it spawns them, rewrites their
/// [`Transform`] and [`Visibility`] every frame, and despawns them when the
/// pool shrinks. Query the component to count them or to add your own
/// components (for example render layers).
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
pub struct AmbientParticle {
    /// Stable slot of the particle in the pool, in `0..count`. It is the
    /// `index` passed to [`ambient_particle_state`].
    pub index: u32,
}

/// Shared asset handles used by all ambient particle entities.
///
/// Inserted by [`AmbientParticlesPlugin`] the first time particles are
/// active, and kept in sync with [`AmbientParticlesConfig::shape`] and
/// [`AmbientParticlesConfig::color`].
#[derive(Resource, Debug, Clone)]
pub struct AmbientParticleAssets {
    /// Handle to the shared unit-size mesh. For
    /// [`AmbientParticleShape::Custom`] it is the game's own handle.
    pub mesh: Handle<Mesh>,
    /// Handle to the shared unlit material.
    pub material: Handle<StandardMaterial>,
    /// Shape the current `mesh` was built for.
    shape: AmbientParticleShape,
}

/// System set of the ambient particle systems, in `PostUpdate`.
///
/// The systems run before transform and visibility propagation, so a
/// [`ViewerPosition`] written in `Update` is used in the same frame. Order
/// your own `PostUpdate` systems against this set when they write
/// [`ViewerPosition`] or read particle transforms.
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AmbientParticleSystems;

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

/// Builds the shared mesh for a shape.
fn shape_mesh(shape: &AmbientParticleShape, meshes: &mut Assets<Mesh>) -> Handle<Mesh> {
    match shape {
        AmbientParticleShape::Cube => meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
        AmbientParticleShape::Sphere => meshes.add(Sphere::new(0.5)),
        AmbientParticleShape::Custom(handle) => handle.clone(),
    }
}

/// Builds the shared unlit material for a color.
fn particle_material(color: Color) -> StandardMaterial {
    StandardMaterial {
        base_color: color,
        unlit: true,
        alpha_mode: if color.to_linear().alpha < 1.0 {
            AlphaMode::Blend
        } else {
            AlphaMode::Opaque
        },
        ..default()
    }
}

/// Allocates the shared assets on first use and keeps them in sync with the
/// config afterwards.
fn sync_ambient_particle_assets(
    mut commands: Commands,
    config: Res<AmbientParticlesConfig>,
    assets: Option<ResMut<AmbientParticleAssets>>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut particles: Query<&mut Mesh3d, With<AmbientParticle>>,
) {
    let Some(mut assets) = assets else {
        if config.active_count() == 0 {
            return;
        }
        let mesh = shape_mesh(&config.shape, &mut meshes);
        let material = materials.add(particle_material(config.color));
        commands.insert_resource(AmbientParticleAssets {
            mesh,
            material,
            shape: config.shape.clone(),
        });
        return;
    };

    if !config.is_changed() {
        return;
    }

    if assets.shape != config.shape {
        let mesh = shape_mesh(&config.shape, &mut meshes);
        for mut particle_mesh in &mut particles {
            particle_mesh.0 = mesh.clone();
        }
        assets.mesh = mesh;
        assets.shape = config.shape.clone();
    }

    // Read first: `get_mut` marks the asset as modified even when nothing changes.
    let color_changed = materials
        .get(&assets.material)
        .is_some_and(|material| material.base_color != config.color);
    if color_changed && let Some(material) = materials.get_mut(&assets.material) {
        *material = particle_material(config.color);
    }
}

/// Grows or shrinks the pool to [`AmbientParticlesConfig::active_count`].
fn sync_ambient_particle_pool(
    mut commands: Commands,
    config: Res<AmbientParticlesConfig>,
    assets: Option<Res<AmbientParticleAssets>>,
    particles: Query<(Entity, &AmbientParticle)>,
) {
    let target = config.active_count();

    let mut kept = 0u32;
    for (entity, particle) in &particles {
        if particle.index < target {
            kept += 1;
        } else {
            commands.entity(entity).despawn();
        }
    }
    if kept == target {
        return;
    }
    let Some(assets) = assets else {
        return;
    };

    // Slots can be missing in any position (a game may despawn a particle),
    // and a slot can be taken twice if a game spawns the marker itself.
    let mut taken = vec![false; target as usize];
    for (entity, particle) in &particles {
        let Some(slot) = taken.get_mut(particle.index as usize) else {
            continue;
        };
        if *slot {
            commands.entity(entity).despawn();
        } else {
            *slot = true;
        }
    }

    for (index, slot) in taken.iter().enumerate() {
        if *slot {
            continue;
        }
        // Spawned hidden; `update_ambient_particles` places it in this frame.
        commands.spawn((
            AmbientParticle {
                index: index as u32,
            },
            Mesh3d(assets.mesh.clone()),
            MeshMaterial3d(assets.material.clone()),
            Transform::from_scale(Vec3::ZERO),
            Visibility::Hidden,
            NotShadowCaster,
        ));
    }
}

/// Places every pooled particle from [`ambient_particle_state`].
fn update_ambient_particles(
    viewer: Res<ViewerPosition>,
    time: Res<Time>,
    config: Res<AmbientParticlesConfig>,
    mut particles: Query<(&AmbientParticle, &mut Transform, &mut Visibility)>,
) {
    let elapsed = time.elapsed_secs();

    for (particle, mut transform, mut visibility) in &mut particles {
        let state = ambient_particle_state(particle.index, viewer.position, elapsed, &config);

        // Write only on change, so a resting field does not look changed
        // every frame.
        let scale = Vec3::splat(state.scale);
        if transform.translation != state.translation || transform.scale != scale {
            transform.translation = state.translation;
            transform.scale = scale;
        }
        let wanted = if state.visible {
            Visibility::Inherited
        } else {
            Visibility::Hidden
        };
        if *visibility != wanted {
            *visibility = wanted;
        }
    }
}

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

/// Plugin that keeps sparse unlit particles in a volume around the viewer.
///
/// Category: Default Implementation. It is not included in `VoxelCorePlugin`
/// or `VoxelPlugin`; add it explicitly.
///
/// # What it registers
///
/// * [`AmbientParticlesConfig`] — initialized with its default unless the
///   game inserted one.
/// * [`ViewerPosition`] — initialized if missing, so the plugin also works
///   without the world plugins. The game still has to write it; the framework
///   never discovers a camera or a player.
/// * Three chained `PostUpdate` systems in [`AmbientParticleSystems`], before
///   transform and visibility propagation: shared asset upkeep
///   ([`AmbientParticleAssets`]), pool upkeep ([`AmbientParticle`] entities),
///   and placement.
///
/// It requires `Assets<Mesh>`, `Assets<StandardMaterial>` and `Time`, which
/// `DefaultPlugins` provide.
///
/// # Examples
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// fn follow_camera(
///     camera: Query<&GlobalTransform, With<Camera3d>>,
///     mut viewer: ResMut<ViewerPosition>,
/// ) {
///     if let Ok(transform) = camera.single() {
///         viewer.position = transform.translation();
///     }
/// }
///
/// fn main() {
///     App::new()
///         .add_plugins(DefaultPlugins)
///         .add_plugins(AmbientParticlesPlugin)
///         .add_systems(Update, follow_camera)
///         .run();
/// }
/// ```
pub struct AmbientParticlesPlugin;

impl Plugin for AmbientParticlesPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<AmbientParticlesConfig>()
            .init_resource::<ViewerPosition>()
            .add_systems(
                PostUpdate,
                (
                    sync_ambient_particle_assets,
                    sync_ambient_particle_pool,
                    update_ambient_particles,
                )
                    .chain()
                    .in_set(AmbientParticleSystems)
                    .before(TransformSystems::Propagate)
                    .before(VisibilitySystems::VisibilityPropagate)
                    .before(VisibilitySystems::CalculateBounds),
            );
    }
}

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

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

    const EPS: f32 = 1e-3;

    fn config() -> AmbientParticlesConfig {
        AmbientParticlesConfig {
            count: 200,
            volume_radius: 10.0,
            size_range: (0.1, 0.3),
            ..default()
        }
    }

    // ── Pure logic ───────────────────────────────────────────────────────────

    #[test]
    fn defaults_are_documented_values() {
        let config = AmbientParticlesConfig::default();
        assert!(config.enabled);
        assert_eq!(config.count, 96);
        assert_eq!(config.volume_radius, 24.0);
        assert_eq!(config.size_range, (0.03, 0.08));
        assert_eq!(config.color, Color::WHITE);
        assert_eq!(config.shape, AmbientParticleShape::Cube);
        assert_eq!(config.edge_fade, 0.25);
        assert_eq!(config.drift_speed, 0.0);
        assert_eq!(config.seed, 0);
    }

    #[test]
    fn state_is_deterministic() {
        let config = config();
        let viewer = Vec3::new(3.5, -120.25, 77.0);
        for index in 0..config.count {
            assert_eq!(
                ambient_particle_state(index, viewer, 1.5, &config),
                ambient_particle_state(index, viewer, 1.5, &config)
            );
        }
    }

    #[test]
    fn particles_stay_within_the_volume_on_every_axis() {
        let config = config();
        for viewer in [
            Vec3::ZERO,
            Vec3::new(1234.5, -987.25, 42.0),
            Vec3::new(-5000.0, 5000.0, -0.5),
        ] {
            for index in 0..config.count {
                let state = ambient_particle_state(index, viewer, 0.0, &config);
                let offset = (state.translation - viewer).abs();
                // Looser than EPS: f32 spacing is about 5e-4 at 5000 units.
                assert!(
                    offset.max_element() <= config.volume_radius + 1e-2,
                    "particle {index} at {offset:?} from viewer {viewer:?}"
                );
            }
        }
    }

    #[test]
    fn visible_particles_are_inside_the_sphere() {
        let config = config();
        let viewer = Vec3::new(10.0, 20.0, 30.0);
        let mut visible = 0;
        for index in 0..config.count {
            let state = ambient_particle_state(index, viewer, 0.0, &config);
            let distance = state.translation.distance(viewer);
            if state.visible {
                visible += 1;
                assert!(distance < config.volume_radius);
                assert!(state.scale > 0.0);
            } else {
                assert_eq!(state.scale, 0.0);
            }
        }
        // The sphere fills about 52% of its bounding cube.
        assert!(
            (60..=150).contains(&visible),
            "{visible} of 200 particles visible"
        );
    }

    #[test]
    fn resting_particles_keep_their_world_position_until_recycled() {
        let config = config();
        let before = Vec3::ZERO;
        let after = Vec3::new(1.0, 0.0, 0.0);
        let mut unchanged = 0;
        let mut recycled = 0;
        for index in 0..config.count {
            let a = ambient_particle_state(index, before, 0.0, &config).translation;
            let b = ambient_particle_state(index, after, 5.0, &config).translation;
            if a.distance(b) < EPS {
                unchanged += 1;
            } else {
                recycled += 1;
                // Recycled across the volume along the direction of travel.
                assert!((b.x - a.x - 2.0 * config.volume_radius).abs() < EPS);
                assert!((b.y - a.y).abs() < EPS);
                assert!((b.z - a.z).abs() < EPS);
            }
        }
        assert!(unchanged > recycled);
        assert!(unchanged + recycled == config.count);
    }

    #[test]
    fn moving_one_full_period_gives_the_same_relative_field() {
        let config = config();
        let shift = Vec3::new(2.0 * config.volume_radius, 0.0, 0.0);
        for index in 0..config.count {
            let a = ambient_particle_state(index, Vec3::ZERO, 0.0, &config);
            let b = ambient_particle_state(index, shift, 0.0, &config);
            assert!((b.translation - shift).distance(a.translation) < EPS);
        }
    }

    #[test]
    fn sizes_stay_in_range_whatever_the_order() {
        let forward = config();
        let reversed = AmbientParticlesConfig {
            size_range: (0.3, 0.1),
            ..config()
        };
        let mut smallest = f32::MAX;
        let mut largest = f32::MIN;
        for index in 0..forward.count {
            let size = ambient_particle_size(index, &forward);
            assert!((0.1..=0.3).contains(&size));
            assert_eq!(size, ambient_particle_size(index, &reversed));
            smallest = smallest.min(size);
            largest = largest.max(size);
        }
        assert!(largest - smallest > 0.1, "sizes should vary");
    }

    #[test]
    fn unusable_sizes_become_zero() {
        let config = AmbientParticlesConfig {
            size_range: (f32::NAN, -1.0),
            ..config()
        };
        assert_eq!(ambient_particle_size(0, &config), 0.0);
        assert!(!ambient_particle_state(0, Vec3::ZERO, 0.0, &config).visible);
    }

    #[test]
    fn edge_fade_shrinks_particles_near_the_surface() {
        let faded = AmbientParticlesConfig {
            edge_fade: 0.5,
            ..config()
        };
        let hard = AmbientParticlesConfig {
            edge_fade: 0.0,
            ..config()
        };
        let band_start = faded.volume_radius * 0.5;
        let mut shrunk = 0;
        for index in 0..faded.count {
            let state = ambient_particle_state(index, Vec3::ZERO, 0.0, &faded);
            let full = ambient_particle_size(index, &faded);
            let distance = state.translation.length();
            if !state.visible {
                continue;
            }
            // Without a fade every visible particle has its full size.
            let unfaded = ambient_particle_state(index, Vec3::ZERO, 0.0, &hard);
            assert_eq!(unfaded.scale, full);
            if distance <= band_start {
                assert_eq!(state.scale, full);
            } else {
                assert!(state.scale <= full);
                if state.scale < full {
                    shrunk += 1;
                }
            }
        }
        assert!(shrunk > 0);
    }

    #[test]
    fn drift_moves_particles_at_the_configured_speed() {
        let config = AmbientParticlesConfig {
            drift_speed: 0.5,
            ..config()
        };
        let mut checked = 0;
        for index in 0..config.count {
            let a = ambient_particle_state(index, Vec3::ZERO, 0.0, &config).translation;
            let b = ambient_particle_state(index, Vec3::ZERO, 1.0, &config).translation;
            let moved = a.distance(b);
            // Particles that crossed a face were recycled; skip those.
            if moved < 1.0 {
                assert!((moved - 0.5).abs() < EPS, "particle {index} moved {moved}");
                checked += 1;
            }
        }
        assert!(checked > config.count / 2);
    }

    #[test]
    fn drift_directions_are_unit_length_and_varied() {
        let first = drift_direction(0, 0);
        let mut varied = false;
        for index in 0..64 {
            let direction = drift_direction(index, 0);
            assert!((direction.length() - 1.0).abs() < EPS);
            varied |= direction.distance(first) > 0.5;
        }
        assert!(varied);
    }

    #[test]
    fn seed_changes_the_field() {
        let a = config();
        let b = AmbientParticlesConfig {
            seed: 1,
            ..config()
        };
        let differing = (0..a.count)
            .filter(|&index| {
                ambient_particle_state(index, Vec3::ZERO, 0.0, &a).translation
                    != ambient_particle_state(index, Vec3::ZERO, 0.0, &b).translation
            })
            .count();
        assert!(differing > 190);
    }

    #[test]
    fn unusable_configs_and_viewers_hide_everything() {
        for volume_radius in [0.0, -4.0, f32::NAN, f32::INFINITY] {
            let config = AmbientParticlesConfig {
                volume_radius,
                ..config()
            };
            assert_eq!(config.active_count(), 0);
            let state = ambient_particle_state(0, Vec3::ZERO, 0.0, &config);
            assert_eq!(state, AmbientParticleState::HIDDEN);
        }
        let disabled = AmbientParticlesConfig {
            enabled: false,
            ..config()
        };
        assert_eq!(disabled.active_count(), 0);

        let state = ambient_particle_state(0, Vec3::splat(f32::NAN), 0.0, &config());
        assert_eq!(state, AmbientParticleState::HIDDEN);
    }

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

    fn app(config: AmbientParticlesConfig) -> App {
        let mut app = App::new();
        app.init_resource::<Time>()
            .init_resource::<Assets<Mesh>>()
            .init_resource::<Assets<StandardMaterial>>()
            .insert_resource(config)
            .add_plugins(AmbientParticlesPlugin);
        app
    }

    fn particles(app: &mut App) -> Vec<(u32, Transform, Visibility)> {
        let world = app.world_mut();
        let mut query = world.query::<(&AmbientParticle, &Transform, &Visibility)>();
        let mut found: Vec<_> = query
            .iter(world)
            .map(|(particle, transform, visibility)| (particle.index, *transform, *visibility))
            .collect();
        found.sort_by_key(|(index, _, _)| *index);
        found
    }

    #[test]
    fn plugin_keeps_an_inserted_config_and_initializes_the_viewer() {
        let mut app = app(config());
        app.update();
        assert_eq!(app.world().resource::<AmbientParticlesConfig>().count, 200);
        assert!(app.world().get_resource::<ViewerPosition>().is_some());
    }

    #[test]
    fn pool_matches_count_and_follows_the_pure_placement() {
        let mut app = app(config());
        app.world_mut().resource_mut::<ViewerPosition>().position = Vec3::new(50.0, 0.0, 0.0);
        app.update();
        app.update();

        let config = config();
        let found = particles(&mut app);
        assert_eq!(found.len(), 200);
        for (slot, (index, transform, visibility)) in found.iter().enumerate() {
            assert_eq!(*index, slot as u32);
            let state = ambient_particle_state(*index, Vec3::new(50.0, 0.0, 0.0), 0.0, &config);
            assert_eq!(transform.translation, state.translation);
            assert_eq!(transform.scale, Vec3::splat(state.scale));
            assert_eq!(*visibility == Visibility::Inherited, state.visible);
        }
    }

    #[test]
    fn particles_share_one_mesh_and_one_material() {
        let mut app = app(config());
        app.update();
        app.update();

        let assets = app.world().resource::<AmbientParticleAssets>().clone();
        let world = app.world_mut();
        let mut query = world
            .query_filtered::<(&Mesh3d, &MeshMaterial3d<StandardMaterial>), With<AmbientParticle>>(
            );
        let mut seen = 0;
        for (mesh, material) in query.iter(world) {
            assert_eq!(mesh.0, assets.mesh);
            assert_eq!(material.0, assets.material);
            seen += 1;
        }
        assert_eq!(seen, 200);
        assert_eq!(world.resource::<Assets<Mesh>>().len(), 1);
        assert_eq!(world.resource::<Assets<StandardMaterial>>().len(), 1);

        let material = world
            .resource::<Assets<StandardMaterial>>()
            .get(&assets.material)
            .expect("shared material exists");
        assert!(material.unlit);
        assert_eq!(material.base_color, Color::WHITE);
    }

    #[test]
    fn pool_follows_count_and_enabled_changes() {
        let mut app = app(config());
        app.update();
        app.update();
        assert_eq!(particles(&mut app).len(), 200);

        app.world_mut()
            .resource_mut::<AmbientParticlesConfig>()
            .count = 50;
        app.update();
        app.update();
        let found = particles(&mut app);
        assert_eq!(found.len(), 50);
        assert!(found.iter().all(|(index, _, _)| *index < 50));

        app.world_mut()
            .resource_mut::<AmbientParticlesConfig>()
            .count = 80;
        app.update();
        app.update();
        let found = particles(&mut app);
        assert_eq!(found.len(), 80);
        assert!(
            found
                .iter()
                .enumerate()
                .all(|(slot, (index, _, _))| *index == slot as u32)
        );

        app.world_mut()
            .resource_mut::<AmbientParticlesConfig>()
            .enabled = false;
        app.update();
        app.update();
        assert!(particles(&mut app).is_empty());
    }

    #[test]
    fn disabled_plugin_allocates_nothing() {
        let mut app = app(AmbientParticlesConfig {
            enabled: false,
            ..config()
        });
        app.update();
        app.update();
        assert!(particles(&mut app).is_empty());
        assert!(
            app.world()
                .get_resource::<AmbientParticleAssets>()
                .is_none()
        );
        assert_eq!(app.world().resource::<Assets<Mesh>>().len(), 0);
    }

    #[test]
    fn a_missing_slot_is_refilled() {
        let mut app = app(config());
        app.update();
        app.update();

        let world = app.world_mut();
        let mut query = world.query::<(Entity, &AmbientParticle)>();
        let victim = query
            .iter(world)
            .find(|(_, particle)| particle.index == 7)
            .map(|(entity, _)| entity)
            .expect("slot 7 exists");
        world.despawn(victim);

        app.update();
        app.update();
        let found = particles(&mut app);
        assert_eq!(found.len(), 200);
        assert_eq!(found[7].0, 7);
    }

    #[test]
    fn color_and_shape_changes_update_the_shared_assets() {
        let mut app = app(config());
        app.update();
        app.update();
        let before = app.world().resource::<AmbientParticleAssets>().clone();

        let translucent = Color::srgba(1.0, 0.5, 0.25, 0.5);
        {
            let mut config = app.world_mut().resource_mut::<AmbientParticlesConfig>();
            config.color = translucent;
            config.shape = AmbientParticleShape::Sphere;
        }
        app.update();
        app.update();

        let after = app.world().resource::<AmbientParticleAssets>().clone();
        assert_eq!(
            after.material, before.material,
            "material is edited in place"
        );
        assert_ne!(after.mesh, before.mesh, "a new shape needs a new mesh");

        let world = app.world_mut();
        let material = world
            .resource::<Assets<StandardMaterial>>()
            .get(&after.material)
            .expect("shared material exists");
        assert_eq!(material.base_color, translucent);
        assert_eq!(material.alpha_mode, AlphaMode::Blend);

        let mut query = world.query_filtered::<&Mesh3d, With<AmbientParticle>>();
        assert!(query.iter(world).all(|mesh| mesh.0 == after.mesh));
    }

    #[test]
    fn particles_stream_past_a_moving_viewer() {
        let mut app = app(config());
        app.update();
        app.update();
        let before = particles(&mut app);

        app.world_mut().resource_mut::<ViewerPosition>().position = Vec3::new(0.5, 0.0, 0.0);
        app.update();
        let after = particles(&mut app);

        // Most particles did not move in the world, so relative to the viewer
        // they moved backwards.
        let still = before
            .iter()
            .zip(&after)
            .filter(|(a, b)| a.1.translation == b.1.translation)
            .count();
        assert!(still > 180, "{still} of 200 particles kept their position");
    }
}