Write an effect
An effect is a Rust static with metadata and a spawn function. This page shows its parts, the drawing API, the rules that keep it deterministic, and how to register and test it.
Anatomy
Effects live in crates/pixfx-effects/src/<category>/<name>.rs. The skeleton below follows fire/candle.rs:
use pixfx_core::{Effect, EffectState, Layer, Meta, NumOpt, Options};
use pixfx_draw::Painter;
use pixfx_draw::color::Rgba;
pub struct Ember;
pub static EMBER: Ember = Ember;
const SIZE: NumOpt = NumOpt::new("size", 3.0).within(1.0, 8.0); // an option of its own, held to a range
const META: Meta = Meta {
id: "fire/ember",
name: "Ember",
desc: "A single coal glowing and dimming.",
tags: &["fire", "prop", "light", "loop"],
size: (40, 40), // room for the glow's radius on every side of the origin
origin: (20, 24), // the point that lands where the caller plays it
duration: 2.0, // seconds per loop (or of the one-shot)
looping: true,
fps: 30,
seed: 1,
state: None,
options: &[SIZE.spec()],
};
const PALETTE: [Rgba; 3] = [
Rgba::hex24(0x4a1712),
Rgba::hex24(0xf2561d),
Rgba::hex24(0xffc23d),
];
impl Effect for Ember {
fn meta(&self) -> &Meta {
&META
}
fn spawn(&self, opts: &Options, seed: u64) -> Box<dyn EffectState> {
Box::new(State {
ramp: opts.palette_or(&PALETTE),
size: opts.num(&SIZE),
seed: seed as f64,
})
}
}
struct State {
ramp: Vec<Rgba>,
size: f64,
seed: f64,
}
impl EffectState for State {
fn draw(&self, p: &mut Painter, t: f64, layer: Layer) {
if layer == Layer::Back {
return; // nothing behind the character
}
// 0..1, one period per `duration` (2 s), so the loop closes exactly
let k = 0.5 + 0.5 * libm::sin(t * core::f64::consts::PI + self.seed);
let last = self.ramp.len().saturating_sub(1);
let pick = (k * last as f64) as usize; // dark to bright as it glows
let Some(&c) = self.ramp.get(pick.min(last)) else {
return;
};
let s = self.size;
p.rect(-s, -s, s * 2.0, s * 2.0, c, 1.0);
p.glow(0.0, 0.0, 10.0, c, 0.6 * k); // light is additive, drawn into the light layer
}
}
Draw in local space: (0, 0) is the effect's origin, y grows downward. The instance places, mirrors and rotates the painter before calling draw, and applies fade-out and the light option, so the effect never handles them.
Draw from time, or simulate
Most effects draw purely from t (seconds into the loop) and the seed, so any frame can be drawn on its own and loops close exactly. Effects with real physics (sparks that bounce, debris that settles) keep state and override EffectState::update(dt), which the instance calls once per sub-step of at most 1/120 s.
The painter
Painter (crates/pixfx-draw/src/painter.rs) draws into the frame's two layers. All coordinates are local and may be fractional; shapes snap to whole pixels.
| Method | Draws |
|---|---|
px, dot, blend | One pixel: opaque; at an alpha faded by ordered dither; or translucent. |
line, rect, ellipse, tri, poly | Filled shapes and 1 px lines. Colour and alpha can be constants or functions of the shape's own coordinates. |
each, shade | Visit every pixel in a local box and decide its colour and light yourself. Every filled shape is built on each, so shapes mirror and rotate exactly. |
glow, glow_line, glow_ring | Light only: radial glow falling as (1 − d)² to 0 at radius r, along a line, or round a ring. |
put, add, blend_px | Write colour or add light at a screen pixel. |
Shared building blocks for fire (flame tongues, licks, sparks, embers, smoke puffs, floor light) are in crates/pixfx-effects/src/fire/lib.rs.
Rules
These keep native and wasm builds bit-identical and are enforced by the compiler and clippy:
- No platform float math.
clippy.tomldisallowsf64::sin,sqrt,floor,roundand every other transcendental, rounding or fused method. Uselibm::*, andpixfx_draw::math::js_roundwhere JavaScript would callMath.round. - Randomness comes from the seed. Use
math::rand,hash,noiseor a seededRng, never a system random source or the clock. - No panics.
unwrap,expectandpanicare denied; handle a missing value (let Some(..) else { return }). - No
unsafe. Every crate has#![forbid(unsafe_code)]. - Ports keep pixelfx's semantics. Where JavaScript behaves differently from Rust (NaN in
Math.min,| 0truncation,Uint8ClampedArrayrounding), use themath::js_*andto_int32/to_uint32helpers.
Register it
Each effect has its own cargo feature, the id with / as -, so a game builds only the effects it plays. tests/features.rs fails if one of these is missing:
- In the category's
mod.rs(for examplesrc/fire/mod.rs):#[cfg(feature = "fire-ember")] mod ember;and#[cfg(feature = "fire-ember")] pub use ember::EMBER;. - In
crates/pixfx-effects/Cargo.toml:fire-ember = [], and add it to its category feature (fire), which is inall. - In
crates/pixfx-effects/src/lib.rs:#[cfg(feature = "fire-ember")] &fire::EMBER,inEFFECTS. The order there is the ordereffects()returns.
Check once with every effect built: cargo test -p pixfx-effects --test features. Every renderer, the scripts and the JS shells pick it up from the registry; nothing else needs changing.
Test it
Build and test the effect alone, behind its feature, so nothing else compiles or runs:
cargo test -p pixfx-effects --no-default-features --features fire-ember --all-targets
PIXFX_BLESS=1 cargo test -p pixfx-effects --no-default-features --features fire-ember --test determinism -- --ignored
cargo test -p pixfx-effects --no-default-features --features fire-ember --test determinism -- --ignored
cargo run -p pixfx-export --example gif -- fire/ember --scale 4
cargo run --release -p pixfx-effects --no-default-features --features fire-ember --example bench
- Look at the gif (
target/out/fire_ember.gif) before you bless: blessing records what is drawn, right or wrong. Blessing with one effect built rewrites only its entry intests/goldens/frame_hashes.json. - For a port, run parity against its source (pixelfx or the vendored Sprite Fusion file).
- A change shared by many effects (
pixfx-core,pixfx-draw, a category'slib.rs) runs the same tests without the feature flags, and the wasm check once:wasm-pack test --node crates/pixfx-effects --test determinism -- --include-ignored.