Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Added
- Added `RotateOverTimeModifier`

### Changed

- Batch same-effect instances. This greatly improves performance when using many instances
Expand Down
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ wgpu = { version = "29.0.3", default-features = false, features = [
"fragile-send-sync-non-atomic-wasm",
] }
naga = { version = "29.0.3", features = ["wgsl-in"] }
naga_oil = { version = "0.22", default-features = false, features = ["test_shader"] }
naga_oil = { version = "0.22", default-features = false, features = [
"test_shader",
] }

# getrandom requires both 'wasm_js' as a feature AND as a RUSTFLAGS to work on wasm
[target.'cfg(target_arch = "wasm32")'.dependencies]
Expand Down Expand Up @@ -165,6 +167,9 @@ name = "puffs"
[[example]]
name = "lightning"

[[example]]
name = "rotate_over_time"

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general please avoid adding examples unless there's a non-obvious new feature or there's really no other example this could fit in. The reason is that the maintenance cost of examples is quite high; not only are examples used as behavior benchmark to validate behavior for all major changes (need to run them all one by one for visual check), they also require extra work in wasm (add new webpage, extra compile time, etc.). Ideally all of that should be automated or covered by unit/feature tests, but until then it's quite the burden. Thanks!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which example would it be ok to include this modifier then? if any?


[[test]]
name = "empty_effect"
path = "gpu_tests/empty_effect.rs"
Expand Down
103 changes: 103 additions & 0 deletions examples/rotate_over_time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//! An example using the [`RotateOverTimeModifier`].

use std::f32::consts::FRAC_PI_2;

use bevy::{core_pipeline::tonemapping::Tonemapping, prelude::*};
use bevy_hanabi::prelude::*;

mod utils;
use utils::*;

const DEMO_DESC: &str = include_str!("rotate_over_time.txt");
const COLOR: Vec4 = Vec4::new(0.7, 0.7, 1.0, 1.0);
const SIZE: Vec3 = Vec3::splat(0.1);

fn main() -> Result<(), Box<dyn std::error::Error>> {
let app_exit = utils::DemoApp::new("box")
.with_desc(DEMO_DESC)
.build()
.add_systems(Startup, setup)
.add_systems(Update, rotate_camera)
.run();
app_exit.into_result()
}

fn setup(
mut commands: Commands,
mut effects: ResMut<Assets<EffectAsset>>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn((
Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
Camera3d::default(),
Projection::Perspective(PerspectiveProjection {
fov: 120.0,
..default()
}),
Tonemapping::None,
));

// The ground
commands.spawn((
Transform::from_xyz(0.0, -0.5, 0.0)
* Transform::from_rotation(Quat::from_rotation_x(-FRAC_PI_2)),
Mesh3d(meshes.add(Rectangle {
half_size: Vec2::splat(2.0),
})),
MeshMaterial3d(materials.add(utils::COLOR_BLUE)),
Name::new("ground"),
));

let writer = ExprWriter::new();

let init_pos = SetPositionCircleModifier {
center: writer.lit(Vec3::Y * 0.1).expr(),
axis: writer.lit(Vec3::Y).expr(),
radius: writer.lit(1.).expr(),
dimension: ShapeDimension::Volume,
};

let init_axis_x = SetAttributeModifier::new(Attribute::AXIS_X, writer.lit(Vec3::X).expr());
let init_axis_y = SetAttributeModifier::new(Attribute::AXIS_Y, writer.lit(Vec3::Y).expr());
let init_axis_z = SetAttributeModifier::new(Attribute::AXIS_Z, writer.lit(Vec3::Z).expr());

// Particle will complete 3/4 of a rotation around Y axis per second
let rotate_over_time = RotateOverTimeModifier {
rotation: writer
.lit(Vec3::new(0., 270.0f32.to_radians(), 190.0f32.to_radians()))
.expr(),
};

let module = writer.finish();

let effect = effects.add(
EffectAsset::new(32768, SpawnerSettings::once(64.0.into()), module)
.with_name("rotate_over_time")
// Disable motion integration; in this demo particles don't move. This silences some warning
// about missing the VELOCITY attribute.
.with_motion_integration(MotionIntegration::None)
.with_simulation_space(SimulationSpace::Local)
.init(init_pos)
.init(init_axis_x)
.init(init_axis_y)
.init(init_axis_z)
.update(rotate_over_time)
.render(SetColorModifier::new(COLOR))
.render(SetSizeModifier { size: SIZE.into() }),
);

commands.spawn((
Transform::from_translation(Vec3::new(0., 1., 0.)),
ParticleEffect::new(effect),
Name::new("Rotate Over Time"),
));
}

fn rotate_camera(time: Res<Time>, mut camera_transform: Single<&mut Transform, With<Camera3d>>) {
let radius_xz = 18_f32.sqrt();
let a = (time.elapsed_secs() * 0.3).sin();
let (s, c) = a.sin_cos();
**camera_transform =
Transform::from_xyz(c * radius_xz, 3.0, s * radius_xz).looking_at(Vec3::ZERO, Vec3::Y)
}
1 change: 1 addition & 0 deletions examples/rotate_over_time.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This example shows the behavior of the RotateOverTimeModifier.
2 changes: 2 additions & 0 deletions src/modifier/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ pub mod kill;
pub mod output;
pub mod position;
pub mod registry;
mod rotate_over_time;
pub mod velocity;

pub use accel::*;
Expand All @@ -73,6 +74,7 @@ pub use kill::*;
pub use output::*;
pub use position::*;
pub use registry::*;
pub use rotate_over_time::*;
pub use velocity::*;

use crate::{
Expand Down
78 changes: 78 additions & 0 deletions src/modifier/rotate_over_time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use bevy::reflect::Reflect;

use crate::{
Attribute, BoxedModifier, BuiltInExpr, EvalContext, ExprError, ExprHandle, Modifier,
ModifierContext, Module, ShaderWriter,
};

/// Rotates particles over time.
#[derive(Clone, Copy, Reflect)]
pub struct RotateOverTimeModifier {
/// Rotation that the particle will have in a second.
///
/// The rotation is defined as a Euler rotation, applied
/// in XYZ order. Angles must be in radians.
///
/// Expr type: Vec3
pub rotation: ExprHandle,
}

impl Modifier for RotateOverTimeModifier {
fn context(&self) -> ModifierContext {
ModifierContext::Update
}

fn attributes(&self) -> &[Attribute] {
&[Attribute::AXIS_X, Attribute::AXIS_Y, Attribute::AXIS_Z]
}

fn boxed_clone(&self) -> BoxedModifier {
Box::new(*self)
}

fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
let rotation = context.eval(module, self.rotation)?;
let dt = BuiltInExpr::new(crate::graph::BuiltInOperator::DeltaTime).eval(context)?;
context.main_code += &format!(
r#" {{
let euler_angles = {rotation} * {dt};
let cx = cos(euler_angles.x);
let sx = sin(euler_angles.x);
let cy = cos(euler_angles.y);
let sy = sin(euler_angles.y);
let cz = cos(euler_angles.z);
let sz = sin(euler_angles.z);

// Individual axes matrices (Column-major format)
let rx = mat3x3<f32>(
1.0, 0.0, 0.0,
0.0, cx, sx,
0.0, -sx, cx
);

let ry = mat3x3<f32>(
cy, 0.0, -sy,
0.0, 1.0, 0.0,
sy, 0.0, cy
);

let rz = mat3x3<f32>(
cz, sz, 0.0,
-sz, cz, 0.0,
0.0, 0.0, 1.0
);

// Combines rotations (Applies X, then Y, then Z)
let rotation = rz * ry * rx;
particle.{0} = particle.{0} * rotation;
particle.{1} = particle.{1} * rotation;
particle.{2} = particle.{2} * rotation;
}}
"#,
Attribute::AXIS_X.name(),
Attribute::AXIS_Y.name(),
Attribute::AXIS_Z.name(),
);
Ok(())
}
}