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
use rust_gpu_bridge::prelude::{Vec2, Vec2Swizzles};

use crate::signed_distance_field::{attributes::distance::Distance, SignedDistanceField};

// Inigo Quilez' quadratic circle
// Appears to be a superellipse / lame curve with n = 1.0 / 0.75
// Can be generalized to 3D as a superellipsoid
//
// Desmos decomposition: https://www.desmos.com/calculator/i9cgthn0ls
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Squircle;

impl SignedDistanceField<Vec2, Distance> for Squircle {
    fn evaluate(&self, mut p: Vec2) -> Distance {
        // Axial reflection
        p = p.abs();

        // Cheap diagonal mirror
        if p.y > p.x {
            p = p.yx()
        }

        // Diagonal X maximum
        let a = p.x - p.y;

        // Diagonal Y minimum
        let b = p.x + p.y;

        // Diagonal Y maximum
        let c = (2.0 * b - 1.0) / 3.0;

        // Semicircle at (0.5, 0.5)
        let h = a * a + c * c * c;

        let t = if h >= 0.0 {
            // Appears identical to h in graph plot, maybe field related
            let h = h.sqrt();
            // Uneven circular curve
            (h - a).signum() * (h - a).abs().powf(1.0 / 3.0) - (h + a).powf(1.0 / 3.0)
        } else {
            // Negative Y minimum
            let z = (-c).sqrt();
            // Uneven tangent curve
            let v = (a / (c * z)).acos() / 3.0;
            // Uneven tangent curve, repeating w/different frequency
            -z * (v.cos() + v.sin() * 1.732050808)
        } * 0.5;

        // Bounded quadradic curve
        let w = Vec2::new(-t, t) + 0.75 - t * t - p;

        // Quadratic curve sign
        let s = (a * a * 0.5 + b - 1.5).signum();

        // Final curve w / sign
        (w.length() * s).into()
    }
}

#[cfg(test)]
pub mod test {
    use rust_gpu_bridge::prelude::Vec2;

    use crate::prelude::BoundChecker;

    use super::Squircle;

    #[test]
    pub fn test_squircle() {
        assert!(BoundChecker::<Vec2, Squircle>::default().is_field())
    }
}