#[cfg(feature = "fluid")]
mod cpu;
pub(crate) mod passes;
pub(crate) mod read_out;
pub(crate) mod shader;
#[cfg(feature = "fluid")]
mod volume;
pub(crate) mod volume_config;
pub(crate) mod volume_shader;
#[cfg(all(feature = "fluid", target_arch = "wasm32", not(threers_no_js_bindings)))]
mod web;
#[cfg(feature = "fluid")]
use std::sync::Arc;
#[cfg(feature = "fluid")]
use crate::renderer::fullscreen::{self, draw, DoubleFbo, Fbo, Load};
#[cfg(feature = "fluid")]
use passes::{
batch_ubo, bind, ubo, Params, Pipelines, FLAG_BLOOM, FLAG_ENCODE, FLAG_SHADING, FLAG_SUNRAYS,
MAX_BATCH,
};
#[cfg(feature = "fluid")]
pub use cpu::CpuFluid3d;
#[cfg(feature = "fluid")]
pub use passes::FluidFormats;
#[cfg(feature = "fluid")]
pub use volume::{memory_for, within_memory, FluidSim3d, STAGE_NAMES};
pub use volume_config::{
quality3d, quality3d_names, Atlas, FluidConfig3d, FluidQuality3d, QUALITY_LEVELS_3D,
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FluidConfig {
pub sim_resolution: u32,
pub dye_resolution: u32,
pub density_dissipation: f32,
pub velocity_dissipation: f32,
pub pressure: f32,
pub pressure_iterations: u32,
pub show_fps: bool,
pub time_scale: f32,
pub advection: Advection,
pub pressure_solver: PressureSolver,
pub multigrid_cycles: u32,
pub gradient_scale: f32,
pub curl: f32,
pub splat_radius: f32,
pub splat_force: f32,
pub shading: bool,
pub colorful: bool,
pub color_update_speed: f32,
pub back_color: [f32; 3],
pub transparent: bool,
pub bloom: bool,
pub bloom_iterations: u32,
pub bloom_resolution: u32,
pub bloom_intensity: f32,
pub bloom_threshold: f32,
pub bloom_soft_knee: f32,
pub sunrays: bool,
pub sunrays_resolution: u32,
pub sunrays_weight: f32,
pub seed: u64,
}
impl Default for FluidConfig {
fn default() -> Self {
Self {
sim_resolution: 128,
dye_resolution: 1024,
density_dissipation: 1.0,
velocity_dissipation: 0.2,
pressure: 0.8,
pressure_iterations: 20,
show_fps: false,
time_scale: 1.0,
advection: Advection::SemiLagrangian,
pressure_solver: PressureSolver::Jacobi,
multigrid_cycles: 1,
gradient_scale: 1.0,
curl: 30.0,
splat_radius: 0.25,
splat_force: 6000.0,
shading: true,
colorful: true,
color_update_speed: 10.0,
back_color: [0.0, 0.0, 0.0],
transparent: false,
bloom: true,
bloom_iterations: 8,
bloom_resolution: 256,
bloom_intensity: 0.8,
bloom_threshold: 0.6,
bloom_soft_knee: 0.7,
sunrays: true,
sunrays_resolution: 196,
sunrays_weight: 1.0,
seed: 0x5EED_F101_D1CE,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Advection {
#[default]
SemiLagrangian,
MacCormack,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PressureSolver {
#[default]
Jacobi,
Multigrid,
}
impl FluidConfig {
pub fn with_quality(mut self, quality: &FluidQuality) -> Self {
self.sim_resolution = quality.sim_resolution;
self.dye_resolution = quality.dye_resolution;
self.pressure_iterations = quality.pressure_iterations;
self.bloom_iterations = quality.bloom_iterations;
self.bloom_resolution = quality.bloom_resolution;
self.sunrays_resolution = quality.sunrays_resolution;
self
}
pub fn plain() -> Self {
Self {
dye_resolution: 512,
shading: false,
bloom: false,
sunrays: false,
..Self::default()
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FluidQuality {
pub name: &'static str,
pub sim_resolution: u32,
pub dye_resolution: u32,
pub pressure_iterations: u32,
pub bloom_iterations: u32,
pub bloom_resolution: u32,
pub sunrays_resolution: u32,
}
pub const QUALITY_LEVELS: &[FluidQuality] = &[
FluidQuality {
name: "low",
sim_resolution: 64,
dye_resolution: 256,
pressure_iterations: 12,
bloom_iterations: 6,
bloom_resolution: 128,
sunrays_resolution: 128,
},
FluidQuality {
name: "medium",
sim_resolution: 96,
dye_resolution: 512,
pressure_iterations: 16,
bloom_iterations: 7,
bloom_resolution: 192,
sunrays_resolution: 160,
},
FluidQuality {
name: "high",
sim_resolution: 128,
dye_resolution: 1024,
pressure_iterations: 20,
bloom_iterations: 8,
bloom_resolution: 256,
sunrays_resolution: 196,
},
FluidQuality {
name: "ultra",
sim_resolution: 256,
dye_resolution: 2048,
pressure_iterations: 32,
bloom_iterations: 9,
bloom_resolution: 512,
sunrays_resolution: 384,
},
FluidQuality {
name: "extreme",
sim_resolution: 512,
dye_resolution: 4096,
pressure_iterations: 48,
bloom_iterations: 10,
bloom_resolution: 1024,
sunrays_resolution: 768,
},
];
pub fn quality(name: &str) -> Option<&'static FluidQuality> {
QUALITY_LEVELS.iter().find(|q| q.name == name)
}
pub fn quality_names() -> impl Iterator<Item = &'static str> {
QUALITY_LEVELS.iter().map(|q| q.name)
}
#[derive(Clone, Copy, Debug)]
struct Pointer {
id: i32,
x: f32,
y: f32,
dx: f32,
dy: f32,
down: bool,
moved: bool,
color: [f32; 3],
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FluidSplat {
pub x: f32,
pub y: f32,
pub dx: f32,
pub dy: f32,
pub color: [f32; 3],
pub radius: f32,
pub erase: bool,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Pointers(Vec<Pointer>);
impl Pointers {
pub(crate) fn down(&mut self, id: i32, x: f32, y: f32, color: [f32; 3]) {
let p = Pointer {
id,
x,
y,
dx: 0.0,
dy: 0.0,
down: true,
moved: false,
color,
};
match self.0.iter_mut().find(|p| p.id == id || !p.down) {
Some(slot) => *slot = p,
None => self.0.push(p),
}
}
pub(crate) fn move_to(&mut self, id: i32, x: f32, y: f32, aspect: f32) {
let Some(p) = self.0.iter_mut().find(|p| p.id == id && p.down) else {
return;
};
let (px, py) = (p.x, p.y);
p.x = x;
p.y = y;
p.dx = (p.x - px) * if aspect < 1.0 { aspect } else { 1.0 };
p.dy = (p.y - py) / if aspect > 1.0 { aspect } else { 1.0 };
p.moved = p.dx != 0.0 || p.dy != 0.0;
}
pub(crate) fn up(&mut self, id: i32) {
if let Some(p) = self.0.iter_mut().find(|p| p.id == id) {
p.down = false;
}
}
pub(crate) fn recolor(&mut self, mut color: impl FnMut() -> [f32; 3]) {
self.0.iter_mut().for_each(|p| p.color = color());
}
pub(crate) fn take_moved(&mut self, force: f32) -> Vec<(f32, f32, f32, f32, [f32; 3])> {
self.0
.iter_mut()
.filter(|p| p.moved)
.map(|p| {
p.moved = false;
(p.x, p.y, p.dx * force, p.dy * force, p.color)
})
.collect()
}
}
pub(crate) struct Rng(u64);
impl Rng {
pub(crate) fn new(seed: u64) -> Self {
Self(seed | 1)
}
pub(crate) fn next_f32(&mut self) -> f32 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
((x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 40) as f32) / 16_777_216.0
}
}
#[cfg(metal_core)]
pub(crate) fn hsv_to_rgb_for_backends(h: f32, s: f32, v: f32) -> [f32; 3] {
hsv_to_rgb(h, s, v)
}
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] {
let i = (h * 6.0).floor();
let f = h * 6.0 - i;
let p = v * (1.0 - s);
let q = v * (1.0 - f * s);
let t = v * (1.0 - (1.0 - f) * s);
match (i as i32).rem_euclid(6) {
0 => [v, t, p],
1 => [q, v, p],
2 => [p, v, t],
3 => [p, q, v],
4 => [t, p, v],
_ => [v, p, q],
}
}
#[cfg(feature = "fluid")]
fn grid_size_limited(resolution: u32, width: u32, height: u32, max: u32) -> (u32, u32) {
let (w, h) = grid_size(resolution, width, height);
let longest = w.max(h);
if longest <= max.max(1) {
return (w, h);
}
let scale = max as f64 / longest as f64;
(
((w as f64 * scale).floor() as u32).max(1),
((h as f64 * scale).floor() as u32).max(1),
)
}
#[cfg(feature = "fluid")]
fn grid_size(resolution: u32, width: u32, height: u32) -> (u32, u32) {
let (width, height) = (width.max(1), height.max(1));
let aspect = width as f32 / height as f32;
let aspect = if aspect < 1.0 { 1.0 / aspect } else { aspect };
let min = resolution.max(1);
let max = ((resolution as f32 * aspect).round() as u32).max(1);
if width > height {
(max, min)
} else {
(min, max)
}
}
#[cfg(feature = "fluid")]
struct MgLevel {
pressure: DoubleFbo,
rhs: Fbo,
residual: Fbo,
ubo_smooth: wgpu::Buffer,
ubo_residual: wgpu::Buffer,
ubo_restrict: wgpu::Buffer,
ubo_prolong: wgpu::Buffer,
}
pub(crate) const MG_COARSEST: u32 = 4;
pub(crate) const MG_WEIGHT: f32 = 1.0;
#[cfg(feature = "fluid")]
fn mg_levels(
device: &wgpu::Device,
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> Vec<MgLevel> {
let mut levels = Vec::new();
let (mut w, mut h) = (width, height);
while w / 2 >= MG_COARSEST && h / 2 >= MG_COARSEST && levels.len() < 8 {
w /= 2;
h /= 2;
levels.push(MgLevel {
pressure: DoubleFbo::new(device, "fluid mg pressure", w, h, format),
rhs: Fbo::new(device, "fluid mg rhs", w, h, format),
residual: Fbo::new(device, "fluid mg residual", w, h, format),
ubo_smooth: ubo(device, "fluid mg smooth"),
ubo_residual: ubo(device, "fluid mg residual"),
ubo_restrict: ubo(device, "fluid mg restrict"),
ubo_prolong: ubo(device, "fluid mg prolong"),
});
}
levels
}
#[cfg(feature = "fluid")]
struct Ubos {
copy: wgpu::Buffer,
curl: wgpu::Buffer,
vorticity: wgpu::Buffer,
divergence: wgpu::Buffer,
clear: wgpu::Buffer,
pressure: wgpu::Buffer,
gradient: wgpu::Buffer,
advect_velocity: wgpu::Buffer,
advect_dye: wgpu::Buffer,
correct_velocity: wgpu::Buffer,
correct_dye: wgpu::Buffer,
splat_velocity: wgpu::Buffer,
splat_dye: wgpu::Buffer,
batch_velocity: wgpu::Buffer,
batch_dye: wgpu::Buffer,
batch_idle: wgpu::Buffer,
bloom_prefilter: wgpu::Buffer,
bloom_final: wgpu::Buffer,
bloom_chain: Vec<wgpu::Buffer>,
sunrays_mask: wgpu::Buffer,
sunrays: wgpu::Buffer,
blur_h: wgpu::Buffer,
blur_v: wgpu::Buffer,
display: wgpu::Buffer,
background: wgpu::Buffer,
read_out: wgpu::Buffer,
}
#[cfg(feature = "fluid")]
impl Ubos {
fn new(device: &wgpu::Device, chain: usize) -> Self {
Self {
copy: ubo(device, "fluid copy"),
curl: ubo(device, "fluid curl"),
vorticity: ubo(device, "fluid vorticity"),
divergence: ubo(device, "fluid divergence"),
clear: ubo(device, "fluid clear"),
pressure: ubo(device, "fluid pressure"),
gradient: ubo(device, "fluid gradient"),
advect_velocity: ubo(device, "fluid advect velocity"),
advect_dye: ubo(device, "fluid advect dye"),
correct_velocity: ubo(device, "fluid correct velocity"),
correct_dye: ubo(device, "fluid correct dye"),
splat_velocity: ubo(device, "fluid splat velocity"),
splat_dye: ubo(device, "fluid splat dye"),
batch_velocity: batch_ubo(device, "fluid splat batch velocity"),
batch_dye: batch_ubo(device, "fluid splat batch dye"),
batch_idle: batch_ubo(device, "fluid splat batch idle"),
bloom_prefilter: ubo(device, "fluid bloom prefilter"),
bloom_final: ubo(device, "fluid bloom final"),
bloom_chain: (0..chain.max(1) * 2)
.map(|_| ubo(device, "fluid bloom chain"))
.collect(),
sunrays_mask: ubo(device, "fluid sunrays mask"),
sunrays: ubo(device, "fluid sunrays"),
blur_h: ubo(device, "fluid blur h"),
blur_v: ubo(device, "fluid blur v"),
display: ubo(device, "fluid display"),
background: ubo(device, "fluid background"),
read_out: ubo(device, "fluid read-out"),
}
}
}
#[cfg(feature = "fluid")]
pub struct FluidSim {
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
config: FluidConfig,
formats: FluidFormats,
width: u32,
height: u32,
max_dim: u32,
dye: DoubleFbo,
velocity: DoubleFbo,
pressure: DoubleFbo,
divergence: Fbo,
curl: Fbo,
residual: Fbo,
scratch_velocity: Fbo,
scratch_dye: Fbo,
mg: Vec<MgLevel>,
bloom: Fbo,
bloom_chain: Vec<Fbo>,
sunrays: Fbo,
sunrays_temp: Fbo,
pipes: Pipelines,
sampler: wgpu::Sampler,
ubos: Ubos,
pointers: Pointers,
rate: read_out::Rate,
history: read_out::History,
rng: Rng,
color_timer: f32,
paused: bool,
}
#[cfg(feature = "fluid")]
#[derive(Clone, Copy)]
struct Splat {
x: f32,
y: f32,
dx: f32,
dy: f32,
color: [f32; 3],
}
#[cfg(feature = "fluid")]
impl FluidSim {
pub fn new(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
width: u32,
height: u32,
config: FluidConfig,
) -> Result<Self, String> {
Self::with_formats(
device,
queue,
width,
height,
config,
FluidFormats::default(),
)
}
pub fn with_formats(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
width: u32,
height: u32,
config: FluidConfig,
formats: FluidFormats,
) -> Result<Self, String> {
if config.pressure_iterations == 0 {
return Err("fluid: pressure_iterations must be at least 1".into());
}
let (width, height) = (width.max(1), height.max(1));
let pipes = Pipelines::new(&device, formats);
let sampler = fullscreen::linear_sampler(&device);
let ubos = Ubos::new(&device, config.bloom_iterations as usize);
let max_dim = device.limits().max_texture_dimension_2d;
let (sw, sh) = grid_size_limited(config.sim_resolution, width, height, max_dim);
let (dw, dh) = grid_size_limited(config.dye_resolution, width, height, max_dim);
let (bw, bh) = grid_size_limited(config.bloom_resolution, width, height, max_dim);
let (rw, rh) = grid_size_limited(config.sunrays_resolution, width, height, max_dim);
let sim = Self {
dye: DoubleFbo::new(&device, "fluid dye", dw, dh, formats.dye),
velocity: DoubleFbo::new(&device, "fluid velocity", sw, sh, formats.velocity),
pressure: DoubleFbo::new(&device, "fluid pressure", sw, sh, formats.scalar),
divergence: Fbo::new(&device, "fluid divergence", sw, sh, formats.scalar),
curl: Fbo::new(&device, "fluid curl", sw, sh, formats.scalar),
residual: Fbo::new(&device, "fluid residual", sw, sh, formats.scalar),
scratch_velocity: Fbo::new(&device, "fluid advect scratch", sw, sh, formats.velocity),
scratch_dye: Fbo::new(&device, "fluid dye scratch", dw, dh, formats.dye),
mg: mg_levels(&device, sw, sh, formats.scalar),
bloom: Fbo::new(&device, "fluid bloom", bw, bh, formats.dye),
bloom_chain: bloom_chain(&device, bw, bh, config.bloom_iterations, formats.dye),
sunrays: Fbo::new(&device, "fluid sunrays", rw, rh, formats.scalar),
sunrays_temp: Fbo::new(&device, "fluid sunrays temp", rw, rh, formats.scalar),
device,
queue,
config,
formats,
width,
height,
max_dim,
pipes,
sampler,
ubos,
pointers: Pointers::default(),
rate: Default::default(),
history: Default::default(),
rng: Rng::new(config.seed),
color_timer: 0.0,
paused: false,
};
Ok(sim)
}
pub fn config(&self) -> &FluidConfig {
&self.config
}
pub fn set_config(&mut self, config: FluidConfig) {
let resized = config.sim_resolution != self.config.sim_resolution
|| config.dye_resolution != self.config.dye_resolution
|| config.bloom_resolution != self.config.bloom_resolution
|| config.bloom_iterations != self.config.bloom_iterations
|| config.sunrays_resolution != self.config.sunrays_resolution;
if config.bloom_iterations != self.config.bloom_iterations {
self.ubos.bloom_chain = (0..config.bloom_iterations.max(1) as usize * 2)
.map(|_| ubo(&self.device, "fluid bloom chain"))
.collect();
}
self.config = config;
if resized {
self.reallocate();
}
}
pub fn fps(&self) -> f32 {
self.rate.fps()
}
#[cfg(test)]
pub(crate) fn set_frame_times_for_test(&mut self, ms: &[f32]) {
self.rate.pin_frame_times(ms);
}
#[cfg(test)]
pub(crate) fn set_fps_for_test(&mut self, fps: f32) {
self.rate.pin_fps(fps);
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn formats(&self) -> FluidFormats {
self.formats
}
pub fn grid_sizes(&self) -> ((u32, u32), (u32, u32)) {
(
(self.dye.width(), self.dye.height()),
(self.velocity.width(), self.velocity.height()),
)
}
pub fn memory_bytes(&self) -> u64 {
let bytes = |fbo: &Fbo| {
let texel = crate::renderer::readback::bytes_per_texel(fbo.texture.format()) as u64;
fbo.width as u64 * fbo.height as u64 * texel
};
let double = |f: &DoubleFbo| bytes(&f.read) + bytes(&f.write);
double(&self.dye)
+ double(&self.velocity)
+ double(&self.pressure)
+ bytes(&self.divergence)
+ bytes(&self.curl)
+ bytes(&self.bloom)
+ self.bloom_chain.iter().map(bytes).sum::<u64>()
+ bytes(&self.sunrays)
+ bytes(&self.sunrays_temp)
}
pub fn paused(&self) -> bool {
self.paused
}
pub fn set_paused(&mut self, paused: bool) {
self.paused = paused;
}
pub fn dye_texture(&self) -> &wgpu::Texture {
&self.dye.read.texture
}
pub fn velocity_texture(&self) -> &wgpu::Texture {
&self.velocity.read.texture
}
pub fn resize(&mut self, width: u32, height: u32) {
let (width, height) = (width.max(1), height.max(1));
if (width, height) == (self.width, self.height) {
return;
}
self.width = width;
self.height = height;
self.reallocate();
}
fn reallocate(&mut self) {
let (w, h) = (self.width, self.height);
let c = &self.config;
let max_dim = self.max_dim;
let (sw, sh) = grid_size_limited(c.sim_resolution, w, h, max_dim);
let (dw, dh) = grid_size_limited(c.dye_resolution, w, h, max_dim);
let (bw, bh) = grid_size_limited(c.bloom_resolution, w, h, max_dim);
let (rw, rh) = grid_size_limited(c.sunrays_resolution, w, h, max_dim);
let (dye_fmt, vel_fmt, scalar) =
(self.formats.dye, self.formats.velocity, self.formats.scalar);
let iterations = c.bloom_iterations;
self.resample(dw, dh, dye_fmt, true);
self.resample(sw, sh, vel_fmt, false);
self.pressure = DoubleFbo::new(&self.device, "fluid pressure", sw, sh, scalar);
self.divergence = Fbo::new(&self.device, "fluid divergence", sw, sh, scalar);
self.curl = Fbo::new(&self.device, "fluid curl", sw, sh, scalar);
self.residual = Fbo::new(&self.device, "fluid residual", sw, sh, scalar);
self.scratch_velocity = Fbo::new(&self.device, "fluid advect scratch", sw, sh, vel_fmt);
self.scratch_dye = Fbo::new(&self.device, "fluid dye scratch", dw, dh, dye_fmt);
self.mg = mg_levels(&self.device, sw, sh, scalar);
self.bloom = Fbo::new(&self.device, "fluid bloom", bw, bh, dye_fmt);
self.bloom_chain = bloom_chain(&self.device, bw, bh, iterations, dye_fmt);
self.sunrays = Fbo::new(&self.device, "fluid sunrays", rw, rh, scalar);
self.sunrays_temp = Fbo::new(&self.device, "fluid sunrays temp", rw, rh, scalar);
}
fn resample(&mut self, w: u32, h: u32, format: wgpu::TextureFormat, dye: bool) {
let field = if dye { &self.dye } else { &self.velocity };
if field.width() == w && field.height() == h {
return;
}
let label = if dye { "fluid dye" } else { "fluid velocity" };
let fresh = Fbo::new(&self.device, label, w, h, format);
write(&self.queue, &self.ubos.copy, Params::default());
let bg = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
&self.ubos.copy,
&self.ubos.batch_idle,
&field.read.view,
None,
None,
);
let pipeline = if dye {
&self.pipes.copy_dye
} else {
&self.pipes.copy_velocity
};
let mut enc = self.encoder("fluid resize");
draw(&mut enc, &fresh.view, Load::Clear, pipeline, &bg);
self.queue.submit([enc.finish()]);
let replacement = DoubleFbo {
read: fresh,
write: Fbo::new(&self.device, label, w, h, format),
};
if dye {
self.dye = replacement;
} else {
self.velocity = replacement;
}
}
pub fn pointer_down(&mut self, id: i32, x: f32, y: f32) {
let color = self.generate_color();
self.pointers
.down(id, x / self.width as f32, y / self.height as f32, color);
}
pub fn pointer_move(&mut self, id: i32, x: f32, y: f32) {
let (w, h) = (self.width as f32, self.height as f32);
self.pointers.move_to(id, x / w, y / h, w / h);
}
pub fn pointer_up(&mut self, id: i32) {
self.pointers.up(id);
}
pub fn multiple_splats(&mut self, count: u32) {
let mut batch = Vec::with_capacity(count as usize);
for _ in 0..count {
let mut color = self.generate_color();
for c in &mut color {
*c *= 10.0;
}
let x = self.rng.next_f32();
let y = self.rng.next_f32();
let dx = 1000.0 * (self.rng.next_f32() - 0.5);
let dy = 1000.0 * (self.rng.next_f32() - 0.5);
batch.push(Splat {
x,
y,
dx,
dy,
color,
});
}
self.record_splats(&batch);
}
pub fn splat(&mut self, x: f32, y: f32, dx: f32, dy: f32, color: [f32; 3]) {
self.record_splats(&[Splat {
x,
y,
dx,
dy,
color,
}]);
}
pub fn set_uniform_velocity(&mut self, x: f32, y: f32) {
write(
&self.queue,
&self.ubos.clear,
Params {
color: [x, y, 0.0, 1.0],
..Default::default()
},
);
let bg = self.bind(&self.ubos.clear, &self.velocity.read, None, None);
let mut enc = self.encoder("fluid fill velocity");
draw(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.fill_velocity,
&bg,
);
self.queue.submit([enc.finish()]);
self.velocity.swap();
}
fn generate_color(&mut self) -> [f32; 3] {
let c = hsv_to_rgb(self.rng.next_f32(), 1.0, 1.0);
[c[0] * 0.15, c[1] * 0.15, c[2] * 0.15]
}
pub fn update(&mut self, dt: f32) {
let dt = dt * self.config.time_scale.max(0.0);
self.update_colors(dt);
self.apply_inputs();
if !self.paused && dt > 0.0 {
self.step(dt);
}
}
fn update_colors(&mut self, dt: f32) {
if !self.config.colorful {
return;
}
self.color_timer += dt * self.config.color_update_speed;
if self.color_timer >= 1.0 {
self.color_timer = self.color_timer.fract();
let mut pointers = std::mem::take(&mut self.pointers);
pointers.recolor(|| self.generate_color());
self.pointers = pointers;
}
}
fn apply_inputs(&mut self) {
let scaled: Vec<Splat> = self
.pointers
.take_moved(self.config.splat_force)
.into_iter()
.map(|(x, y, dx, dy, color)| Splat {
x,
y,
dx,
dy,
color,
})
.collect();
self.record_splats(&scaled);
}
fn record_splats(&mut self, splats: &[Splat]) {
let aspect = self.width as f32 / self.height as f32;
let mut radius = self.config.splat_radius / 100.0;
if aspect > 1.0 {
radius *= aspect;
}
let sized: Vec<FluidSplat> = splats
.iter()
.map(|s| FluidSplat {
x: s.x,
y: s.y,
dx: s.dx,
dy: s.dy,
color: s.color,
radius,
erase: false,
})
.collect();
self.splat_batch(&sized);
}
pub fn splat_batch(&mut self, splats: &[FluidSplat]) {
for chunk in splats.chunks(MAX_BATCH) {
self.record_splat_batch(chunk);
}
}
fn record_splat_batch(&mut self, splats: &[FluidSplat]) {
if splats.is_empty() {
return;
}
let aspect = self.width as f32 / self.height as f32;
let mut velocity_batch = [0.0f32; MAX_BATCH * 8];
let mut dye_batch = [0.0f32; MAX_BATCH * 8];
for (k, s) in splats.iter().enumerate() {
let at = k * 8;
for batch in [&mut velocity_batch, &mut dye_batch] {
batch[at] = s.x;
batch[at + 1] = s.y;
batch[at + 2] = s.radius;
}
velocity_batch[at + 4] = s.dx;
velocity_batch[at + 5] = s.dy;
dye_batch[at + 4] = s.color[0];
dye_batch[at + 5] = s.color[1];
dye_batch[at + 6] = s.color[2];
dye_batch[at + 7] = if s.erase { 1.0 } else { 0.0 };
}
self.queue.write_buffer(
&self.ubos.batch_velocity,
0,
bytemuck::cast_slice(&velocity_batch),
);
self.queue
.write_buffer(&self.ubos.batch_dye, 0, bytemuck::cast_slice(&dye_batch));
let params = Params {
aspect_ratio: aspect,
value: splats.len() as f32,
..Default::default()
};
write(&self.queue, &self.ubos.splat_velocity, params);
write(&self.queue, &self.ubos.splat_dye, params);
let bg_velocity = self.bind_batched(
&self.ubos.splat_velocity,
&self.ubos.batch_velocity,
&self.velocity.read,
None,
None,
);
let bg_dye = self.bind_batched(
&self.ubos.splat_dye,
&self.ubos.batch_dye,
&self.dye.read,
None,
None,
);
let mut enc = self.encoder("fluid splat");
draw(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.splat_velocity,
&bg_velocity,
);
draw(
&mut enc,
&self.dye.write.view,
Load::Clear,
&self.pipes.splat_dye,
&bg_dye,
);
self.queue.submit([enc.finish()]);
self.velocity.swap();
self.dye.swap();
}
pub fn step(&mut self, dt: f32) {
let c = self.config;
let texel = self.velocity.texel();
let mut enc = self.encoder("fluid step");
let p = Params {
texel_size: texel,
..Default::default()
};
write(&self.queue, &self.ubos.curl, p);
let bg = self.bind(&self.ubos.curl, &self.velocity.read, None, None);
draw(
&mut enc,
&self.curl.view,
Load::Clear,
&self.pipes.curl,
&bg,
);
write(
&self.queue,
&self.ubos.vorticity,
Params {
texel_size: texel,
dt,
curl: c.curl,
..Default::default()
},
);
let bg = self.bind(
&self.ubos.vorticity,
&self.velocity.read,
Some(&self.curl),
None,
);
draw(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.vorticity,
&bg,
);
self.velocity.swap();
self.record_divergence(&mut enc);
write(
&self.queue,
&self.ubos.clear,
Params {
value: c.pressure,
..Default::default()
},
);
let bg = self.bind(&self.ubos.clear, &self.pressure.read, None, None);
draw(
&mut enc,
&self.pressure.write.view,
Load::Clear,
&self.pipes.clear,
&bg,
);
self.pressure.swap();
match c.pressure_solver {
PressureSolver::Jacobi => self.record_jacobi(&mut enc, c.pressure_iterations, 1.0),
PressureSolver::Multigrid => self.record_multigrid(&mut enc),
}
write(
&self.queue,
&self.ubos.gradient,
Params {
texel_size: texel,
value: c.gradient_scale,
..Default::default()
},
);
let bg = self.bind(
&self.ubos.gradient,
&self.pressure.read,
Some(&self.velocity.read),
None,
);
draw(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.gradient,
&bg,
);
self.velocity.swap();
self.record_advection(&mut enc, dt, texel, true);
self.record_advection(&mut enc, dt, texel, false);
self.queue.submit([enc.finish()]);
}
fn record_advection(
&mut self,
enc: &mut wgpu::CommandEncoder,
dt: f32,
texel: [f32; 2],
velocity_field: bool,
) {
let c = self.config;
let maccormack = c.advection == Advection::MacCormack;
let dissipation = if velocity_field {
c.velocity_dissipation
} else {
c.density_dissipation
};
let field_texel = if velocity_field {
self.velocity.texel()
} else {
self.dye.texel()
};
let (forward_ubo, correct_ubo) = if velocity_field {
(&self.ubos.advect_velocity, &self.ubos.correct_velocity)
} else {
(&self.ubos.advect_dye, &self.ubos.correct_dye)
};
let (forward_pipe, correct_pipe) = if velocity_field {
(&self.pipes.advect_velocity, &self.pipes.correct_velocity)
} else {
(&self.pipes.advect_dye, &self.pipes.correct_dye)
};
let params = Params {
texel_size: texel,
dye_texel_size: field_texel,
dt,
dissipation: if maccormack { 0.0 } else { dissipation },
..Default::default()
};
write(&self.queue, forward_ubo, params);
{
let (source, target) = if velocity_field {
(&self.velocity.read, &self.velocity.write)
} else {
(&self.dye.read, &self.dye.write)
};
let bg = self.bind(forward_ubo, &self.velocity.read, Some(source), None);
draw(enc, &target.view, Load::Clear, forward_pipe, &bg);
}
if !maccormack {
if velocity_field {
self.velocity.swap();
} else {
self.dye.swap();
}
return;
}
write(
&self.queue,
correct_ubo,
Params {
dissipation,
..params
},
);
if velocity_field {
let bg = self.bind_three(
correct_ubo,
&self.velocity.read,
&self.velocity.write,
&self.velocity.read,
);
draw(
enc,
&self.scratch_velocity.view,
Load::Clear,
correct_pipe,
&bg,
);
std::mem::swap(&mut self.velocity.read, &mut self.scratch_velocity);
} else {
let bg = self.bind_three(
correct_ubo,
&self.velocity.read,
&self.dye.write,
&self.dye.read,
);
draw(enc, &self.scratch_dye.view, Load::Clear, correct_pipe, &bg);
std::mem::swap(&mut self.dye.read, &mut self.scratch_dye);
}
}
fn record_jacobi(&mut self, enc: &mut wgpu::CommandEncoder, count: u32, weight: f32) {
write(
&self.queue,
&self.ubos.pressure,
Params {
texel_size: self.velocity.texel(),
value: weight,
..Default::default()
},
);
let bg_even = self.bind(
&self.ubos.pressure,
&self.pressure.read,
Some(&self.divergence),
None,
);
let bg_odd = self.bind(
&self.ubos.pressure,
&self.pressure.write,
Some(&self.divergence),
None,
);
for i in 0..count {
let (bg, target) = if i % 2 == 0 {
(&bg_even, &self.pressure.write.view)
} else {
(&bg_odd, &self.pressure.read.view)
};
draw(enc, target, Load::Clear, &self.pipes.pressure, bg);
}
if count % 2 == 1 {
self.pressure.swap();
}
}
fn record_multigrid(&mut self, enc: &mut wgpu::CommandEncoder) {
if self.mg.is_empty() {
self.record_jacobi(enc, self.config.pressure_iterations, 1.0);
return;
}
let nu = 2;
let coarse_sweeps = self.config.pressure_iterations.max(nu * 2);
for cycle in 0..self.config.multigrid_cycles.max(1) {
let _ = cycle;
self.record_smooth_top(enc, nu);
for level in 0..self.mg.len() {
self.record_residual(enc, level);
self.record_restrict(enc, level);
let _ = fullscreen::begin(enc, &self.mg[level].pressure.read.view, Load::Clear);
let sweeps = if level + 1 == self.mg.len() {
coarse_sweeps
} else {
nu
};
self.record_smooth_level(enc, level, sweeps);
}
for level in (0..self.mg.len()).rev() {
self.record_prolong(enc, level);
if level == 0 {
self.record_smooth_top(enc, nu);
} else {
self.record_smooth_level(enc, level - 1, nu);
}
}
}
}
fn record_smooth_top(&mut self, enc: &mut wgpu::CommandEncoder, sweeps: u32) {
self.record_jacobi(enc, sweeps, MG_WEIGHT);
}
fn record_smooth_level(&mut self, enc: &mut wgpu::CommandEncoder, level: usize, sweeps: u32) {
let l = &self.mg[level];
write(
&self.queue,
&l.ubo_smooth,
Params {
texel_size: l.pressure.texel(),
value: MG_WEIGHT,
..Default::default()
},
);
let bg_even = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
&l.ubo_smooth,
&self.ubos.batch_idle,
&l.pressure.read.view,
Some(&l.rhs.view),
None,
);
let bg_odd = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
&l.ubo_smooth,
&self.ubos.batch_idle,
&l.pressure.write.view,
Some(&l.rhs.view),
None,
);
for i in 0..sweeps {
let (bg, target) = if i % 2 == 0 {
(&bg_even, &l.pressure.write.view)
} else {
(&bg_odd, &l.pressure.read.view)
};
draw(enc, target, Load::Clear, &self.pipes.pressure, bg);
}
if sweeps % 2 == 1 {
self.mg[level].pressure.swap();
}
}
fn record_residual(&mut self, enc: &mut wgpu::CommandEncoder, level: usize) {
let (pressure, rhs, texel) = if level == 0 {
(&self.pressure.read, &self.divergence, self.pressure.texel())
} else {
let l = &self.mg[level - 1];
(&l.pressure.read, &l.rhs, l.pressure.texel())
};
let slot = &self.mg[level].ubo_residual;
write(
&self.queue,
slot,
Params {
texel_size: texel,
..Default::default()
},
);
let bg = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
slot,
&self.ubos.batch_idle,
&pressure.view,
Some(&rhs.view),
None,
);
let target = if level == 0 {
&self.residual
} else {
&self.mg[level - 1].residual
};
draw(enc, &target.view, Load::Clear, &self.pipes.residual, &bg);
}
fn record_restrict(&mut self, enc: &mut wgpu::CommandEncoder, level: usize) {
let (residual, fine_texel) = if level == 0 {
(&self.residual, self.pressure.texel())
} else {
let l = &self.mg[level - 1];
(&l.residual, l.pressure.texel())
};
let slot = &self.mg[level].ubo_restrict;
write(
&self.queue,
slot,
Params {
texel_size: fine_texel,
..Default::default()
},
);
let bg = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
slot,
&self.ubos.batch_idle,
&residual.view,
None,
None,
);
draw(
enc,
&self.mg[level].rhs.view,
Load::Clear,
&self.pipes.restrict,
&bg,
);
}
fn record_prolong(&mut self, enc: &mut wgpu::CommandEncoder, level: usize) {
let coarse = &self.mg[level].pressure.read;
let slot = &self.mg[level].ubo_prolong;
write(&self.queue, slot, Params::default());
let (fine_read, fine_write) = if level == 0 {
(&self.pressure.read, &self.pressure.write)
} else {
let l = &self.mg[level - 1];
(&l.pressure.read, &l.pressure.write)
};
let bg = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
slot,
&self.ubos.batch_idle,
&coarse.view,
Some(&fine_read.view),
None,
);
draw(enc, &fine_write.view, Load::Clear, &self.pipes.prolong, &bg);
if level == 0 {
self.pressure.swap();
} else {
self.mg[level - 1].pressure.swap();
}
}
fn record_divergence(&self, enc: &mut wgpu::CommandEncoder) {
write(
&self.queue,
&self.ubos.divergence,
Params {
texel_size: self.velocity.texel(),
..Default::default()
},
);
let bg = self.bind(&self.ubos.divergence, &self.velocity.read, None, None);
draw(
enc,
&self.divergence.view,
Load::Clear,
&self.pipes.divergence,
&bg,
);
}
pub fn render(&mut self, target: &wgpu::Texture) {
let view = target.create_view(&wgpu::TextureViewDescriptor::default());
self.render_into(fullscreen::Target::from_texture(target, &view), true);
}
pub fn render_capture(&mut self, target: &wgpu::Texture) {
let view = target.create_view(&wgpu::TextureViewDescriptor::default());
self.render_into(fullscreen::Target::from_texture(target, &view), false);
}
pub fn render_to_view(
&mut self,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
size: (u32, u32),
on_screen: bool,
) {
self.render_into(
fullscreen::Target {
view: target,
format,
width: size.0,
height: size.1,
},
on_screen,
)
}
pub fn render_into(&mut self, target: fullscreen::Target<'_>, on_screen: bool) {
let c = self.config;
let (format, size) = (target.format, target.size());
let target = target.view;
let mut enc = self.encoder("fluid render");
if c.bloom {
self.record_bloom(&mut enc);
}
if c.sunrays {
self.record_sunrays(&mut enc);
}
let encode = if format.is_srgb() { FLAG_ENCODE } else { 0 };
let mut flags = encode;
if c.shading {
flags |= FLAG_SHADING;
}
if c.bloom {
flags |= FLAG_BLOOM;
}
if c.sunrays {
flags |= FLAG_SUNRAYS;
}
let (w, h) = (size.0.max(1), size.1.max(1));
write(
&self.queue,
&self.ubos.display,
Params {
texel_size: [1.0 / w as f32, 1.0 / h as f32],
flags,
..Default::default()
},
);
write(
&self.queue,
&self.ubos.background,
Params {
color: [c.back_color[0], c.back_color[1], c.back_color[2], 1.0],
aspect_ratio: w as f32 / h as f32,
flags: encode,
..Default::default()
},
);
let bg_display = self.bind(
&self.ubos.display,
&self.dye.read,
Some(&self.bloom),
Some(&self.sunrays),
);
let bg_background = self.bind(&self.ubos.background, &self.dye.read, None, None);
write(
&self.queue,
&self.ubos.read_out,
Params {
value: self.rate.fps(),
radius: self.rate.scale_ms(),
curl: self.rate.target_ms(),
..Default::default()
},
);
let bg_read_out = {
let (device, queue) = (self.device.clone(), self.queue.clone());
let history = self
.history
.view(&device, &queue, self.rate.frames())
.clone();
passes::bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
&self.ubos.read_out,
&self.ubos.batch_idle,
&history,
None,
None,
)
};
let pipes = self.pipes.output(&self.device, format);
let display = if on_screen || !c.transparent {
&pipes.display_over
} else {
&pipes.display_replace
};
{
let mut pass = fullscreen::begin(&mut enc, target, Load::Clear);
if !c.transparent {
pass.set_pipeline(&pipes.color);
pass.set_bind_group(0, &bg_background, &[]);
pass.draw(0..3, 0..1);
} else if on_screen {
pass.set_pipeline(&pipes.checkerboard);
pass.set_bind_group(0, &bg_background, &[]);
pass.draw(0..3, 0..1);
}
pass.set_pipeline(display);
pass.set_bind_group(0, &bg_display, &[]);
pass.draw(0..3, 0..1);
if c.show_fps {
pass.set_pipeline(&pipes.overlay);
pass.set_bind_group(0, &bg_read_out, &[]);
pass.draw(0..3, 0..1);
}
}
self.queue.submit([enc.finish()]);
self.rate.tick();
}
fn record_bloom(&mut self, enc: &mut wgpu::CommandEncoder) {
if self.bloom_chain.len() < 2 {
return;
}
let c = self.config;
let knee = c.bloom_threshold * c.bloom_soft_knee + 0.0001;
write(
&self.queue,
&self.ubos.bloom_prefilter,
Params {
curve: [
c.bloom_threshold - knee,
knee * 2.0,
0.25 / knee,
c.bloom_threshold,
],
..Default::default()
},
);
let bg = self.bind(&self.ubos.bloom_prefilter, &self.dye.read, None, None);
draw(
enc,
&self.bloom.view,
Load::Clear,
&self.pipes.bloom_prefilter,
&bg,
);
let mut last = &self.bloom;
for (i, dest) in self.bloom_chain.iter().enumerate() {
let slot = &self.ubos.bloom_chain[i];
write(
&self.queue,
slot,
Params {
texel_size: last.texel(),
..Default::default()
},
);
let bg = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
slot,
&self.ubos.batch_idle,
&last.view,
None,
None,
);
draw(enc, &dest.view, Load::Clear, &self.pipes.bloom_blur, &bg);
last = dest;
}
let n = self.bloom_chain.len();
for i in (0..n - 1).rev() {
let base = &self.bloom_chain[i];
let slot = &self.ubos.bloom_chain[n + i];
write(
&self.queue,
slot,
Params {
texel_size: last.texel(),
..Default::default()
},
);
let bg = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
slot,
&self.ubos.batch_idle,
&last.view,
None,
None,
);
draw(enc, &base.view, Load::Keep, &self.pipes.bloom_blur_add, &bg);
last = base;
}
write(
&self.queue,
&self.ubos.bloom_final,
Params {
texel_size: last.texel(),
value: c.bloom_intensity,
..Default::default()
},
);
let bg = bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
&self.ubos.bloom_final,
&self.ubos.batch_idle,
&last.view,
None,
None,
);
draw(
enc,
&self.bloom.view,
Load::Clear,
&self.pipes.bloom_final,
&bg,
);
}
fn record_sunrays(&mut self, enc: &mut wgpu::CommandEncoder) {
write(&self.queue, &self.ubos.sunrays_mask, Params::default());
let bg = self.bind(&self.ubos.sunrays_mask, &self.dye.read, None, None);
draw(
enc,
&self.dye.write.view,
Load::Clear,
&self.pipes.sunrays_mask,
&bg,
);
write(
&self.queue,
&self.ubos.sunrays,
Params {
value: self.config.sunrays_weight,
..Default::default()
},
);
let bg = self.bind(&self.ubos.sunrays, &self.dye.write, None, None);
draw(
enc,
&self.sunrays.view,
Load::Clear,
&self.pipes.sunrays,
&bg,
);
let texel = self.sunrays.texel();
write(
&self.queue,
&self.ubos.blur_h,
Params {
texel_size: [texel[0], 0.0],
..Default::default()
},
);
let bg = self.bind(&self.ubos.blur_h, &self.sunrays, None, None);
draw(
enc,
&self.sunrays_temp.view,
Load::Clear,
&self.pipes.blur,
&bg,
);
write(
&self.queue,
&self.ubos.blur_v,
Params {
texel_size: [0.0, texel[1]],
..Default::default()
},
);
let bg = self.bind(&self.ubos.blur_v, &self.sunrays_temp, None, None);
draw(enc, &self.sunrays.view, Load::Clear, &self.pipes.blur, &bg);
}
fn encoder(&self, label: &str) -> wgpu::CommandEncoder {
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(label) })
}
#[cfg(not(target_arch = "wasm32"))]
pub fn capture_rgba(&mut self, width: u32, height: u32) -> Vec<u8> {
let (width, height) = (width.max(1), height.max(1));
let target = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("fluid capture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
self.render_capture(&target);
crate::renderer::readback::texture_bytes(&self.device, &self.queue, &target)
}
fn bind(
&self,
params: &wgpu::Buffer,
a: &Fbo,
b: Option<&Fbo>,
c: Option<&Fbo>,
) -> wgpu::BindGroup {
self.bind_batched(params, &self.ubos.batch_idle, a, b, c)
}
fn bind_three(&self, params: &wgpu::Buffer, a: &Fbo, b: &Fbo, c: &Fbo) -> wgpu::BindGroup {
self.bind_batched(params, &self.ubos.batch_idle, a, Some(b), Some(c))
}
fn bind_batched(
&self,
params: &wgpu::Buffer,
batch: &wgpu::Buffer,
a: &Fbo,
b: Option<&Fbo>,
c: Option<&Fbo>,
) -> wgpu::BindGroup {
bind(
&self.device,
&self.pipes.bgl,
&self.sampler,
params,
batch,
&a.view,
b.map(|f| &f.view),
c.map(|f| &f.view),
)
}
}
#[cfg(feature = "fluid")]
fn bloom_chain(
device: &wgpu::Device,
width: u32,
height: u32,
iterations: u32,
format: wgpu::TextureFormat,
) -> Vec<Fbo> {
let mut chain = Vec::new();
for i in 0..iterations {
let w = width >> (i + 1);
let h = height >> (i + 1);
if w < 2 || h < 2 {
break;
}
chain.push(Fbo::new(device, "fluid bloom level", w, h, format));
}
chain
}
#[cfg(feature = "fluid")]
fn write(queue: &wgpu::Queue, buffer: &wgpu::Buffer, params: Params) {
queue.write_buffer(buffer, 0, bytemuck::bytes_of(¶ms));
}
#[cfg(all(test, feature = "fluid"))]
mod tests;