Skip to main content

voxel_framework/particles/
mod.rs

1//! Ambient particles kept in a volume around the viewer.
2//!
3//! [`AmbientParticlesPlugin`] keeps a fixed pool of small unlit meshes around
4//! [`ViewerPosition`]. The particles have no gravity and no lifetime: each one
5//! rests at a fixed place in the world (or drifts slowly in a straight line),
6//! so they stream past when the viewer moves and give a sense of motion where
7//! nothing else is nearby.
8//!
9//! The framework only provides the tool. Count, volume, sizes, color and shape
10//! come from [`AmbientParticlesConfig`], which the game owns.
11//!
12//! # How the volume works
13//!
14//! The particle field is periodic. Every particle has a deterministic *home*
15//! inside a cube whose side is twice [`AmbientParticlesConfig::volume_radius`],
16//! and it is drawn at the copy of that home nearest to the viewer. When the
17//! viewer moves away from a particle, the particle leaves the volume on one
18//! side and is recycled on the opposite side. Nothing is stored per particle
19//! besides its index, so the placement is a pure function of
20//! `(index, viewer, elapsed time, config)`; see [`ambient_particle_state`].
21//!
22//! Only the sphere of radius `volume_radius` inside that cube is shown.
23//! Particles shrink to nothing as they approach the surface of the sphere
24//! ([`AmbientParticlesConfig::edge_fade`]), so recycling is never visible as a
25//! pop. A sphere fills a little over half of its bounding cube, so on average
26//! slightly more than half of [`AmbientParticlesConfig::count`] is visible at
27//! one time.
28//!
29//! # Pooled assets
30//!
31//! Like the fragment system, all particles share one [`Mesh`] handle and one
32//! unlit [`StandardMaterial`] handle, stored in [`AmbientParticleAssets`]. The
33//! mesh has unit size and each particle is scaled through its [`Transform`],
34//! so particles of different sizes still share the mesh. Entities are spawned
35//! once and reused; recycling a particle only rewrites its transform.
36//!
37//! # Integration
38//!
39//! The plugin is not part of any convenience bundle. Add it explicitly and
40//! keep [`ViewerPosition`] in sync with your camera, as streaming already
41//! requires.
42//!
43//! ```no_run
44//! use bevy::prelude::*;
45//! use voxel_framework::particles::{
46//!     AmbientParticleShape, AmbientParticlesConfig, AmbientParticlesPlugin,
47//! };
48//!
49//! fn main() {
50//!     App::new()
51//!         .add_plugins(DefaultPlugins)
52//!         .insert_resource(AmbientParticlesConfig {
53//!             count: 200,
54//!             volume_radius: 30.0,
55//!             size_range: (0.02, 0.06),
56//!             color: Color::srgb(0.8, 0.85, 1.0),
57//!             shape: AmbientParticleShape::Sphere,
58//!             ..Default::default()
59//!         })
60//!         .add_plugins(AmbientParticlesPlugin)
61//!         .run();
62//! }
63//! ```
64
65use bevy::camera::visibility::VisibilitySystems;
66use bevy::light::NotShadowCaster;
67use bevy::prelude::*;
68use bevy::transform::TransformSystems;
69
70use crate::noise::hash3;
71use crate::world::ViewerPosition;
72
73// ─── Configuration ───────────────────────────────────────────────────────────
74
75/// Mesh used for every ambient particle.
76///
77/// The built-in shapes have unit size (a cube of side 1, a sphere of diameter
78/// 1) and are scaled per particle by a size taken from
79/// [`AmbientParticlesConfig::size_range`]. A [`Custom`](Self::Custom) mesh is
80/// scaled the same way, so author it at unit size.
81#[derive(Debug, Clone, PartialEq, Default)]
82pub enum AmbientParticleShape {
83    /// A cube. The default.
84    #[default]
85    Cube,
86    /// A low-detail sphere.
87    Sphere,
88    /// A mesh provided by the game, for example a quad or a loaded asset.
89    Custom(Handle<Mesh>),
90}
91
92/// Controls the ambient particles drawn by [`AmbientParticlesPlugin`].
93///
94/// Insert a customized instance before or after adding the plugin; the plugin
95/// only initializes the resource when the game has not inserted one. Changes
96/// made at runtime are applied on the next frame: the pool grows or shrinks to
97/// `count`, and the shared mesh and material follow `shape` and `color`.
98///
99/// Values that cannot be used (a non-finite or non-positive `volume_radius`,
100/// a zero `count`, `enabled: false`) produce no particles instead of an error.
101#[derive(Resource, Debug, Clone, PartialEq)]
102pub struct AmbientParticlesConfig {
103    /// Whether particles are shown. When `false` the pool is emptied.
104    ///
105    /// Default: `true`.
106    pub enabled: bool,
107    /// Number of pooled particle entities.
108    ///
109    /// The particles are spread over the cube that bounds the volume and only
110    /// the ones inside the sphere are visible, so on average a little over
111    /// half of them are visible at once. Default: `96`.
112    pub count: u32,
113    /// Radius of the sphere around the viewer in which particles are visible,
114    /// in world units.
115    ///
116    /// Default: `24.0`.
117    pub volume_radius: f32,
118    /// Smallest and largest particle size, in world units.
119    ///
120    /// Each particle gets a fixed size between the two values. The order of
121    /// the two values does not matter. Default: `(0.03, 0.08)`.
122    pub size_range: (f32, f32),
123    /// Base color of the shared unlit material.
124    ///
125    /// A color with alpha below 1 is drawn with alpha blending. Default:
126    /// opaque white.
127    pub color: Color,
128    /// Mesh shared by all particles. Default: [`AmbientParticleShape::Cube`].
129    pub shape: AmbientParticleShape,
130    /// Fraction of `volume_radius`, from the surface of the sphere inward,
131    /// over which particles shrink to nothing.
132    ///
133    /// Clamped to `0.0..=1.0`. With `0.0` particles keep their full size up
134    /// to the surface and disappear there. Default: `0.25`.
135    pub edge_fade: f32,
136    /// Speed, in world units per second, at which each particle drifts along
137    /// its own fixed direction.
138    ///
139    /// `0.0` keeps particles at rest in the world, so they only appear to
140    /// move when the viewer moves. Default: `0.0`.
141    pub drift_speed: f32,
142    /// Seed of the particle field. Two configs that differ only in the seed
143    /// place their particles differently.
144    ///
145    /// Default: `0`.
146    pub seed: u32,
147}
148
149impl Default for AmbientParticlesConfig {
150    fn default() -> Self {
151        Self {
152            enabled: true,
153            count: 96,
154            volume_radius: 24.0,
155            size_range: (0.03, 0.08),
156            color: Color::WHITE,
157            shape: AmbientParticleShape::Cube,
158            edge_fade: 0.25,
159            drift_speed: 0.0,
160            seed: 0,
161        }
162    }
163}
164
165impl AmbientParticlesConfig {
166    /// Number of particles the pool should hold for this configuration.
167    ///
168    /// Returns `0` when the config is disabled or its `volume_radius` is not
169    /// a finite positive number; otherwise returns `count`.
170    ///
171    /// ```
172    /// use voxel_framework::particles::AmbientParticlesConfig;
173    ///
174    /// let config = AmbientParticlesConfig::default();
175    /// assert_eq!(config.active_count(), config.count);
176    ///
177    /// let disabled = AmbientParticlesConfig {
178    ///     enabled: false,
179    ///     ..Default::default()
180    /// };
181    /// assert_eq!(disabled.active_count(), 0);
182    /// ```
183    pub fn active_count(&self) -> u32 {
184        if self.enabled && self.radius().is_some() {
185            self.count
186        } else {
187            0
188        }
189    }
190
191    /// The volume radius when it is usable.
192    fn radius(&self) -> Option<f32> {
193        (self.volume_radius.is_finite() && self.volume_radius > 0.0).then_some(self.volume_radius)
194    }
195}
196
197// ─── Pure placement logic ────────────────────────────────────────────────────
198
199/// Where and how one ambient particle is drawn at a given moment.
200///
201/// Returned by [`ambient_particle_state`].
202#[derive(Debug, Clone, Copy, PartialEq)]
203pub struct AmbientParticleState {
204    /// World-space position of the particle.
205    pub translation: Vec3,
206    /// Uniform scale applied to the unit-size shared mesh, in world units.
207    /// Zero when the particle is not visible.
208    pub scale: f32,
209    /// Whether the particle is inside the visible sphere with a non-zero size.
210    pub visible: bool,
211}
212
213impl AmbientParticleState {
214    /// State of a particle that is not drawn.
215    const HIDDEN: Self = Self {
216        translation: Vec3::ZERO,
217        scale: 0.0,
218        visible: false,
219    };
220}
221
222// Hash channels: one independent value per particle and purpose.
223const CHANNEL_HOME_X: i32 = 0;
224const CHANNEL_HOME_Y: i32 = 1;
225const CHANNEL_HOME_Z: i32 = 2;
226const CHANNEL_SIZE: i32 = 3;
227const CHANNEL_DRIFT_HEIGHT: i32 = 4;
228const CHANNEL_DRIFT_ANGLE: i32 = 5;
229
230/// Deterministic value in `[0, 1]` for one particle and channel.
231#[inline]
232fn particle_hash(index: u32, channel: i32, seed: u32) -> f32 {
233    hash3(index as i32, channel, 0, seed)
234}
235
236/// Fixed size of particle `index`, in world units.
237///
238/// The value lies between the two ends of
239/// [`AmbientParticlesConfig::size_range`], whatever their order. Negative and
240/// non-finite ends are treated as zero.
241///
242/// ```
243/// use voxel_framework::particles::{AmbientParticlesConfig, ambient_particle_size};
244///
245/// let config = AmbientParticlesConfig {
246///     size_range: (0.1, 0.2),
247///     ..Default::default()
248/// };
249/// let size = ambient_particle_size(7, &config);
250/// assert!((0.1..=0.2).contains(&size));
251/// ```
252pub fn ambient_particle_size(index: u32, config: &AmbientParticlesConfig) -> f32 {
253    let sanitize = |value: f32| {
254        if value.is_finite() {
255            value.max(0.0)
256        } else {
257            0.0
258        }
259    };
260    let a = sanitize(config.size_range.0);
261    let b = sanitize(config.size_range.1);
262    let (low, high) = (a.min(b), a.max(b));
263    low + (high - low) * particle_hash(index, CHANNEL_SIZE, config.seed)
264}
265
266/// Fixed unit direction along which particle `index` drifts.
267fn drift_direction(index: u32, seed: u32) -> Vec3 {
268    // Uniform on the sphere: uniform height, uniform angle around the axis.
269    let height = particle_hash(index, CHANNEL_DRIFT_HEIGHT, seed) * 2.0 - 1.0;
270    let angle = particle_hash(index, CHANNEL_DRIFT_ANGLE, seed) * std::f32::consts::TAU;
271    let ring = (1.0 - height * height).max(0.0).sqrt();
272    Vec3::new(ring * angle.cos(), height, ring * angle.sin())
273}
274
275/// Moves `value` by whole periods of `2 * radius` so that it lies within
276/// `radius` of `center`.
277///
278/// The result is `value` plus a whole number of periods, so it does not
279/// depend on `center` while the particle stays in the same copy of the field:
280/// a resting particle keeps exactly the same world coordinate as the viewer
281/// moves around it.
282#[inline]
283fn wrap_axis(value: f32, center: f32, radius: f32) -> f32 {
284    let period = 2.0 * radius;
285    value + ((center - value) / period).round() * period
286}
287
288/// Computes where particle `index` is drawn for a viewer position and time.
289///
290/// This is the whole spawn/advance/recycle rule of the ambient particle
291/// system, as a pure function: the same arguments always give the same
292/// result, on every platform, and no state is kept between calls.
293///
294/// - The particle's home is hashed from `index` and
295///   [`AmbientParticlesConfig::seed`], then moved along its drift direction by
296///   `drift_speed * elapsed_secs`.
297/// - The result is wrapped, per axis, to the copy nearest to `viewer`. This is
298///   the recycling step: a particle further than `volume_radius` along an
299///   axis reappears on the opposite side.
300/// - Particles outside the sphere of radius `volume_radius` are not visible,
301///   and the ones near its surface are scaled down by
302///   [`AmbientParticlesConfig::edge_fade`].
303///
304/// With `drift_speed == 0.0` a particle's world position does not change
305/// while it stays inside the volume, so it streams past a moving viewer.
306///
307/// A config with an unusable `volume_radius`, or a non-finite `viewer`, gives
308/// a hidden state.
309///
310/// ```
311/// use bevy::prelude::*;
312/// use voxel_framework::particles::{AmbientParticlesConfig, ambient_particle_state};
313///
314/// let config = AmbientParticlesConfig::default();
315/// let viewer = Vec3::new(100.0, 0.0, -40.0);
316/// let state = ambient_particle_state(3, viewer, 0.0, &config);
317///
318/// // Deterministic, and never further than the volume allows on any axis.
319/// assert_eq!(state, ambient_particle_state(3, viewer, 0.0, &config));
320/// let offset = (state.translation - viewer).abs();
321/// assert!(offset.max_element() <= config.volume_radius + 1e-3);
322/// ```
323pub fn ambient_particle_state(
324    index: u32,
325    viewer: Vec3,
326    elapsed_secs: f32,
327    config: &AmbientParticlesConfig,
328) -> AmbientParticleState {
329    let Some(radius) = config.radius() else {
330        return AmbientParticleState::HIDDEN;
331    };
332    if !viewer.is_finite() {
333        return AmbientParticleState::HIDDEN;
334    }
335
336    let seed = config.seed;
337    let period = 2.0 * radius;
338    // `Vec3::is_finite` above keeps the wrap below free of NaN.
339    let mut home = Vec3::new(
340        particle_hash(index, CHANNEL_HOME_X, seed),
341        particle_hash(index, CHANNEL_HOME_Y, seed),
342        particle_hash(index, CHANNEL_HOME_Z, seed),
343    ) * period;
344
345    let drift = config.drift_speed * elapsed_secs;
346    if drift.is_finite() && drift != 0.0 {
347        home += drift_direction(index, seed) * drift;
348    }
349
350    let translation = Vec3::new(
351        wrap_axis(home.x, viewer.x, radius),
352        wrap_axis(home.y, viewer.y, radius),
353        wrap_axis(home.z, viewer.z, radius),
354    );
355
356    let distance = translation.distance(viewer);
357    if !distance.is_finite() || distance >= radius {
358        return AmbientParticleState {
359            translation,
360            scale: 0.0,
361            visible: false,
362        };
363    }
364
365    let fade = if config.edge_fade.is_finite() {
366        config.edge_fade.clamp(0.0, 1.0)
367    } else {
368        0.0
369    };
370    let band = fade * radius;
371    let factor = if band > 0.0 {
372        ((radius - distance) / band).clamp(0.0, 1.0)
373    } else {
374        1.0
375    };
376    let scale = ambient_particle_size(index, config) * factor;
377
378    AmbientParticleState {
379        translation,
380        scale,
381        visible: scale > 0.0,
382    }
383}
384
385// ─── Components and resources ────────────────────────────────────────────────
386
387/// Marks an entity of the ambient particle pool.
388///
389/// The plugin owns these entities: it spawns them, rewrites their
390/// [`Transform`] and [`Visibility`] every frame, and despawns them when the
391/// pool shrinks. Query the component to count them or to add your own
392/// components (for example render layers).
393#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
394pub struct AmbientParticle {
395    /// Stable slot of the particle in the pool, in `0..count`. It is the
396    /// `index` passed to [`ambient_particle_state`].
397    pub index: u32,
398}
399
400/// Shared asset handles used by all ambient particle entities.
401///
402/// Inserted by [`AmbientParticlesPlugin`] the first time particles are
403/// active, and kept in sync with [`AmbientParticlesConfig::shape`] and
404/// [`AmbientParticlesConfig::color`].
405#[derive(Resource, Debug, Clone)]
406pub struct AmbientParticleAssets {
407    /// Handle to the shared unit-size mesh. For
408    /// [`AmbientParticleShape::Custom`] it is the game's own handle.
409    pub mesh: Handle<Mesh>,
410    /// Handle to the shared unlit material.
411    pub material: Handle<StandardMaterial>,
412    /// Shape the current `mesh` was built for.
413    shape: AmbientParticleShape,
414}
415
416/// System set of the ambient particle systems, in `PostUpdate`.
417///
418/// The systems run before transform and visibility propagation, so a
419/// [`ViewerPosition`] written in `Update` is used in the same frame. Order
420/// your own `PostUpdate` systems against this set when they write
421/// [`ViewerPosition`] or read particle transforms.
422#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
423pub struct AmbientParticleSystems;
424
425// ─── Systems ─────────────────────────────────────────────────────────────────
426
427/// Builds the shared mesh for a shape.
428fn shape_mesh(shape: &AmbientParticleShape, meshes: &mut Assets<Mesh>) -> Handle<Mesh> {
429    match shape {
430        AmbientParticleShape::Cube => meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
431        AmbientParticleShape::Sphere => meshes.add(Sphere::new(0.5)),
432        AmbientParticleShape::Custom(handle) => handle.clone(),
433    }
434}
435
436/// Builds the shared unlit material for a color.
437fn particle_material(color: Color) -> StandardMaterial {
438    StandardMaterial {
439        base_color: color,
440        unlit: true,
441        alpha_mode: if color.to_linear().alpha < 1.0 {
442            AlphaMode::Blend
443        } else {
444            AlphaMode::Opaque
445        },
446        ..default()
447    }
448}
449
450/// Allocates the shared assets on first use and keeps them in sync with the
451/// config afterwards.
452fn sync_ambient_particle_assets(
453    mut commands: Commands,
454    config: Res<AmbientParticlesConfig>,
455    assets: Option<ResMut<AmbientParticleAssets>>,
456    mut meshes: ResMut<Assets<Mesh>>,
457    mut materials: ResMut<Assets<StandardMaterial>>,
458    mut particles: Query<&mut Mesh3d, With<AmbientParticle>>,
459) {
460    let Some(mut assets) = assets else {
461        if config.active_count() == 0 {
462            return;
463        }
464        let mesh = shape_mesh(&config.shape, &mut meshes);
465        let material = materials.add(particle_material(config.color));
466        commands.insert_resource(AmbientParticleAssets {
467            mesh,
468            material,
469            shape: config.shape.clone(),
470        });
471        return;
472    };
473
474    if !config.is_changed() {
475        return;
476    }
477
478    if assets.shape != config.shape {
479        let mesh = shape_mesh(&config.shape, &mut meshes);
480        for mut particle_mesh in &mut particles {
481            particle_mesh.0 = mesh.clone();
482        }
483        assets.mesh = mesh;
484        assets.shape = config.shape.clone();
485    }
486
487    // Read first: `get_mut` marks the asset as modified even when nothing changes.
488    let color_changed = materials
489        .get(&assets.material)
490        .is_some_and(|material| material.base_color != config.color);
491    if color_changed && let Some(material) = materials.get_mut(&assets.material) {
492        *material = particle_material(config.color);
493    }
494}
495
496/// Grows or shrinks the pool to [`AmbientParticlesConfig::active_count`].
497fn sync_ambient_particle_pool(
498    mut commands: Commands,
499    config: Res<AmbientParticlesConfig>,
500    assets: Option<Res<AmbientParticleAssets>>,
501    particles: Query<(Entity, &AmbientParticle)>,
502) {
503    let target = config.active_count();
504
505    let mut kept = 0u32;
506    for (entity, particle) in &particles {
507        if particle.index < target {
508            kept += 1;
509        } else {
510            commands.entity(entity).despawn();
511        }
512    }
513    if kept == target {
514        return;
515    }
516    let Some(assets) = assets else {
517        return;
518    };
519
520    // Slots can be missing in any position (a game may despawn a particle),
521    // and a slot can be taken twice if a game spawns the marker itself.
522    let mut taken = vec![false; target as usize];
523    for (entity, particle) in &particles {
524        let Some(slot) = taken.get_mut(particle.index as usize) else {
525            continue;
526        };
527        if *slot {
528            commands.entity(entity).despawn();
529        } else {
530            *slot = true;
531        }
532    }
533
534    for (index, slot) in taken.iter().enumerate() {
535        if *slot {
536            continue;
537        }
538        // Spawned hidden; `update_ambient_particles` places it in this frame.
539        commands.spawn((
540            AmbientParticle {
541                index: index as u32,
542            },
543            Mesh3d(assets.mesh.clone()),
544            MeshMaterial3d(assets.material.clone()),
545            Transform::from_scale(Vec3::ZERO),
546            Visibility::Hidden,
547            NotShadowCaster,
548        ));
549    }
550}
551
552/// Places every pooled particle from [`ambient_particle_state`].
553fn update_ambient_particles(
554    viewer: Res<ViewerPosition>,
555    time: Res<Time>,
556    config: Res<AmbientParticlesConfig>,
557    mut particles: Query<(&AmbientParticle, &mut Transform, &mut Visibility)>,
558) {
559    let elapsed = time.elapsed_secs();
560
561    for (particle, mut transform, mut visibility) in &mut particles {
562        let state = ambient_particle_state(particle.index, viewer.position, elapsed, &config);
563
564        // Write only on change, so a resting field does not look changed
565        // every frame.
566        let scale = Vec3::splat(state.scale);
567        if transform.translation != state.translation || transform.scale != scale {
568            transform.translation = state.translation;
569            transform.scale = scale;
570        }
571        let wanted = if state.visible {
572            Visibility::Inherited
573        } else {
574            Visibility::Hidden
575        };
576        if *visibility != wanted {
577            *visibility = wanted;
578        }
579    }
580}
581
582// ─── Plugin ──────────────────────────────────────────────────────────────────
583
584/// Plugin that keeps sparse unlit particles in a volume around the viewer.
585///
586/// Category: Default Implementation. It is not included in `VoxelCorePlugin`
587/// or `VoxelPlugin`; add it explicitly.
588///
589/// # What it registers
590///
591/// * [`AmbientParticlesConfig`] — initialized with its default unless the
592///   game inserted one.
593/// * [`ViewerPosition`] — initialized if missing, so the plugin also works
594///   without the world plugins. The game still has to write it; the framework
595///   never discovers a camera or a player.
596/// * Three chained `PostUpdate` systems in [`AmbientParticleSystems`], before
597///   transform and visibility propagation: shared asset upkeep
598///   ([`AmbientParticleAssets`]), pool upkeep ([`AmbientParticle`] entities),
599///   and placement.
600///
601/// It requires `Assets<Mesh>`, `Assets<StandardMaterial>` and `Time`, which
602/// `DefaultPlugins` provide.
603///
604/// # Examples
605///
606/// ```no_run
607/// use bevy::prelude::*;
608/// use voxel_framework::prelude::*;
609///
610/// fn follow_camera(
611///     camera: Query<&GlobalTransform, With<Camera3d>>,
612///     mut viewer: ResMut<ViewerPosition>,
613/// ) {
614///     if let Ok(transform) = camera.single() {
615///         viewer.position = transform.translation();
616///     }
617/// }
618///
619/// fn main() {
620///     App::new()
621///         .add_plugins(DefaultPlugins)
622///         .add_plugins(AmbientParticlesPlugin)
623///         .add_systems(Update, follow_camera)
624///         .run();
625/// }
626/// ```
627pub struct AmbientParticlesPlugin;
628
629impl Plugin for AmbientParticlesPlugin {
630    fn build(&self, app: &mut App) {
631        app.init_resource::<AmbientParticlesConfig>()
632            .init_resource::<ViewerPosition>()
633            .add_systems(
634                PostUpdate,
635                (
636                    sync_ambient_particle_assets,
637                    sync_ambient_particle_pool,
638                    update_ambient_particles,
639                )
640                    .chain()
641                    .in_set(AmbientParticleSystems)
642                    .before(TransformSystems::Propagate)
643                    .before(VisibilitySystems::VisibilityPropagate)
644                    .before(VisibilitySystems::CalculateBounds),
645            );
646    }
647}
648
649// ─── Tests ───────────────────────────────────────────────────────────────────
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654
655    const EPS: f32 = 1e-3;
656
657    fn config() -> AmbientParticlesConfig {
658        AmbientParticlesConfig {
659            count: 200,
660            volume_radius: 10.0,
661            size_range: (0.1, 0.3),
662            ..default()
663        }
664    }
665
666    // ── Pure logic ───────────────────────────────────────────────────────────
667
668    #[test]
669    fn defaults_are_documented_values() {
670        let config = AmbientParticlesConfig::default();
671        assert!(config.enabled);
672        assert_eq!(config.count, 96);
673        assert_eq!(config.volume_radius, 24.0);
674        assert_eq!(config.size_range, (0.03, 0.08));
675        assert_eq!(config.color, Color::WHITE);
676        assert_eq!(config.shape, AmbientParticleShape::Cube);
677        assert_eq!(config.edge_fade, 0.25);
678        assert_eq!(config.drift_speed, 0.0);
679        assert_eq!(config.seed, 0);
680    }
681
682    #[test]
683    fn state_is_deterministic() {
684        let config = config();
685        let viewer = Vec3::new(3.5, -120.25, 77.0);
686        for index in 0..config.count {
687            assert_eq!(
688                ambient_particle_state(index, viewer, 1.5, &config),
689                ambient_particle_state(index, viewer, 1.5, &config)
690            );
691        }
692    }
693
694    #[test]
695    fn particles_stay_within_the_volume_on_every_axis() {
696        let config = config();
697        for viewer in [
698            Vec3::ZERO,
699            Vec3::new(1234.5, -987.25, 42.0),
700            Vec3::new(-5000.0, 5000.0, -0.5),
701        ] {
702            for index in 0..config.count {
703                let state = ambient_particle_state(index, viewer, 0.0, &config);
704                let offset = (state.translation - viewer).abs();
705                // Looser than EPS: f32 spacing is about 5e-4 at 5000 units.
706                assert!(
707                    offset.max_element() <= config.volume_radius + 1e-2,
708                    "particle {index} at {offset:?} from viewer {viewer:?}"
709                );
710            }
711        }
712    }
713
714    #[test]
715    fn visible_particles_are_inside_the_sphere() {
716        let config = config();
717        let viewer = Vec3::new(10.0, 20.0, 30.0);
718        let mut visible = 0;
719        for index in 0..config.count {
720            let state = ambient_particle_state(index, viewer, 0.0, &config);
721            let distance = state.translation.distance(viewer);
722            if state.visible {
723                visible += 1;
724                assert!(distance < config.volume_radius);
725                assert!(state.scale > 0.0);
726            } else {
727                assert_eq!(state.scale, 0.0);
728            }
729        }
730        // The sphere fills about 52% of its bounding cube.
731        assert!(
732            (60..=150).contains(&visible),
733            "{visible} of 200 particles visible"
734        );
735    }
736
737    #[test]
738    fn resting_particles_keep_their_world_position_until_recycled() {
739        let config = config();
740        let before = Vec3::ZERO;
741        let after = Vec3::new(1.0, 0.0, 0.0);
742        let mut unchanged = 0;
743        let mut recycled = 0;
744        for index in 0..config.count {
745            let a = ambient_particle_state(index, before, 0.0, &config).translation;
746            let b = ambient_particle_state(index, after, 5.0, &config).translation;
747            if a.distance(b) < EPS {
748                unchanged += 1;
749            } else {
750                recycled += 1;
751                // Recycled across the volume along the direction of travel.
752                assert!((b.x - a.x - 2.0 * config.volume_radius).abs() < EPS);
753                assert!((b.y - a.y).abs() < EPS);
754                assert!((b.z - a.z).abs() < EPS);
755            }
756        }
757        assert!(unchanged > recycled);
758        assert!(unchanged + recycled == config.count);
759    }
760
761    #[test]
762    fn moving_one_full_period_gives_the_same_relative_field() {
763        let config = config();
764        let shift = Vec3::new(2.0 * config.volume_radius, 0.0, 0.0);
765        for index in 0..config.count {
766            let a = ambient_particle_state(index, Vec3::ZERO, 0.0, &config);
767            let b = ambient_particle_state(index, shift, 0.0, &config);
768            assert!((b.translation - shift).distance(a.translation) < EPS);
769        }
770    }
771
772    #[test]
773    fn sizes_stay_in_range_whatever_the_order() {
774        let forward = config();
775        let reversed = AmbientParticlesConfig {
776            size_range: (0.3, 0.1),
777            ..config()
778        };
779        let mut smallest = f32::MAX;
780        let mut largest = f32::MIN;
781        for index in 0..forward.count {
782            let size = ambient_particle_size(index, &forward);
783            assert!((0.1..=0.3).contains(&size));
784            assert_eq!(size, ambient_particle_size(index, &reversed));
785            smallest = smallest.min(size);
786            largest = largest.max(size);
787        }
788        assert!(largest - smallest > 0.1, "sizes should vary");
789    }
790
791    #[test]
792    fn unusable_sizes_become_zero() {
793        let config = AmbientParticlesConfig {
794            size_range: (f32::NAN, -1.0),
795            ..config()
796        };
797        assert_eq!(ambient_particle_size(0, &config), 0.0);
798        assert!(!ambient_particle_state(0, Vec3::ZERO, 0.0, &config).visible);
799    }
800
801    #[test]
802    fn edge_fade_shrinks_particles_near_the_surface() {
803        let faded = AmbientParticlesConfig {
804            edge_fade: 0.5,
805            ..config()
806        };
807        let hard = AmbientParticlesConfig {
808            edge_fade: 0.0,
809            ..config()
810        };
811        let band_start = faded.volume_radius * 0.5;
812        let mut shrunk = 0;
813        for index in 0..faded.count {
814            let state = ambient_particle_state(index, Vec3::ZERO, 0.0, &faded);
815            let full = ambient_particle_size(index, &faded);
816            let distance = state.translation.length();
817            if !state.visible {
818                continue;
819            }
820            // Without a fade every visible particle has its full size.
821            let unfaded = ambient_particle_state(index, Vec3::ZERO, 0.0, &hard);
822            assert_eq!(unfaded.scale, full);
823            if distance <= band_start {
824                assert_eq!(state.scale, full);
825            } else {
826                assert!(state.scale <= full);
827                if state.scale < full {
828                    shrunk += 1;
829                }
830            }
831        }
832        assert!(shrunk > 0);
833    }
834
835    #[test]
836    fn drift_moves_particles_at_the_configured_speed() {
837        let config = AmbientParticlesConfig {
838            drift_speed: 0.5,
839            ..config()
840        };
841        let mut checked = 0;
842        for index in 0..config.count {
843            let a = ambient_particle_state(index, Vec3::ZERO, 0.0, &config).translation;
844            let b = ambient_particle_state(index, Vec3::ZERO, 1.0, &config).translation;
845            let moved = a.distance(b);
846            // Particles that crossed a face were recycled; skip those.
847            if moved < 1.0 {
848                assert!((moved - 0.5).abs() < EPS, "particle {index} moved {moved}");
849                checked += 1;
850            }
851        }
852        assert!(checked > config.count / 2);
853    }
854
855    #[test]
856    fn drift_directions_are_unit_length_and_varied() {
857        let first = drift_direction(0, 0);
858        let mut varied = false;
859        for index in 0..64 {
860            let direction = drift_direction(index, 0);
861            assert!((direction.length() - 1.0).abs() < EPS);
862            varied |= direction.distance(first) > 0.5;
863        }
864        assert!(varied);
865    }
866
867    #[test]
868    fn seed_changes_the_field() {
869        let a = config();
870        let b = AmbientParticlesConfig {
871            seed: 1,
872            ..config()
873        };
874        let differing = (0..a.count)
875            .filter(|&index| {
876                ambient_particle_state(index, Vec3::ZERO, 0.0, &a).translation
877                    != ambient_particle_state(index, Vec3::ZERO, 0.0, &b).translation
878            })
879            .count();
880        assert!(differing > 190);
881    }
882
883    #[test]
884    fn unusable_configs_and_viewers_hide_everything() {
885        for volume_radius in [0.0, -4.0, f32::NAN, f32::INFINITY] {
886            let config = AmbientParticlesConfig {
887                volume_radius,
888                ..config()
889            };
890            assert_eq!(config.active_count(), 0);
891            let state = ambient_particle_state(0, Vec3::ZERO, 0.0, &config);
892            assert_eq!(state, AmbientParticleState::HIDDEN);
893        }
894        let disabled = AmbientParticlesConfig {
895            enabled: false,
896            ..config()
897        };
898        assert_eq!(disabled.active_count(), 0);
899
900        let state = ambient_particle_state(0, Vec3::splat(f32::NAN), 0.0, &config());
901        assert_eq!(state, AmbientParticleState::HIDDEN);
902    }
903
904    // ── Plugin ───────────────────────────────────────────────────────────────
905
906    fn app(config: AmbientParticlesConfig) -> App {
907        let mut app = App::new();
908        app.init_resource::<Time>()
909            .init_resource::<Assets<Mesh>>()
910            .init_resource::<Assets<StandardMaterial>>()
911            .insert_resource(config)
912            .add_plugins(AmbientParticlesPlugin);
913        app
914    }
915
916    fn particles(app: &mut App) -> Vec<(u32, Transform, Visibility)> {
917        let world = app.world_mut();
918        let mut query = world.query::<(&AmbientParticle, &Transform, &Visibility)>();
919        let mut found: Vec<_> = query
920            .iter(world)
921            .map(|(particle, transform, visibility)| (particle.index, *transform, *visibility))
922            .collect();
923        found.sort_by_key(|(index, _, _)| *index);
924        found
925    }
926
927    #[test]
928    fn plugin_keeps_an_inserted_config_and_initializes_the_viewer() {
929        let mut app = app(config());
930        app.update();
931        assert_eq!(app.world().resource::<AmbientParticlesConfig>().count, 200);
932        assert!(app.world().get_resource::<ViewerPosition>().is_some());
933    }
934
935    #[test]
936    fn pool_matches_count_and_follows_the_pure_placement() {
937        let mut app = app(config());
938        app.world_mut().resource_mut::<ViewerPosition>().position = Vec3::new(50.0, 0.0, 0.0);
939        app.update();
940        app.update();
941
942        let config = config();
943        let found = particles(&mut app);
944        assert_eq!(found.len(), 200);
945        for (slot, (index, transform, visibility)) in found.iter().enumerate() {
946            assert_eq!(*index, slot as u32);
947            let state = ambient_particle_state(*index, Vec3::new(50.0, 0.0, 0.0), 0.0, &config);
948            assert_eq!(transform.translation, state.translation);
949            assert_eq!(transform.scale, Vec3::splat(state.scale));
950            assert_eq!(*visibility == Visibility::Inherited, state.visible);
951        }
952    }
953
954    #[test]
955    fn particles_share_one_mesh_and_one_material() {
956        let mut app = app(config());
957        app.update();
958        app.update();
959
960        let assets = app.world().resource::<AmbientParticleAssets>().clone();
961        let world = app.world_mut();
962        let mut query = world
963            .query_filtered::<(&Mesh3d, &MeshMaterial3d<StandardMaterial>), With<AmbientParticle>>(
964            );
965        let mut seen = 0;
966        for (mesh, material) in query.iter(world) {
967            assert_eq!(mesh.0, assets.mesh);
968            assert_eq!(material.0, assets.material);
969            seen += 1;
970        }
971        assert_eq!(seen, 200);
972        assert_eq!(world.resource::<Assets<Mesh>>().len(), 1);
973        assert_eq!(world.resource::<Assets<StandardMaterial>>().len(), 1);
974
975        let material = world
976            .resource::<Assets<StandardMaterial>>()
977            .get(&assets.material)
978            .expect("shared material exists");
979        assert!(material.unlit);
980        assert_eq!(material.base_color, Color::WHITE);
981    }
982
983    #[test]
984    fn pool_follows_count_and_enabled_changes() {
985        let mut app = app(config());
986        app.update();
987        app.update();
988        assert_eq!(particles(&mut app).len(), 200);
989
990        app.world_mut()
991            .resource_mut::<AmbientParticlesConfig>()
992            .count = 50;
993        app.update();
994        app.update();
995        let found = particles(&mut app);
996        assert_eq!(found.len(), 50);
997        assert!(found.iter().all(|(index, _, _)| *index < 50));
998
999        app.world_mut()
1000            .resource_mut::<AmbientParticlesConfig>()
1001            .count = 80;
1002        app.update();
1003        app.update();
1004        let found = particles(&mut app);
1005        assert_eq!(found.len(), 80);
1006        assert!(
1007            found
1008                .iter()
1009                .enumerate()
1010                .all(|(slot, (index, _, _))| *index == slot as u32)
1011        );
1012
1013        app.world_mut()
1014            .resource_mut::<AmbientParticlesConfig>()
1015            .enabled = false;
1016        app.update();
1017        app.update();
1018        assert!(particles(&mut app).is_empty());
1019    }
1020
1021    #[test]
1022    fn disabled_plugin_allocates_nothing() {
1023        let mut app = app(AmbientParticlesConfig {
1024            enabled: false,
1025            ..config()
1026        });
1027        app.update();
1028        app.update();
1029        assert!(particles(&mut app).is_empty());
1030        assert!(
1031            app.world()
1032                .get_resource::<AmbientParticleAssets>()
1033                .is_none()
1034        );
1035        assert_eq!(app.world().resource::<Assets<Mesh>>().len(), 0);
1036    }
1037
1038    #[test]
1039    fn a_missing_slot_is_refilled() {
1040        let mut app = app(config());
1041        app.update();
1042        app.update();
1043
1044        let world = app.world_mut();
1045        let mut query = world.query::<(Entity, &AmbientParticle)>();
1046        let victim = query
1047            .iter(world)
1048            .find(|(_, particle)| particle.index == 7)
1049            .map(|(entity, _)| entity)
1050            .expect("slot 7 exists");
1051        world.despawn(victim);
1052
1053        app.update();
1054        app.update();
1055        let found = particles(&mut app);
1056        assert_eq!(found.len(), 200);
1057        assert_eq!(found[7].0, 7);
1058    }
1059
1060    #[test]
1061    fn color_and_shape_changes_update_the_shared_assets() {
1062        let mut app = app(config());
1063        app.update();
1064        app.update();
1065        let before = app.world().resource::<AmbientParticleAssets>().clone();
1066
1067        let translucent = Color::srgba(1.0, 0.5, 0.25, 0.5);
1068        {
1069            let mut config = app.world_mut().resource_mut::<AmbientParticlesConfig>();
1070            config.color = translucent;
1071            config.shape = AmbientParticleShape::Sphere;
1072        }
1073        app.update();
1074        app.update();
1075
1076        let after = app.world().resource::<AmbientParticleAssets>().clone();
1077        assert_eq!(
1078            after.material, before.material,
1079            "material is edited in place"
1080        );
1081        assert_ne!(after.mesh, before.mesh, "a new shape needs a new mesh");
1082
1083        let world = app.world_mut();
1084        let material = world
1085            .resource::<Assets<StandardMaterial>>()
1086            .get(&after.material)
1087            .expect("shared material exists");
1088        assert_eq!(material.base_color, translucent);
1089        assert_eq!(material.alpha_mode, AlphaMode::Blend);
1090
1091        let mut query = world.query_filtered::<&Mesh3d, With<AmbientParticle>>();
1092        assert!(query.iter(world).all(|mesh| mesh.0 == after.mesh));
1093    }
1094
1095    #[test]
1096    fn particles_stream_past_a_moving_viewer() {
1097        let mut app = app(config());
1098        app.update();
1099        app.update();
1100        let before = particles(&mut app);
1101
1102        app.world_mut().resource_mut::<ViewerPosition>().position = Vec3::new(0.5, 0.0, 0.0);
1103        app.update();
1104        let after = particles(&mut app);
1105
1106        // Most particles did not move in the world, so relative to the viewer
1107        // they moved backwards.
1108        let still = before
1109            .iter()
1110            .zip(&after)
1111            .filter(|(a, b)| a.1.translation == b.1.translation)
1112            .count();
1113        assert!(still > 180, "{still} of 200 particles kept their position");
1114    }
1115}