use crate::NodeKey;
use numen::{CouplingResponse, FieldDefinition};
use quint::{FieldRegistry, ScalarField, VectorField, eval_scalar, eval_vector, grad_scalar};
use rapier2d::prelude::*;
use crate::{Force, ForceContext};
pub struct CouplingForce {
response: CouplingResponse,
strength: f32,
targets: Vec<NodeKey>,
field: FieldDefinition,
registry: FieldRegistry,
}
impl CouplingForce {
pub fn new(
response: CouplingResponse,
strength: f32,
targets: impl IntoIterator<Item = NodeKey>,
field: FieldDefinition,
) -> Self {
Self {
response,
strength,
targets: targets.into_iter().collect(),
field,
registry: FieldRegistry::new(),
}
}
pub fn with_registry(mut self, registry: FieldRegistry) -> Self {
self.registry = registry;
self
}
pub fn target_count(&self) -> usize {
self.targets.len()
}
fn scalar(&self) -> Option<&ScalarField> {
match &self.field {
FieldDefinition::Scalar(s) => Some(s),
FieldDefinition::Vector(_) => None,
}
}
fn vector(&self) -> Option<&VectorField> {
match &self.field {
FieldDefinition::Vector(v) => Some(v),
FieldDefinition::Scalar(_) => None,
}
}
}
impl Force for CouplingForce {
fn apply(&self, ctx: &mut ForceContext<'_>, dt: f32) {
let mut samples: Vec<(RigidBodyHandle, f32, f32)> = Vec::with_capacity(self.targets.len());
for &node in &self.targets {
if let Some(&handle) = ctx.bodies_by_node.get(&node) {
if let Some(body) = ctx.bodies.get(handle) {
let t = body.translation();
samples.push((handle, t.x, t.y));
}
}
}
match &self.response {
CouplingResponse::AttractToMin | CouplingResponse::RepelFromMax => {
let Some(scalar) = self.scalar() else { return };
let sign = if matches!(self.response, CouplingResponse::AttractToMin) {
-1.0
} else {
1.0
};
for (handle, x, y) in samples {
let (gx, gy) = grad_scalar(scalar, &self.registry, x, y, 0.0);
if let Some(body) = ctx.bodies.get_mut(handle) {
let f = Vector::new(sign * gx * self.strength, sign * gy * self.strength);
body.add_force(f, true);
}
}
}
CouplingResponse::ContainmentWall => {
let Some(scalar) = self.scalar() else { return };
for (handle, x, y) in samples {
let depth = eval_scalar(scalar, &self.registry, x, y, 0.0);
if depth > 0.0 {
let (gx, gy) = grad_scalar(scalar, &self.registry, x, y, 0.0);
if let Some(body) = ctx.bodies.get_mut(handle) {
let f = Vector::new(gx, gy) * (self.strength * depth);
body.add_force(f, true);
}
}
}
}
CouplingResponse::DampenInside { factor } => {
let Some(scalar) = self.scalar() else { return };
for (handle, x, y) in samples {
if eval_scalar(scalar, &self.registry, x, y, 0.0) > 0.0 {
if let Some(body) = ctx.bodies.get_mut(handle) {
let v = body.linvel();
body.set_linvel(v * *factor, true);
}
}
}
}
CouplingResponse::AlignVelocity => {
let Some(field) = self.vector() else { return };
for (handle, x, y) in samples {
let (vx, vy) = eval_vector(field, &self.registry, x, y, 0.0);
if let Some(body) = ctx.bodies.get_mut(handle) {
body.set_linvel(Vector::new(vx * self.strength, vy * self.strength), true);
}
}
}
CouplingResponse::FlowAdvect => {
let Some(field) = self.vector() else { return };
for (handle, x, y) in samples {
let (vx, vy) = eval_vector(field, &self.registry, x, y, 0.0);
if let Some(body) = ctx.bodies.get_mut(handle) {
let t = body.translation();
let next = t + Vector::new(vx, vy) * (self.strength * dt);
body.set_translation(next, true);
}
}
}
CouplingResponse::Open { .. } => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Boundary, NodeKey, Simulation};
use euclid::default::Point2D;
#[derive(Default)]
struct Nodes {
list: Vec<(NodeKey, Point2D<f32>)>,
}
impl Nodes {
fn at(&mut self, x: f32, y: f32) -> NodeKey {
let key = NodeKey::new(self.list.len());
self.list.push((key, Point2D::new(x, y)));
key
}
fn sync(&self, sim: &mut Simulation) {
sim.sync_nodes(self.list.iter().copied());
}
}
fn radius(sim: &Simulation, k: NodeKey) -> f32 {
sim.position_of(k).unwrap().to_vector().length()
}
fn paraboloid() -> ScalarField {
ScalarField::Scale(
Box::new(ScalarField::Add(
Box::new(ScalarField::Mul(
Box::new(ScalarField::CoordX),
Box::new(ScalarField::CoordX),
)),
Box::new(ScalarField::Mul(
Box::new(ScalarField::CoordY),
Box::new(ScalarField::CoordY),
)),
)),
0.5,
)
}
#[test]
fn attract_to_min_centers_like_boundary() {
let mut g = Nodes::default();
let a = g.at(500.0, -300.0);
let mut boundary_sim = Simulation::new();
g.sync(&mut boundary_sim);
boundary_sim.add_force(Boundary { strength: 1.5 });
let mut coupling_sim = Simulation::new();
g.sync(&mut coupling_sim);
coupling_sim.add_force(CouplingForce::new(
CouplingResponse::AttractToMin,
1.5,
[a],
FieldDefinition::Scalar(paraboloid()),
));
for _ in 0..120 {
boundary_sim.tick(1.0 / 60.0);
coupling_sim.tick(1.0 / 60.0);
}
let pb = boundary_sim.position_of(a).unwrap();
let pc = coupling_sim.position_of(a).unwrap();
assert!(
radius(&coupling_sim, a) < 500.0,
"coupling should pull inward"
);
assert!(
(pb - pc).length() < 5.0,
"coupling diverged from Boundary: {pb:?} vs {pc:?}"
);
}
#[test]
fn open_response_applies_no_force() {
let mut g = Nodes::default();
let a = g.at(300.0, 0.0);
let mut sim = Simulation::new();
g.sync(&mut sim);
sim.add_force(CouplingForce::new(
CouplingResponse::open(
"https://mere.computer/ns/coupling#visual/highlight".to_string(),
),
1.0,
[a],
FieldDefinition::Scalar(paraboloid()),
));
let p0 = sim.position_of(a).unwrap();
for _ in 0..120 {
sim.tick(1.0 / 60.0);
}
assert!(
(sim.position_of(a).unwrap() - p0).length() < 1.0e-3,
"an open-tail response must apply no force"
);
}
}