1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use nalgebra::{Point2, RealField, Scalar, Vector2, U2};

use crate::{AxisAlignedBoundingBox2d, BoundedGeometry};
use numeric_literals::replace_float_literals;

pub trait SignedDistanceFunction2d<T>
where
    T: Scalar,
{
    fn eval(&self, x: &Point2<T>) -> T;
    fn gradient(&self, x: &Point2<T>) -> Option<Vector2<T>>;

    fn union<Other>(self, other: Other) -> SdfUnion<Self, Other>
    where
        Self: Sized,
        Other: Sized + SignedDistanceFunction2d<T>,
    {
        SdfUnion {
            left: self,
            right: other,
        }
    }
}

pub trait BoundedSdf<T>: SignedDistanceFunction2d<T> + BoundedGeometry<T, Dimension = U2>
where
    T: Scalar,
{
}

impl<X, T> BoundedSdf<T> for X
where
    T: Scalar,
    X: SignedDistanceFunction2d<T> + BoundedGeometry<T, Dimension = U2>,
{
}

#[derive(Copy, Clone, Debug)]
pub struct SdfCircle<T>
where
    T: Scalar,
{
    pub radius: T,
    pub center: Vector2<T>,
}

#[derive(Copy, Clone, Debug)]
pub struct SdfUnion<Left, Right> {
    pub left: Left,
    pub right: Right,
}

#[derive(Copy, Clone, Debug)]
pub struct SdfAxisAlignedBox<T>
where
    T: Scalar,
{
    pub aabb: AxisAlignedBoundingBox2d<T>,
}

impl<T> BoundedGeometry<T> for SdfCircle<T>
where
    T: RealField,
{
    type Dimension = U2;

    fn bounding_box(&self) -> AxisAlignedBoundingBox2d<T> {
        let eps = self.radius * T::from_f64(0.01).unwrap();
        AxisAlignedBoundingBox2d::new(
            self.center - Vector2::repeat(T::one()) * (self.radius + eps),
            self.center + Vector2::repeat(T::one()) * (self.radius + eps),
        )
    }
}

impl<T> SignedDistanceFunction2d<T> for SdfCircle<T>
where
    T: RealField,
{
    fn eval(&self, x: &Point2<T>) -> T {
        let y = x - self.center;
        y.coords.norm() - self.radius
    }

    fn gradient(&self, x: &Point2<T>) -> Option<Vector2<T>> {
        let y = x - self.center;
        let y_norm = y.coords.norm();

        if y_norm == T::zero() {
            None
        } else {
            Some(y.coords / y_norm)
        }
    }
}

impl<T, Left, Right> BoundedGeometry<T> for SdfUnion<Left, Right>
where
    T: RealField,
    Left: BoundedGeometry<T, Dimension = U2>,
    Right: BoundedGeometry<T, Dimension = U2>,
{
    type Dimension = U2;

    fn bounding_box(&self) -> AxisAlignedBoundingBox2d<T> {
        self.left.bounding_box().enclose(&self.right.bounding_box())
    }
}

impl<T, Left, Right> SignedDistanceFunction2d<T> for SdfUnion<Left, Right>
where
    T: RealField,
    Left: SignedDistanceFunction2d<T>,
    Right: SignedDistanceFunction2d<T>,
{
    fn eval(&self, x: &Point2<T>) -> T {
        self.left.eval(x).min(self.right.eval(x))
    }

    fn gradient(&self, x: &Point2<T>) -> Option<Vector2<T>> {
        // TODO: Is this actually correct? It might give funky results if exactly
        // at points where either SDF is non-differentiable
        if self.left.eval(x) < self.right.eval(x) {
            self.left.gradient(x)
        } else {
            self.right.gradient(x)
        }
    }
}

impl<T> BoundedGeometry<T> for SdfAxisAlignedBox<T>
where
    T: RealField,
{
    type Dimension = U2;

    fn bounding_box(&self) -> AxisAlignedBoundingBox2d<T> {
        self.aabb
    }
}

impl<T> SignedDistanceFunction2d<T> for SdfAxisAlignedBox<T>
where
    T: RealField,
{
    #[replace_float_literals(T::from_f64(literal).unwrap())]
    fn eval(&self, x: &Point2<T>) -> T {
        let b = self.aabb.extents() / 2.0;
        let p = x - self.aabb.center();
        let d = p.abs() - b;

        // TODO: Use d.max() when fixed. See https://github.com/rustsim/nalgebra/issues/620
        d.sup(&Vector2::zeros()).norm() + T::min(T::zero(), d[d.imax()])
    }

    #[replace_float_literals(T::from_f64(literal).expect("Literal must fit in T"))]
    fn gradient(&self, x: &Point2<T>) -> Option<Vector2<T>> {
        // TODO: Replace finite differences with "proper" gradient
        // Note: arbitrary "step"/resolution h
        let h = 1e-4;
        let mut gradient = Vector2::zeros();
        for i in 0..2 {
            let mut dx = Vector2::zeros();
            dx[i] = h;
            gradient[i] = (self.eval(&(x + dx)) - self.eval(&(x - dx))) / (2.0 * h)
        }
        gradient.normalize_mut();
        Some(gradient)
    }
}