use super::PressureSolver;
use crate::cameras::Camera;
use crate::Vector3;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FluidConfig3d {
pub resolution: u32,
pub dye_resolution: u32,
pub density_dissipation: f32,
pub velocity_dissipation: f32,
pub pressure: f32,
pub pressure_iterations: u32,
pub time_scale: f32,
pub pressure_solver: PressureSolver,
pub multigrid_cycles: u32,
pub multigrid_smooth: u32,
pub multigrid_coarsest: u32,
pub cache_bindings: bool,
pub show_fps: bool,
pub temporal_samples: u32,
pub temporal_clip: f32,
pub empty_space_skip: bool,
pub compact_dye: bool,
pub curl: f32,
pub gradient_scale: f32,
pub splat_radius: f32,
pub splat_force: f32,
pub buoyancy: f32,
pub buoyancy_axis: [f32; 3],
pub march_steps: u32,
pub absorption: f32,
pub emission: f32,
pub exposure: f32,
pub background: [f32; 3],
pub transparent: bool,
pub bounds_min: [f32; 3],
pub bounds_max: [f32; 3],
pub seed: u64,
}
#[derive(Clone, Copy, Debug)]
pub struct FluidQuality3d {
pub name: &'static str,
pub resolution: u32,
pub dye_resolution: u32,
pub pressure_iterations: u32,
pub march_steps: u32,
}
pub const QUALITY_LEVELS_3D: &[FluidQuality3d] = &[
FluidQuality3d {
name: "low",
resolution: 24,
dye_resolution: 48,
pressure_iterations: 16,
march_steps: 48,
},
FluidQuality3d {
name: "medium",
resolution: 40,
dye_resolution: 80,
pressure_iterations: 18,
march_steps: 64,
},
FluidQuality3d {
name: "high",
resolution: 64,
dye_resolution: 128,
pressure_iterations: 20,
march_steps: 96,
},
FluidQuality3d {
name: "ultra",
resolution: 96,
dye_resolution: 192,
pressure_iterations: 24,
march_steps: 128,
},
FluidQuality3d {
name: "extreme",
resolution: 128,
dye_resolution: 256,
pressure_iterations: 28,
march_steps: 192,
},
];
pub fn quality3d(name: &str) -> Option<&'static FluidQuality3d> {
QUALITY_LEVELS_3D.iter().find(|q| q.name == name)
}
pub fn quality3d_names() -> impl Iterator<Item = &'static str> {
QUALITY_LEVELS_3D.iter().map(|q| q.name)
}
impl FluidConfig3d {
pub fn with_quality(mut self, quality: &FluidQuality3d) -> Self {
self.resolution = quality.resolution;
self.dye_resolution = quality.dye_resolution;
self.pressure_iterations = quality.pressure_iterations;
self.march_steps = quality.march_steps;
self
}
}
impl Default for FluidConfig3d {
fn default() -> Self {
Self {
resolution: 64,
dye_resolution: 128,
density_dissipation: 0.4,
velocity_dissipation: 0.2,
pressure: 1.0,
pressure_iterations: 20,
time_scale: 1.0,
pressure_solver: PressureSolver::Multigrid,
multigrid_cycles: 1,
multigrid_smooth: 2,
multigrid_coarsest: 4,
cache_bindings: true,
show_fps: false,
temporal_samples: 1,
temporal_clip: 0.5,
empty_space_skip: true,
compact_dye: false,
curl: 12.0,
gradient_scale: 1.0,
splat_radius: 0.6,
splat_force: 6.0,
buoyancy: 0.0,
buoyancy_axis: [0.0, 1.0, 0.0],
march_steps: 96,
absorption: 28.0,
emission: 1.2,
exposure: 1.0,
background: [0.015, 0.015, 0.025],
transparent: false,
bounds_min: [-0.5, -0.5, -0.5],
bounds_max: [0.5, 0.5, 0.5],
seed: 0x5EED_F101_D1CE,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Atlas {
pub grid: u32,
pub tiles: (u32, u32),
}
impl Atlas {
pub fn new(grid: u32) -> Self {
let grid = grid.max(2);
let across = (grid as f32).sqrt().ceil() as u32;
let down = grid.div_ceil(across);
Self {
grid,
tiles: (across, down),
}
}
pub fn size(&self) -> (u32, u32) {
(self.grid * self.tiles.0, self.grid * self.tiles.1)
}
pub fn largest_within(mut grid: u32, max: u32) -> Self {
loop {
let a = Self::new(grid);
let (w, h) = a.size();
if (w <= max && h <= max) || grid <= 8 {
return a;
}
grid /= 2;
}
}
}
pub(crate) const MG_COARSEST_3D: u32 = 4;
pub(crate) fn memory_bytes(resolution: u32, dye_resolution: u32, bytes: [u64; 3]) -> u64 {
let texels = |grid: u32| {
let a = Atlas::new(grid);
let (w, h) = a.size();
w as u64 * h as u64
};
let [vec3, dye_fmt, scalar] = bytes;
let sim = texels(resolution.max(2));
let dye = texels(dye_resolution.max(2));
let mut total = sim * (2 * vec3 + 2 * scalar + scalar + vec3 + scalar);
total += dye * 2 * dye_fmt;
let mut n = resolution.max(2);
let mut levels = 0;
while n / 2 >= MG_COARSEST_3D && levels < 6 {
n /= 2;
levels += 1;
total += texels(n) * 4 * scalar;
}
total += (texels(dye_resolution / 2) + texels(dye_resolution / 4)) * scalar;
total
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct GridUniform {
pub(crate) size: [f32; 4],
pub(crate) tiles: [f32; 4],
}
impl From<Atlas> for GridUniform {
fn from(a: Atlas) -> Self {
let n = a.grid as f32;
let (tx, ty) = (a.tiles.0 as f32, a.tiles.1 as f32);
Self {
size: [n, n, n, 1.0 / n],
tiles: [tx, ty, 1.0 / tx, 1.0 / ty],
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct Vol {
pub(crate) out_grid: GridUniform,
pub(crate) a_grid: GridUniform,
pub(crate) b_grid: GridUniform,
pub(crate) texel: [f32; 4],
pub(crate) point: [f32; 4],
pub(crate) color: [f32; 4],
pub(crate) params: [f32; 4],
pub(crate) bounds_min: [f32; 4],
pub(crate) bounds_max: [f32; 4],
pub(crate) march: [f32; 4],
pub(crate) background: [f32; 4],
pub(crate) cam_pos: [f32; 4],
pub(crate) inv_view_proj: [f32; 16],
pub(crate) prev_view_proj: [f32; 16],
}
pub(crate) fn impulse(
config: &FluidConfig3d,
sim_grid: u32,
camera: &dyn Camera,
uv: [f32; 2],
drag: [f32; 2],
strength: f32,
) -> Option<([f32; 3], [f32; 3])> {
let inv = camera
.projection_matrix()
.multiply(&camera.view_matrix())
.invert();
let ray = |uv: [f32; 2]| -> (Vector3, Vector3) {
let ndc =
|z: f32| Vector3::new(uv[0] * 2.0 - 1.0, 1.0 - uv[1] * 2.0, z).apply_matrix4(&inv);
let near = ndc(0.0);
let far = ndc(1.0);
(near, (far - near).normalize())
};
let c = *config;
let centre = Vector3::new(
0.5 * (c.bounds_min[0] + c.bounds_max[0]),
0.5 * (c.bounds_min[1] + c.bounds_max[1]),
0.5 * (c.bounds_min[2] + c.bounds_max[2]),
);
let eye = camera.position();
let normal = (centre - eye).normalize();
let on_plane = |uv: [f32; 2]| -> Option<Vector3> {
let (origin, dir) = ray(uv);
let denom = dir.dot(normal);
if denom.abs() < 1e-6 {
return None;
}
let t = (centre - origin).dot(normal) / denom;
if t <= 0.0 {
return None;
}
Some(origin + dir * t)
};
let hit = on_plane(uv)?;
let size = Vector3::new(
c.bounds_max[0] - c.bounds_min[0],
c.bounds_max[1] - c.bounds_min[1],
c.bounds_max[2] - c.bounds_min[2],
);
let at = [
(hit.x - c.bounds_min[0]) / size.x,
(hit.y - c.bounds_min[1]) / size.y,
(hit.z - c.bounds_min[2]) / size.z,
];
if at.iter().any(|v| !(0.0..=1.0).contains(v)) {
return None;
}
let moved = on_plane([uv[0] + drag[0], uv[1] + drag[1]])
.map(|to| to - hit)
.unwrap_or(Vector3::ZERO);
let scale = strength * sim_grid as f32;
Some((
at,
[
moved.x / size.x * scale,
moved.y / size.y * scale,
moved.z / size.z * scale,
],
))
}
pub(crate) fn random_splats(
rng: &mut super::Rng,
count: u32,
) -> Vec<([f32; 3], [f32; 3], [f32; 3])> {
let mut batch = Vec::with_capacity(count as usize);
for _ in 0..count {
let hue = rng.next_f32();
let c = super::hsv_to_rgb(hue, 1.0, 1.0);
let at = [
0.2 + 0.6 * rng.next_f32(),
0.2 + 0.6 * rng.next_f32(),
0.2 + 0.6 * rng.next_f32(),
];
let z = 2.0 * rng.next_f32() - 1.0;
let theta = std::f32::consts::TAU * rng.next_f32();
let r = (1.0 - z * z).max(0.0).sqrt();
let speed = 120.0 + 180.0 * rng.next_f32();
let v = [r * theta.cos() * speed, z * speed, r * theta.sin() * speed];
batch.push((at, v, [c[0] * 1.5, c[1] * 1.5, c[2] * 1.5]));
}
batch
}
pub(crate) fn within_bytes(budget: u64, ratio: u32, bytes: [u64; 3]) -> (u32, u32) {
let ratio = ratio.max(1);
let mut best = (8u32, 8 * ratio);
for solver in (8..=512).step_by(8) {
let dye = solver * ratio;
if memory_bytes(solver, dye, bytes) > budget {
break;
}
best = (solver, dye);
}
best
}