# effect/particlesystem (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/effect/particlesystem/

Particle system component.
- ParticleSystem of the original effect/particlesystem.js. Names, defaults and usage (play / stop / emit / simulate / setStart...) follow the original.
- Like the original, particles come out of the origin of the coordinates the component draws in (the top left of the node content_size area is the origin). For a node whose content_size is 0, it is the node position.
  The attractor position (set_attractor) uses the same coordinates as in the original.
- The order of drawing random numbers and of calculations when emitting is also the same as the original. With the same seed (set_random_seed), the same particles as the original come out.
  (The seeded random is the same sequence as the original down to the bit. Particle math is also f64 like the original)
- Draws with draw_colored_quads, carrying a color per vertex. Like the original, the image shape also does not use the color curve or start color (r, g, b) and only fades by start alpha x (1 - life ratio).
  The original draws image separately per particle, and the Rust version draws at once with the image texture. (the drawn positions and colors are the same)
- Differences from the original:
  - Emitter shape, render shape and blending are enums (ParticleEmitterShape, ParticleRenderShape, BlendMode) instead of the original strings. The description (apply_description) reads the original strings.
  - Rust has no default arguments of the original (like setStartLifetime(min, max = min)), so both values are taken. The origin offset of emit is an Option.
  - The node local position added when emitting in world space (set_world_space) is read in tick, because a Rust component cannot read the node outside tick and draw.
    To emit at the node position at emit time like the original, emit with ParticleSystem::emit_in_tree(tree, node, count, offset), or put the position with set_node_position and emit.
    (The emit event of Timeline emits after putting the node position at that moment)
  - Vertex color quads are drawn in parts of the vertex count that can be drawn at once (the Graphic limit). The original grows the array and draws at once.
  - The imageDataUrl of the description (the data: URL of the image picked in the particle editor) is decoded on the spot on desktop, and on the web the browser decodes it like the original and it draws once decoded.

## ParticleSystem (struct) (Default, Component)

Particle system component.
- When attached to a node, it emits (per second emission, bursts) every tick, integrates particles and draws them as vertex color quads. Coordinates are component coordinates with the top left of the node's content_size area as the origin.

Example: A firework burst that goes off once

```rust
use vanilla::{Color, NodeTree, ParticleEmitterShape, ParticleRenderShape, ParticleSystem};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let spark_id = node_tree.create_child(root_id, "Spark");
let particle_system = node_tree[spark_id].add_component(ParticleSystem::new());
particle_system.set_looping(false);
particle_system.set_emission_rate(0.0);
particle_system.set_burst_list(vec![(0.0, 24)]);
particle_system.set_emitter_shape(ParticleEmitterShape::Circle);
particle_system.set_shape_radius(8.0);
particle_system.set_start_lifetime(0.6, 1.0);
particle_system.set_start_speed(120.0, 240.0);
particle_system.set_start_color(Color::create(1.0, 0.8, 0.2, 1.0), Color::create(1.0, 0.4, 0.1, 1.0));
particle_system.set_gravity(0.0, 300.0);
particle_system.set_render_shape(ParticleRenderShape::Streak);
particle_system.set_additive(true);
particle_system.set_random_seed(7);
particle_system.simulate(0.016);
assert_eq!(particle_system.get_particle_count(), 24);
particle_system.simulate(1.5);
assert_eq!(particle_system.get_particle_count(), 0);
assert!(particle_system.is_finished());
```

- `pub fn new() -> ParticleSystem` (constructor, since 0.3.2): Creates. (defaults of the original constructor)
  - returns ParticleSystem: A particle system with the original defaults. (playing, looping, duration 1 second, up to 512, 20 per second, Point shape, lifetime 1 second, speed 60, size 6, white, Circle render, normal blending, no seed)
- `pub fn play(&mut self)` (method, since 0.3.2): Play.
- `pub fn stop(&mut self, is_clearing: bool)` (method, since 0.3.2): Stops. (also clears live particles if is_clearing)
  - `is_clearing` bool: If true, clears live particles and the accumulated emission and resets the seeded random numbers to the start. If false, only stops emitting and the remaining particles live out their lifetime.
- `pub fn emit(&mut self, count: usize, origin_offset: Option<Vector2>)` (method, since 0.3.2): Emits several at once. (for event-like effects such as a button click, origin_offset adjusts the emission origin, relative to node local)
  - Emits even when not playing.
  - `count` usize: Number of particles to emit. (those beyond the maximum particle count are not emitted)
  - `origin_offset` Option<Vector2>: Emission origin offset. (component coordinates) The origin if None.

  Example: Emit up to the maximum and emit with a moved origin

  ```rust
  use vanilla::{ParticleSystem, Vector2};
  
  let mut particle_system = ParticleSystem::new();
  particle_system.set_max_particle_count(12);
  particle_system.emit(10, None);
  particle_system.emit(5, Some(Vector2::create(0.0, -20.0)));
  assert_eq!(particle_system.get_particle_count(), 12);
  assert_eq!(particle_system.get_particle_position_list()[11], Vector2::create(0.0, -20.0));
  ```

- `pub fn emit_in_tree(node_tree: &mut NodeTree, node_id: NodeId, count: usize, origin_offset: Option<Vector2>) -> bool` (static, since 0.4.0): Emits several at the node's current position. (reads the node local position at emit time like the original emit. false if there is no node or particle system)
  - `node_tree` &mut NodeTree: Node tree containing the node.
  - `node_id` NodeId: Node with a ParticleSystem attached. (emits with the first ParticleSystem)
  - `count` usize: Number of particles to emit.
  - `origin_offset` Option<Vector2>: Emission origin offset. (component coordinates) The origin if None.
  - returns bool: true if emitted. false if there is no node or no ParticleSystem attached.

  Example: Emit world space particles at the node's position

  ```rust
  use vanilla::{NodeTree, ParticleSystem, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let spark_id = node_tree.create_child(root_id, "Spark");
  node_tree[spark_id].set_local_position(Vector2::create(100.0, 50.0));
  let particle_system = node_tree[spark_id].add_component(ParticleSystem::new());
  particle_system.set_world_space(true);
  assert!(ParticleSystem::emit_in_tree(&mut node_tree, spark_id, 3, None));
  let position_list = node_tree[spark_id].get_component::<ParticleSystem>().map(|particle_system| particle_system.get_particle_position_list()).unwrap_or_default();
  assert_eq!(position_list, vec![Vector2::create(100.0, 50.0); 3]);
  assert!(!ParticleSystem::emit_in_tree(&mut node_tree, root_id, 3, None));
  ```

- `pub fn set_node_position(&mut self, node_position: Vector2)` (method, since 0.4.0): Sets the node local position added when emitting in world space. (for correcting the value tick records at the emitting site)
  - `node_position` Vector2: Node local position. (parent coordinates, the next tick overwrites it with the node position)
- `pub fn simulate(&mut self, time_delta: f64)` (method, since 0.3.2): Advances time. (emission + integration, called from outside for manual tick)
  - If not playing, nothing is emitted and only the remaining particles move. The time received at once is integrated in one step.
  - `time_delta` f64: Time to advance. (seconds)

  Example: Advance 0.5 seconds with a manual tick

  ```rust
  use vanilla::ParticleSystem;
  
  let mut particle_system = ParticleSystem::new();
  particle_system.set_manual_tick(true);
  particle_system.set_emission_rate(10.0);
  particle_system.simulate(0.5);
  assert_eq!(particle_system.get_particle_count(), 5);
  ```

- `pub fn set_emission_rate(&mut self, emission_rate: f64)` (method, since 0.3.2): Sets the per second emission count.
  - `emission_rate` f64: Number of particles emitted per second. (0 or less means no steady emission, default 20. If not looping, emits only during duration)
- `pub fn set_burst_list(&mut self, burst_list: Vec<(f64, usize)>)` (method, since 0.3.2): Sets the burst list. (list of (seconds from playback start, count))
  - `burst_list` Vec<(f64, usize)>: List of (seconds from playback start, count). Replaces the previous list and clears the emitted marks. If looping, emits again every duration period.
- `pub fn set_emitter_shape(&mut self, emitter_shape: ParticleEmitterShape)` (method, since 0.3.2): Sets the emitter shape.
  - `emitter_shape` ParticleEmitterShape: Shape that decides where and in which direction particles are emitted. (default Point)
- `pub fn set_shape_radius(&mut self, shape_radius: f64)` (method, since 0.3.2): circle / cone radius.
  - `shape_radius` f64: Emission radius of circle and cone. (component coordinates, default 0)
- `pub fn set_cone_angle(&mut self, cone_angle_radian: f64)` (method, since 0.3.2): cone half-angle. (radians)
  - `cone_angle_radian` f64: Half angle of the fan relative to up (-Y). (radians, default 0.5)
- `pub fn set_box_size(&mut self, width: f64, height: f64)` (method, since 0.3.2): Sets the size of the box emission area. (the origin is the center)
  - `width` f64: Area width. (component coordinates, default 0)
  - `height` f64: Area height. (component coordinates, default 0)
- `pub fn set_edge_width(&mut self, edge_width: f64)` (method, since 0.4.0): Horizontal length of the edge emitter shape.
  - `edge_width` f64: Length of the horizontal line segment. (component coordinates, the origin is the center, default 0)
- `pub fn set_start_lifetime(&mut self, minimum_seconds: f64, maximum_seconds: f64)` (method, since 0.3.2): Sets the start lifetime range. (random between the two when emitting)
  - `minimum_seconds` f64: Shortest lifetime. (seconds, default 1)
  - `maximum_seconds` f64: Longest lifetime. (seconds, default 1, fixed if equal to the minimum)
- `pub fn set_start_speed(&mut self, minimum_speed: f64, maximum_speed: f64)` (method, since 0.3.2): Sets the start speed range. (random between the two when emitting)
  - `minimum_speed` f64: Slowest speed. (component coordinates per second, default 60)
  - `maximum_speed` f64: Fastest speed. (component coordinates per second, default 60)
- `pub fn set_start_size(&mut self, minimum_size: f64, maximum_size: f64)` (method, since 0.3.2): Sets the start size range. (random between the two when emitting)
  - `minimum_size` f64: Smallest diameter. (component coordinates, default 6)
  - `maximum_size` f64: Largest diameter. (component coordinates, default 6)
- `pub fn set_start_rotation(&mut self, minimum_radian: f64, maximum_radian: f64)` (method, since 0.3.2): Sets the start rotation range. (random between the two when emitting, only rect and image renders rotate)
  - `minimum_radian` f64: Smallest rotation. (radians, default 0)
  - `maximum_radian` f64: Largest rotation. (radians, default 0)
- `pub fn set_start_color(&mut self, color_a: impl Into<Color>, color_b: impl Into<Color>)` (method, since 0.3.2): Start color. (random between the two)
  - `color_a` impl Into<Color>: Color at one end. (a Color or text like "#rrggbb", default white)
  - `color_b` impl Into<Color>: Color at the other end. (mixes the two colors at a random ratio when emitting, default white)
- `pub fn set_color_over_lifetime(&mut self, gradient: Vec<(f64, Color)>)` (method, since 0.3.2): Color curve over lifetime. (list of pairs of life ratio 0 ~ 1 and color, multiplied by the start color)
  - `gradient` Vec<(f64, Color)>: List of (life ratio 0 ~ 1, color). Give them in ascending ratio order. Values in between are mixed linearly, and an empty list keeps the start color as is. (not used by the image render)
- `pub fn set_size_over_lifetime(&mut self, start_scale: f64, end_scale: f64)` (method, since 0.3.2): Sets the size scale over lifetime. (linear from birth to the end of life)
  - `start_scale` f64: Scale at birth. (default 1)
  - `end_scale` f64: Scale at the end of life. (default 1)
- `pub fn set_angular_velocity(&mut self, minimum_radian_per_second: f64, maximum_radian_per_second: f64)` (method, since 0.3.2): Sets the angular velocity range. (random between the two when emitting)
  - `minimum_radian_per_second` f64: Slowest angular velocity. (radians per second, default 0)
  - `maximum_radian_per_second` f64: Fastest angular velocity. (radians per second, default 0)
- `pub fn set_gravity(&mut self, gravity_x: f64, gravity_y: f64)` (method, since 0.3.2): Sets the gravity acceleration.
  - `gravity_x` f64: Horizontal acceleration. (component coordinates per second per second, default 0)
  - `gravity_y` f64: Vertical acceleration. (down is +, default 0)
- `pub fn set_damping(&mut self, damping: f64)` (method, since 0.3.2): Damping coefficient per second. (0 = none)
  - `damping` f64: Damping coefficient. (each simulate multiplies the velocity by max(1 - coefficient x time_delta, 0). None if 0 or less, default 0)
- `pub fn set_render_shape(&mut self, render_shape: ParticleRenderShape)` (method, since 0.4.0): Sets the render shape. (default circle)
  - `render_shape` ParticleRenderShape: Shape to draw particles with.
- `pub fn set_image(&mut self, image: Option<Rc<Image>>)` (method, since 0.3.2): Particle image. (used when the render shape is image)
  - `image` Option<Rc<Image>>: Image to draw with the Image render. If None, the Image render also draws a white square in the particle color.
- `pub fn set_additive(&mut self, is_additive: bool)` (method, since 0.3.2): Whether to use additive blending. (sugar for set_blend_mode(Lighter))
  - `is_additive` bool: Lighter blending if true, Normal if false.
- `pub fn set_blend_mode(&mut self, blend_mode: BlendMode)` (method, since 0.3.2): Sets the blending.
  - `blend_mode` BlendMode: Blending to draw particles with. (default Normal, restores the previous blending after drawing)
- `pub fn set_attractor(&mut self, x: f64, y: f64, strength: f64, swirl: f64)` (method, since 0.4.0): Sets the attractor. (position in component coordinates, acceleration toward the center (pushes away if negative), tangential acceleration (swirl))
  - `x` f64: Attractor x. (component coordinates)
  - `y` f64: Attractor y. (component coordinates)
  - `strength` f64: Acceleration toward the center. (per second per second, pushes away if negative. Distances below 4 are treated as 4)
  - `swirl` f64: Tangential acceleration. (per second per second, swirl)
- `pub fn clear_attractor(&mut self)` (method, since 0.4.0): Clears the attractor.
- `pub fn set_wobble(&mut self, amplitude: f64, frequency: f64)` (method, since 0.4.0): Sets the wobble. (horizontal sway amplitude, angular speed per second. The original default angular speed is 4)
  - `amplitude` f64: Horizontal sway amplitude. (component coordinates, none if 0 or less. Added only when drawing, not to the position)
  - `frequency` f64: Sway angular speed. (radians per second, default 4)
- `pub fn set_streak_scale(&mut self, streak_scale: f64)` (method, since 0.4.0): Streak length ratio. (length of the streak = velocity x this value)
  - `streak_scale` f64: Streak length ratio multiplied by the speed. (seconds, default 0.06)
- `pub fn set_world_space(&mut self, is_world_space: bool)` (method, since 0.4.0): Sets world space. (when on, particles stay where they are even if the node moves after emitting)
  - `is_world_space` bool: If true, adds the node local position when emitting and subtracts the node position when drawing. (default false)
- `pub fn set_looping(&mut self, is_looping: bool)` (method, since 0.3.2): Sets looping.
  - `is_looping` bool: If true, emits endlessly and re-emits bursts every duration period. If false, emits only during duration. (default true)
- `pub fn set_duration(&mut self, duration: f64)` (method, since 0.3.2): Emission duration when looping is off. (burst repeat period)
  - `duration` f64: Emission time and also the burst repeat period. (seconds, default 1)
- `pub fn set_max_particle_count(&mut self, max_particle_count: usize)` (method, since 0.3.2): Sets the maximum particle count.
  - `max_particle_count` usize: Maximum number of live particles. (no new ones are emitted at this count, default 512)
- `pub fn apply_description(&mut self, description: &serde_json::Value)` (method, since 0.3.2): Applies a description (JSON). (the original applyDescription. Shared by vfx asset loading and the particle editor. Only the given items are applied. Colors are [r, g, b, a] arrays)
  - attractor is { x, y, strength, swirl }, and null releases the attractor. wobble is [amplitude, angular speed], and the angular speed is 4 when omitted.
  - imageDataUrl is the data: URL of the image picked in the particle editor. That image is set as the particle image, and when empty or null the image is cleared.
  - When the maximum of a [minimum, maximum] pair is omitted, it is the same as the minimum, like the original default arguments.
  - `description` &serde_json::Value: Description object. (the original keys looping, duration, maxParticleCount, emissionRate, bursts, shape, shapeRadius, coneAngle, boxSize, edgeWidth, lifetime, speed, size, rotation, angularVelocity, startColorA, startColorB, colorOverLifetime, sizeOverLifetime, gravity, damping, attractor, wobble, renderShape, blendMode, streakScale, worldSpace. Shapes and blending with unknown names are ignored)

  Example: Set a one-shot burst with a description

  ```rust
  use serde_json::json;
  use vanilla::ParticleSystem;
  
  let mut particle_system = ParticleSystem::new();
  particle_system.apply_description(&json!({
  	"looping": false,
  	"duration": 1.2,
  	"emissionRate": 0,
  	"bursts": [{ "time": 0, "count": 25 }],
  	"shape": "circle",
  	"shapeRadius": 6,
  	"lifetime": [0.8, 1.0],
  	"speed": [100, 200],
  	"startColorA": [1, 0.8, 0.2, 1],
  	"blendMode": "lighter",
  }));
  particle_system.simulate(0.1);
  assert_eq!(particle_system.get_particle_count(), 25);
  ```

- `pub fn get_particle_count(&self) -> usize` (method, since 0.3.2): Returns the number of live particles.
  - returns usize: Number of live particles.
- `pub fn get_particle_position_list(&self) -> Vec<Vector2>` (method, since 0.4.0): List of particle positions. (component coordinates, integrated positions without the wobble. For same seed comparisons and tests)
  - returns Vec<Vector2>: List of positions of live particles. (in emission order)
- `pub fn is_playing(&self) -> bool` (method, since 0.3.2): Returns whether it is playing.
  - returns bool: true after play and before stop. (default true)
- `pub fn is_finished(&self) -> bool` (method, since 0.3.2): Whether it has finished. (nothing more to emit and no particles left, for disposing of one-shot nodes)
  - If stopped, or not looping with duration elapsed and all bursts emitted, there is nothing to emit.
  - returns bool: true if no particles remain and nothing more will be emitted. (false until stopped if looping)
- `pub fn set_manual_tick(&mut self, is_manual_tick: bool)` (method, since 0.3.2): Sets manual tick. (when on, it does not advance in the node update, only with simulate. For when time is handled from outside, like a timeline)
  - `is_manual_tick` bool: If true, the node tick only records the node position, and it advances only when simulate is called. (default false)
- `pub fn is_manual_tick(&self) -> bool` (method, since 0.3.2): Returns whether manual tick is on.
  - returns bool: true if manual tick.
- `pub fn set_random_seed(&mut self, random_seed: u32)` (method, since 0.3.2): Sets the random seed. (when set, spawn random numbers switch to seeded random numbers and go back to the seed on every stop(true). For rewind reproduction)
  - `random_seed` u32: Seed value. (the same seed gives the same particles)

  Example: Two systems with the same seed emit at the same positions

  ```rust
  use vanilla::ParticleSystem;
  
  let mut first_system = ParticleSystem::new();
  let mut second_system = ParticleSystem::new();
  first_system.set_random_seed(42);
  second_system.set_random_seed(42);
  first_system.emit(8, None);
  second_system.emit(8, None);
  first_system.simulate(0.25);
  second_system.simulate(0.25);
  assert_eq!(first_system.get_particle_position_list(), second_system.get_particle_position_list());
  assert_eq!(first_system.get_random_seed(), Some(42));
  ```

- `pub fn get_random_seed(&self) -> Option<u32>` (method, since 0.3.2): Returns the random seed.
  - returns Option<u32>: Seed given with set_random_seed. None if not given. (uses the global random numbers)
- `pub fn random_range(&mut self, minimum_value: f64, maximum_value: f64) -> f64` (method, since 0.3.2): Random numbers for spawning. (seeded random numbers if there is a seed, otherwise the global random numbers)
  - `minimum_value` f64: Lower bound. (inclusive)
  - `maximum_value` f64: Upper bound. (exclusive)
  - returns f64: Random number from minimum_value inclusive to maximum_value exclusive. (advances the sequence by one for seeded random numbers)

## ParticleEmitterShape (enum) (Clone, Copy, Debug, PartialEq, Eq)

Emitter shape. (the original ParticleEmitterShape)

- `Point`: In all directions from a single point at the node origin.
- `Circle`: Outward from a random position inside the radius.
- `Cone`: In a fan direction with half angle cone_angle relative to up (-Y), from a position inside the radius in that direction.
- `Box`: Upward (-Y) from a random position inside the box_size rectangle.
- `Edge`: Downward (+Y) from a random position on the horizontal line segment of edge_width. (for scattering from above, like snow or rain)

## ParticleRenderShape (enum) (Clone, Copy, Debug, PartialEq, Eq)

Render shape. (the original ParticleRenderShape)

- `Circle`: Soft circle. (default)
- `Rect`: Rectangle. (a spinning plate like confetti)
- `Streak`: A streak stretched in the direction of travel. (rain, meteors)
- `Image`: The image set with set_image.
