use euclid::default::Point2D;
use rapier2d::prelude::*;
use crate::{Basin, Fluid, FluidContact, FluidParams, NODE_BODY_RADIUS, NodeCollider, Simulation};
const FLUID_REACTION: f32 = 0.25;
impl Simulation {
pub fn load_fluid(
&mut self,
params: FluidParams,
basin: Basin,
spawn_origin: Point2D<f32>,
cols: usize,
rows: usize,
spacing: f32,
) {
let mut fluid = Fluid::new(params, basin);
fluid.spawn_block(spawn_origin, cols, rows, spacing);
self.fluid = Some(fluid);
}
pub fn clear_fluid(&mut self) {
self.fluid = None;
}
pub fn has_fluid(&self) -> bool {
self.fluid.is_some()
}
pub fn fluid_particles(&self) -> impl Iterator<Item = Point2D<f32>> + '_ {
self.fluid.iter().flat_map(|f| f.positions())
}
pub(crate) fn couple_fluid_to_bodies(&mut self) {
if self.fluid.is_none() {
return;
}
let mut handles: Vec<RigidBodyHandle> = Vec::new();
let mut contacts: Vec<FluidContact> = Vec::new();
for (handle, collider) in self.scene_bodies.values() {
if let Some(body) = self.bodies.get(*handle) {
let t = body.translation();
let center = Point2D::new(t.x, t.y);
let contact = match collider {
NodeCollider::Ball { radius } => FluidContact::circle(center, *radius),
NodeCollider::Square { half } | NodeCollider::RoundedSquare { half, .. } => {
FluidContact::obb(center, (*half, *half), body.rotation().angle())
}
NodeCollider::Hull { fallback, .. } => FluidContact::circle(center, *fallback),
};
handles.push(*handle);
contacts.push(contact);
}
}
if self.nodes_tangible {
for handle in self.bodies_by_node.values() {
if let Some(body) = self.bodies.get(*handle) {
let t = body.translation();
handles.push(*handle);
contacts.push(FluidContact::circle(
Point2D::new(t.x, t.y),
NODE_BODY_RADIUS,
));
}
}
}
let reactions = self.fluid.as_mut().unwrap().resolve_contacts(&contacts);
for (handle, reaction) in handles.iter().zip(reactions) {
if let Some(body) = self.bodies.get_mut(*handle) {
if body.is_dynamic() {
body.apply_impulse(Vector::new(reaction.x, reaction.y) * FLUID_REACTION, true);
}
}
}
}
}