use bevy::camera::visibility::VisibilitySystems;
use bevy::light::NotShadowCaster;
use bevy::prelude::*;
use bevy::transform::TransformSystems;
use crate::noise::hash3;
use crate::world::ViewerPosition;
#[derive(Debug, Clone, PartialEq, Default)]
pub enum AmbientParticleShape {
#[default]
Cube,
Sphere,
Custom(Handle<Mesh>),
}
#[derive(Resource, Debug, Clone, PartialEq)]
pub struct AmbientParticlesConfig {
pub enabled: bool,
pub count: u32,
pub volume_radius: f32,
pub size_range: (f32, f32),
pub color: Color,
pub shape: AmbientParticleShape,
pub edge_fade: f32,
pub drift_speed: f32,
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 {
pub fn active_count(&self) -> u32 {
if self.enabled && self.radius().is_some() {
self.count
} else {
0
}
}
fn radius(&self) -> Option<f32> {
(self.volume_radius.is_finite() && self.volume_radius > 0.0).then_some(self.volume_radius)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AmbientParticleState {
pub translation: Vec3,
pub scale: f32,
pub visible: bool,
}
impl AmbientParticleState {
const HIDDEN: Self = Self {
translation: Vec3::ZERO,
scale: 0.0,
visible: false,
};
}
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;
#[inline]
fn particle_hash(index: u32, channel: i32, seed: u32) -> f32 {
hash3(index as i32, channel, 0, seed)
}
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)
}
fn drift_direction(index: u32, seed: u32) -> Vec3 {
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())
}
#[inline]
fn wrap_axis(value: f32, center: f32, radius: f32) -> f32 {
let period = 2.0 * radius;
value + ((center - value) / period).round() * period
}
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;
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,
}
}
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
pub struct AmbientParticle {
pub index: u32,
}
#[derive(Resource, Debug, Clone)]
pub struct AmbientParticleAssets {
pub mesh: Handle<Mesh>,
pub material: Handle<StandardMaterial>,
shape: AmbientParticleShape,
}
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AmbientParticleSystems;
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(),
}
}
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()
}
}
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();
}
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);
}
}
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;
};
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;
}
commands.spawn((
AmbientParticle {
index: index as u32,
},
Mesh3d(assets.mesh.clone()),
MeshMaterial3d(assets.material.clone()),
Transform::from_scale(Vec3::ZERO),
Visibility::Hidden,
NotShadowCaster,
));
}
}
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);
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;
}
}
}
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),
);
}
}
#[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()
}
}
#[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();
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);
}
}
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;
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;
}
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);
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);
}
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);
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");
}
}