Skip to main content

voxel_framework/fragments/
mod.rs

1//! Voxel break-apart fragment effect.
2//!
3//! When a voxel is destroyed, this module spawns a small burst of cube-shaped
4//! debris particles that fly outward, arc downward under simulated gravity,
5//! and automatically despawn after a configurable lifetime.
6//!
7//! # Lifecycle
8//!
9//! 1. **Spawn** — each `VoxelBroken` message
10//!    triggers the spawning of [`FragmentConfig::count`] fragment entities
11//!    centered at the broken voxel's world position.  Initial velocities are
12//!    distributed using a golden-angle spiral with pseudo-random jitter so
13//!    fragments fan out naturally rather than clustering.
14//! 2. **Physics update** — every `Update` tick, each fragment's velocity is
15//!    updated with a downward gravity acceleration
16//!    ([`FragmentConfig::gravity`]), its position is integrated, and its
17//!    remaining lifetime is decremented.
18//! 3. **Despawn** — once `lifetime_remaining` reaches zero the entity is
19//!    despawned immediately.
20//!
21//! # Pooled mesh assets
22//!
23//! All fragments share a single [`Mesh`] handle and a single
24//! [`StandardMaterial`] handle, both pre-allocated during `Startup` and stored
25//! in the [`FragmentAssets`] resource.  This avoids re-allocating GPU resources
26//! for every voxel break event.
27//!
28//! # Integration
29//!
30//! ```no_run
31//! use bevy::prelude::*;
32//! use voxel_framework::fragments::{FragmentConfig, FragmentPlugin};
33//!
34//! fn main() {
35//!     App::new()
36//!         .insert_resource(FragmentConfig {
37//!             count: 10,
38//!             initial_speed: 5.0,
39//!             gravity: 12.0,
40//!             lifetime: 1.2,
41//!             size: 0.15,
42//!         })
43//!         .add_plugins(FragmentPlugin)
44//!         .run();
45//! }
46//! ```
47
48use bevy::prelude::*;
49
50use crate::generator::GeneratorSystems;
51use crate::world::VoxelBroken;
52
53// ─── Resources ───────────────────────────────────────────────────────────────
54
55/// Controls the appearance and physics behavior of voxel break fragments.
56///
57/// Insert a customized instance before adding [`FragmentPlugin`] to override
58/// the defaults, or rely on [`Default`] for sensible Minecraft-like values.
59#[derive(Resource, Debug, Clone)]
60pub struct FragmentConfig {
61    /// Number of fragment entities spawned per broken voxel.
62    ///
63    /// Higher values produce a denser, more dramatic effect at the cost of
64    /// additional entity overhead per break event.  Default: `6`.
65    pub count: u32,
66    /// Magnitude of the initial outward velocity applied to each fragment,
67    /// in world units per second.
68    ///
69    /// The actual per-fragment speed is jittered in the range
70    /// `[0.7 × initial_speed, 1.3 × initial_speed]`.  Default: `4.0`.
71    pub initial_speed: f32,
72    /// Downward acceleration applied every tick, in world units per second².
73    ///
74    /// Analogous to gravitational acceleration.  Higher values make fragments
75    /// fall faster and arc more sharply.  Default: `9.8`.
76    pub gravity: f32,
77    /// Duration in seconds before a fragment entity is automatically despawned.
78    ///
79    /// Default: `1.5`.
80    pub lifetime: f32,
81    /// Side length of each fragment cube, in world units.
82    ///
83    /// Also controls the random spawn offset: fragments are displaced by up to
84    /// `±size` from the voxel center at spawn time.  Default: `0.2`.
85    pub size: f32,
86}
87
88impl Default for FragmentConfig {
89    fn default() -> Self {
90        Self {
91            count: 6,
92            initial_speed: 4.0,
93            gravity: 9.8,
94            lifetime: 1.5,
95            size: 0.2,
96        }
97    }
98}
99
100/// Shared GPU asset handles used by all fragment entities.
101///
102/// All fragments in a scene share a single [`Mesh`] (a cube of side length
103/// [`FragmentConfig::size`]) and a single warm-grey unlit [`StandardMaterial`].
104/// Sharing these handles avoids creating a new GPU resource per broken voxel.
105///
106/// This resource is inserted automatically at `Startup` by the setup system
107/// registered in [`FragmentPlugin`].  It is available for queries from any
108/// subsequent system that needs to inspect or override the shared assets.
109#[derive(Resource)]
110pub struct FragmentAssets {
111    /// Handle to the shared cuboid mesh used by every fragment entity.
112    pub mesh: Handle<Mesh>,
113    /// Handle to the shared unlit material used by every fragment entity.
114    ///
115    /// The base color is a warm grey (`srgb(0.55, 0.50, 0.47)`) with
116    /// `unlit: true` so fragments remain visible regardless of scene lighting.
117    pub material: Handle<StandardMaterial>,
118}
119
120// ─── Components ──────────────────────────────────────────────────────────────
121
122/// Per-entity state component attached to each fragment particle.
123///
124/// The update system reads and writes both fields every tick.  Entities whose
125/// `lifetime_remaining` reaches zero or below are despawned immediately.
126#[derive(Component)]
127pub struct Fragment {
128    /// Current velocity of the fragment in world space, in units per second.
129    ///
130    /// Set at spawn time from [`FragmentConfig::initial_speed`] and the
131    /// outward direction computed by the golden-angle spiral.  Decremented
132    /// along the Y axis each frame by gravity
133    /// ([`FragmentConfig::gravity`] × delta time).
134    pub velocity: Vec3,
135    /// Seconds remaining before this fragment entity is despawned.
136    ///
137    /// Initialized to [`FragmentConfig::lifetime`] at spawn.  Decremented by
138    /// `Time::delta_secs()` each `Update` tick.
139    pub lifetime_remaining: f32,
140}
141
142// ─── Helpers ─────────────────────────────────────────────────────────────────
143
144/// Cheap deterministic pseudo-random float in [0, 1) derived from a seed.
145///
146/// Uses a xorshift32-style mix so there is no `rand` dependency.
147#[inline]
148fn pseudo_rand(mut seed: u32) -> f32 {
149    seed ^= seed << 13;
150    seed ^= seed >> 17;
151    seed ^= seed << 5;
152    // Map to [0, 1)
153    (seed as f32) / (u32::MAX as f32)
154}
155
156/// Compute a seed from a world position and fragment index.
157#[inline]
158fn position_seed(world_pos: Vec3, index: u32) -> u32 {
159    let ix = (world_pos.x * 1000.0) as i32 as u32;
160    let iy = (world_pos.y * 1000.0) as i32 as u32;
161    let iz = (world_pos.z * 1000.0) as i32 as u32;
162    let h = ix.wrapping_mul(2654435761)
163        ^ iy.wrapping_mul(2246822519)
164        ^ iz.wrapping_mul(3266489917)
165        ^ index.wrapping_mul(1013904223);
166    // One extra mix pass to reduce correlation between adjacent indices.
167    h ^ (h >> 16)
168}
169
170/// Compute an outward direction for fragment `index` using a golden-angle
171/// spiral spread around +Y, with pseudo-random jitter.
172fn fragment_direction(world_pos: Vec3, index: u32, count: u32) -> Vec3 {
173    // Golden angle in radians ≈ 2.399963…
174    const GOLDEN_ANGLE: f32 = 2.399_963;
175
176    let seed_a = position_seed(world_pos, index * 3);
177    let seed_b = position_seed(world_pos, index * 3 + 1);
178    let seed_c = position_seed(world_pos, index * 3 + 2);
179
180    // Elevation: spread fragments in a hemisphere mostly upward / outward.
181    let t = if count > 1 {
182        index as f32 / (count - 1) as f32
183    } else {
184        0.5
185    };
186    // Elevation angle in [10°, 80°] degrees from horizontal
187    let elevation = std::f32::consts::FRAC_PI_8
188        + t * (std::f32::consts::FRAC_PI_2 - std::f32::consts::FRAC_PI_4);
189
190    // Azimuth: golden angle spiral + small random jitter
191    let azimuth = index as f32 * GOLDEN_ANGLE + pseudo_rand(seed_a) * 0.3;
192
193    // Small random jitter on elevation
194    let elevation_jitter = (pseudo_rand(seed_b) - 0.5) * 0.4;
195    let final_elevation = (elevation + elevation_jitter).clamp(0.05, std::f32::consts::FRAC_PI_2);
196
197    // Speed scale jitter in [0.7, 1.3]
198    let _speed_jitter = 0.7 + pseudo_rand(seed_c) * 0.6;
199
200    let (sin_el, cos_el) = final_elevation.sin_cos();
201    let (sin_az, cos_az) = azimuth.sin_cos();
202
203    Vec3::new(cos_el * cos_az, sin_el, cos_el * sin_az).normalize()
204}
205
206// ─── Systems ─────────────────────────────────────────────────────────────────
207
208/// Startup system — allocates the shared mesh and material handles and inserts
209/// them as a [`FragmentAssets`] resource.
210fn setup_fragment_assets(
211    mut commands: Commands,
212    mut meshes: ResMut<Assets<Mesh>>,
213    mut materials: ResMut<Assets<StandardMaterial>>,
214    config: Res<FragmentConfig>,
215) {
216    let mesh = meshes.add(Cuboid::new(config.size, config.size, config.size));
217
218    // Warm grey, unlit so it does not depend on the scene's light setup.
219    let material = materials.add(StandardMaterial {
220        base_color: Color::srgb(0.55, 0.50, 0.47),
221        unlit: true,
222        ..default()
223    });
224
225    commands.insert_resource(FragmentAssets { mesh, material });
226}
227
228/// Listens for [`VoxelBroken`] messages and spawns debris fragments at the
229/// broken voxel's world position.
230fn spawn_fragments_system(
231    mut commands: Commands,
232    mut reader: MessageReader<VoxelBroken>,
233    config: Res<FragmentConfig>,
234    assets: Res<FragmentAssets>,
235) {
236    for event in reader.read() {
237        let origin = event.world_pos;
238
239        for i in 0..config.count {
240            let dir = fragment_direction(origin, i, config.count);
241
242            // Speed jitter: [0.7, 1.3] × initial_speed
243            let seed = position_seed(origin, i * 3 + 2);
244            let speed_scale = 0.7 + pseudo_rand(seed) * 0.6;
245            let velocity = dir * config.initial_speed * speed_scale;
246
247            // Small random offset so fragments don't all start at the exact center.
248            let offset_seed_x = position_seed(origin, i * 7);
249            let offset_seed_y = position_seed(origin, i * 7 + 1);
250            let offset_seed_z = position_seed(origin, i * 7 + 2);
251            let offset = Vec3::new(
252                (pseudo_rand(offset_seed_x) - 0.5) * config.size * 2.0,
253                (pseudo_rand(offset_seed_y) - 0.5) * config.size * 2.0,
254                (pseudo_rand(offset_seed_z) - 0.5) * config.size * 2.0,
255            );
256
257            commands.spawn((
258                Mesh3d(assets.mesh.clone()),
259                MeshMaterial3d(assets.material.clone()),
260                Transform::from_translation(origin + offset),
261                Fragment {
262                    velocity,
263                    lifetime_remaining: config.lifetime,
264                },
265            ));
266        }
267    }
268}
269
270/// Advances all fragment positions and despawns any whose lifetime has expired.
271fn update_fragments_system(
272    mut commands: Commands,
273    time: Res<Time>,
274    mut query: Query<(Entity, &mut Transform, &mut Fragment)>,
275    config: Res<FragmentConfig>,
276) {
277    let delta = time.delta_secs();
278
279    for (entity, mut transform, mut fragment) in &mut query {
280        // Apply gravity.
281        fragment.velocity.y -= config.gravity * delta;
282        // Integrate position.
283        transform.translation += fragment.velocity * delta;
284        // Tick lifetime.
285        fragment.lifetime_remaining -= delta;
286
287        if fragment.lifetime_remaining <= 0.0 {
288            commands.entity(entity).despawn();
289        }
290    }
291}
292
293// ─── Plugin ───────────────────────────────────────────────────────────────────
294
295/// Plugin that enables the voxel break-apart fragment effect.
296///
297/// # What it registers
298///
299/// * [`FragmentConfig`] — initialized as a default resource.  Insert a
300///   pre-populated instance before adding this plugin to override the defaults.
301/// * A `Startup` system that allocates the shared mesh and material and inserts
302///   them as [`FragmentAssets`].
303/// * A `Update` system that listens for `VoxelBroken` messages and spawns
304///   fragment entities; ordered after `GeneratorSystems` to ensure world state
305///   is settled first.
306/// * A `Update` system that advances fragment physics and despawns expired
307///   entities.
308///
309/// # Examples
310///
311/// ```no_run
312/// use bevy::prelude::*;
313/// use voxel_framework::fragments::{FragmentConfig, FragmentPlugin};
314///
315/// fn main() {
316///     App::new()
317///         .insert_resource(FragmentConfig {
318///             count: 8,
319///             ..Default::default()
320///         })
321///         .add_plugins(FragmentPlugin)
322///         .run();
323/// }
324/// ```
325pub struct FragmentPlugin;
326
327impl Plugin for FragmentPlugin {
328    fn build(&self, app: &mut App) {
329        app.init_resource::<FragmentConfig>();
330        app.add_systems(Startup, setup_fragment_assets);
331        app.add_systems(Update, spawn_fragments_system.after(GeneratorSystems));
332        app.add_systems(Update, update_fragments_system);
333    }
334}
335
336// ─── Tests ────────────────────────────────────────────────────────────────────
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    #[test]
343    fn test_fragment_config_defaults() {
344        let config = FragmentConfig::default();
345        assert_eq!(config.count, 6);
346        assert!((config.initial_speed - 4.0).abs() < f32::EPSILON);
347        assert!((config.gravity - 9.8).abs() < f32::EPSILON);
348        assert!((config.lifetime - 1.5).abs() < f32::EPSILON);
349        assert!((config.size - 0.2).abs() < f32::EPSILON);
350    }
351
352    #[test]
353    fn test_fragment_despawns_after_lifetime() {
354        let config = FragmentConfig::default();
355
356        // Simulate a fragment ticking down its lifetime manually.
357        let mut lifetime_remaining = config.lifetime;
358        let velocity = Vec3::new(1.0, 2.0, 0.5);
359        let gravity = config.gravity;
360
361        let mut translation = Vec3::ZERO;
362        let mut vel = velocity;
363
364        let delta = 0.1_f32;
365        let mut despawned = false;
366
367        for _ in 0..100 {
368            vel.y -= gravity * delta;
369            translation += vel * delta;
370            lifetime_remaining -= delta;
371
372            if lifetime_remaining <= 0.0 {
373                despawned = true;
374                break;
375            }
376        }
377
378        assert!(despawned, "fragment should despawn when lifetime expires");
379        assert!(lifetime_remaining <= 0.0, "lifetime must reach zero");
380        // Position should have moved from origin due to initial velocity + gravity.
381        assert!(
382            translation.length() > 0.0,
383            "fragment should have moved before despawning"
384        );
385    }
386}