Skip to main content

Crate bevy_falling_sand

Crate bevy_falling_sand 

Source
Expand description

§Overview

Bevy Falling Sand (bfs) provides a Falling Sand engine for Bevy apps.

bevy_falling_sandbevy
0.7.x0.18.x

§Feature Flags

This crate aims to modularized. Opt out of any simulation features you don’t want/like in favor of your own implementations.

All features are enabled by default.

FeatureDescriptionImplies
renderParticle color profiles and chunk-based rendering
movementParticle movement systems
reactionsInter-particle reactionsrender, movement
physicsavian2d integration. Adds the avian plugin.
debugDebug resources
persistenceSave/load chunks, particle types, and scenes to diskbfs, bfc
bfsEnables persistence::bfs — compact particle scene format
bfcEnables persistence::bfc — scene format with per-particle colorrender

§Quick start

Add the FallingSandPlugin plugin, overriding defaults as desired (see also FallingSandMinimalPlugin). Common overrides:

  • with_chunk_size: side length of a chunk in particles. Must be a power of 2.
  • with_map_size: side length of the loaded region in chunks. Must be a power of 2.
use bevy::prelude::*;
use bevy_falling_sand::prelude::*;

fn main() {
    App::new()
        .add_plugins((
            DefaultPlugins,
            FallingSandPlugin::default()
                // Create a map with 64x64 chunks, each of which can hold 64x64 particles
                .with_chunk_size(64)
                .with_map_size(64),
        ))
        .add_systems(Startup, setup)
        .add_systems(Update, sand_emitter)
        .run();
}

// Spawn a simple particle type with colors and movement behavior resembling sand.
fn setup(mut commands: Commands) {
    commands.spawn((
        ParticleType::new("Sand"),
        ColorProfile::palette(vec![
            Color::Srgba(Srgba::hex("#FFEB8A").unwrap()),
            Color::Srgba(Srgba::hex("#F2E06B").unwrap()),
        ]),
        // First tier: look directly below. Second tier: look diagonally down.
        Movement::from(vec![
            vec![IVec2::NEG_Y],
            vec![IVec2::NEG_ONE, IVec2::new(1, -1)],
        ]),
        Density(1250),
        Speed::new(5, 10),
    ));
}

// Continuously emit sand between (0, 0) and (10, 10)
fn sand_emitter(mut writer: MessageWriter<SpawnParticleSignal>) {
    for x in 0..10 {
        for y in 0..10 {
            writer.write(SpawnParticleSignal::new(
                Particle::new("Sand"),
                IVec2::new(x, y),
            ));
        }
    }
}

§Particle types

The ParticleType component acts as an interface for creating new particles. When ParticleType is inserted on an entity, it becomes a point of synchronization for all Particle entities of the same identifier.

The ParticleType::name and Particle::name fields are used to associate particles with their parents.

bfs provides several components that add behaviors particle types. Inserting any of the components from the table below on a ParticleType entity will influence its child Particle entity’s behavior.

Particle Behavior ComponentDescriptionFeature
ColorProfileColor profile for particles from a predefined palette or gradientrender
ForceColorOverrides ColorProfile assignemnts with another color.render
MovementMovement rulesets for a particlemovement
DensityDensity of a particle, used for displacement comparisonsmovement
SpeedControls how many positions a particle can move per framemovement
AirResistanceChance that a particle will skip movement to a vacant locationmovement
ParticleResistorHow much a particle resists being displaced by other particlesmovement
MomentumDirectional hint that biases movement toward the last directionmovement
ContactReactionDefines reaction rulesets for a particle typereactions
FireMakes a particle spread firereactions
FlammableFlammability properties for particlesreactions
StaticRigidBodyParticleMark particles for inclusion in rigid body mesh generationphysics
TimedLifetimeDespawns a particle after a specified duration
ChanceLifetimeChance to despawn an entity on a per-tick basis

§Table of Contents

§Particle lifecycles

§Rendering

§Movement

§Reactions

§Avian2d integration

§World persistence

§Scenes

§Map origin shifts and dynamic chunk loading

§Particle synchronization

§Registering custom particle components

§Spatial queries and raycasting

ParticleMap convenience methods that accept a Bevy Query filter to define what counts as a “hit” or “blocker”:

§Debug stats and visuals

Re-exports§

pub use core::*;

Modules§

core
Provides all of the core constructs required for the falling sand simulation.
debugdebug
Provides debug and statistics constructs
movementmovement
Provides movement components, systems, and resources for simulating particle movement
persistencepersistence
Save and load particles and particle type definitions to disk.
physicsphysics
Integrates avian2d physics with the falling sand simulation
prelude
Re-exports commonly used items for convenient importing.
reactionsreactions
Provides reaction functionality for particles
renderrender
Particle color assignment and rendering pipeline
scenesscenes
Scene loading and spawning

Macros§

impl_particle_rng
Convenience macro for implementing ParticleRng on a component.

Structs§

FallingSandMinimalPlugin
A minimal plugin for Bevy Falling Sand, which only adds the crate’s core features.
FallingSandPlugin
Plugin that registers all feature-gated Bevy Falling Sand sub-plugins enabled at compile time.