Skip to main content

xpict_core/
catmull.rs

1//! Centripetal Catmull–Rom → cubic Bézier SVG `d`.
2//!
3//! Shared by region hulls (closed) and scheme arrows (open). Lives outside
4//! `doc` so [`crate::arrows`] can paint shafts without a module cycle.
5
6/// Centripetal Catmull–Rom (α = 0.5) closed loop as cubic Bézier SVG `d`.
7pub fn centripetal_catmull_rom_closed_path(pts: &[(f64, f64)]) -> String {
8    let pts = dedupe_poly_pts(pts);
9    let n = pts.len();
10    if n < 3 {
11        return String::new();
12    }
13    const ALPHA: f64 = 0.5;
14    let mut d = format!("M {:.2} {:.2}", pts[0].0, pts[0].1);
15    for i in 0..n {
16        let p0 = pts[(i + n - 1) % n];
17        let p1 = pts[i];
18        let p2 = pts[(i + 1) % n];
19        let p3 = pts[(i + 2) % n];
20        let (c1, c2) = catmull_rom_segment_cubic(p0, p1, p2, p3, ALPHA);
21        d.push_str(&format!(
22            " C {:.2} {:.2} {:.2} {:.2} {:.2} {:.2}",
23            c1.0, c1.1, c2.0, c2.1, p2.0, p2.1
24        ));
25    }
26    d.push_str(" Z");
27    d
28}
29
30/// Open centripetal Catmull–Rom (α = 0.5) as cubic Bézier SVG `d`.
31pub fn centripetal_catmull_rom_open_path(pts: &[(f64, f64)]) -> String {
32    let pts = dedupe_poly_pts_open(pts);
33    if pts.len() < 2 {
34        return String::new();
35    }
36    if pts.len() == 2 {
37        return format!(
38            "M {:.2} {:.2} L {:.2} {:.2}",
39            pts[0].0, pts[0].1, pts[1].0, pts[1].1
40        );
41    }
42    let mut d = format!("M {:.2} {:.2}", pts[0].0, pts[0].1);
43    for_open_cubics(&pts, |_p1, c1, c2, p2| {
44        d.push_str(&format!(
45            " C {:.2} {:.2} {:.2} {:.2} {:.2} {:.2}",
46            c1.0, c1.1, c2.0, c2.1, p2.0, p2.1
47        ));
48    });
49    d
50}
51
52/// Last interpolating vertex and unit last-chord of the open controls.
53pub fn open_catmull_end_frame(pts: &[(f64, f64)]) -> ((f64, f64), (f64, f64)) {
54    let pts = dedupe_poly_pts_open(pts);
55    match pts.as_slice() {
56        [] => ((0.0, 0.0), (1.0, 0.0)),
57        [p] => (*p, (1.0, 0.0)),
58        rest => {
59            let tip = *rest.last().unwrap();
60            let prev = rest[rest.len() - 2];
61            let l = (tip.0 - prev.0).hypot(tip.1 - prev.1).max(1e-9);
62            (tip, ((tip.0 - prev.0) / l, (tip.1 - prev.1) / l))
63        }
64    }
65}
66
67/// Shaft + arrow from the same controls: tip is the last vertex, base is that
68/// point pulled back along the last chord. The shaft interpolates `base`.
69///
70/// Head and shaft share those two points. No SVG `d` is consulted.
71pub fn open_catmull_with_arrow(
72    pts: &[(f64, f64)],
73    head: f64,
74) -> (String, (f64, f64), (f64, f64), (f64, f64)) {
75    let mut shaft = dedupe_poly_pts_open(pts);
76    if shaft.len() < 2 {
77        let tip = shaft.first().copied().unwrap_or((0.0, 0.0));
78        return (String::new(), tip, tip, (1.0, 0.0));
79    }
80    let (tip, (ux, uy)) = open_catmull_end_frame(&shaft);
81    let prev = shaft[shaft.len() - 2];
82    let chord = (tip.0 - prev.0).hypot(tip.1 - prev.1).max(1e-9);
83    let h = head.max(0.0).min(chord * 0.9);
84    let base = (tip.0 - ux * h, tip.1 - uy * h);
85    let last = shaft.len() - 1;
86    shaft[last] = base;
87    (
88        centripetal_catmull_rom_open_path(&shaft),
89        tip,
90        base,
91        (ux, uy),
92    )
93}
94
95/// Dense polyline along the open Catmull–Rom (same cubics as the SVG shaft).
96pub fn sample_open_catmull(pts: &[(f64, f64)], n_per_seg: usize) -> Vec<(f64, f64)> {
97    let pts = dedupe_poly_pts_open(pts);
98    if pts.len() <= 2 {
99        return pts;
100    }
101    let n_per = n_per_seg.max(2);
102    let mut out = vec![pts[0]];
103    for_open_cubics(&pts, |p1, c1, c2, p2| {
104        for k in 1..=n_per {
105            let t = k as f64 / n_per as f64;
106            out.push(bezier_cubic(p1, c1, c2, p2, t));
107        }
108    });
109    out
110}
111
112fn for_open_cubics(
113    pts: &[(f64, f64)],
114    mut each: impl FnMut((f64, f64), (f64, f64), (f64, f64), (f64, f64)),
115) {
116    let n = pts.len();
117    const ALPHA: f64 = 0.5;
118    for i in 0..n - 1 {
119        // Phantom neighbors so the end tangents follow the last chord. Duplicating
120        // the endpoint (p3 = p2) made the last cubic degenerate and left arrow
121        // heads sitting off the painted shaft.
122        let p0 = if i == 0 {
123            (2.0 * pts[0].0 - pts[1].0, 2.0 * pts[0].1 - pts[1].1)
124        } else {
125            pts[i - 1]
126        };
127        let p1 = pts[i];
128        let p2 = pts[i + 1];
129        let p3 = if i + 2 < n {
130            pts[i + 2]
131        } else {
132            (
133                2.0 * pts[n - 1].0 - pts[n - 2].0,
134                2.0 * pts[n - 1].1 - pts[n - 2].1,
135            )
136        };
137        let (c1, c2) = catmull_rom_segment_cubic(p0, p1, p2, p3, ALPHA);
138        each(p1, c1, c2, p2);
139    }
140}
141
142fn bezier_cubic(
143    p0: (f64, f64),
144    c1: (f64, f64),
145    c2: (f64, f64),
146    p3: (f64, f64),
147    t: f64,
148) -> (f64, f64) {
149    let u = 1.0 - t;
150    let uu = u * u;
151    let tt = t * t;
152    (
153        uu * u * p0.0 + 3.0 * uu * t * c1.0 + 3.0 * u * tt * c2.0 + tt * t * p3.0,
154        uu * u * p0.1 + 3.0 * uu * t * c1.1 + 3.0 * u * tt * c2.1 + tt * t * p3.1,
155    )
156}
157
158fn dedupe_poly_pts_open(pts: &[(f64, f64)]) -> Vec<(f64, f64)> {
159    let mut out: Vec<(f64, f64)> = Vec::with_capacity(pts.len());
160    for &p in pts {
161        if out
162            .last()
163            .is_none_or(|&q| (q.0 - p.0).hypot(q.1 - p.1) > 1e-6)
164        {
165            out.push(p);
166        }
167    }
168    out
169}
170
171fn dedupe_poly_pts(pts: &[(f64, f64)]) -> Vec<(f64, f64)> {
172    let mut out = dedupe_poly_pts_open(pts);
173    if out.len() >= 2 {
174        let a = out[0];
175        let b = *out.last().unwrap();
176        if (a.0 - b.0).hypot(a.1 - b.1) <= 1e-6 {
177            out.pop();
178        }
179    }
180    out
181}
182
183fn knot_span(a: (f64, f64), b: (f64, f64), alpha: f64) -> f64 {
184    (a.0 - b.0).hypot(a.1 - b.1).powf(alpha).max(1e-9)
185}
186
187/// Non-uniform CR tangent at `p` given neighbors `pm`, `pp` (Yuksel).
188fn catmull_rom_tangent(pm: (f64, f64), p: (f64, f64), pp: (f64, f64), alpha: f64) -> (f64, f64) {
189    let d0 = knot_span(pm, p, alpha);
190    let d1 = knot_span(p, pp, alpha);
191    (
192        (p.0 - pm.0) / d0 - (pp.0 - pm.0) / (d0 + d1) + (pp.0 - p.0) / d1,
193        (p.1 - pm.1) / d0 - (pp.1 - pm.1) / (d0 + d1) + (pp.1 - p.1) / d1,
194    )
195}
196
197/// Cubic Bézier controls for the CR segment from `p1` → `p2`.
198fn catmull_rom_segment_cubic(
199    p0: (f64, f64),
200    p1: (f64, f64),
201    p2: (f64, f64),
202    p3: (f64, f64),
203    alpha: f64,
204) -> ((f64, f64), (f64, f64)) {
205    let m1 = catmull_rom_tangent(p0, p1, p2, alpha);
206    let m2 = catmull_rom_tangent(p1, p2, p3, alpha);
207    let dt = knot_span(p1, p2, alpha);
208    (
209        (p1.0 + m1.0 * dt / 3.0, p1.1 + m1.1 * dt / 3.0),
210        (p2.0 - m2.0 * dt / 3.0, p2.1 - m2.1 * dt / 3.0),
211    )
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn closed_interpolates_square() {
220        let sq = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
221        let d = centripetal_catmull_rom_closed_path(&sq);
222        assert!(d.starts_with("M 0.00 0.00"), "d={d}");
223        assert!(d.contains("C "), "expected cubic segments: {d}");
224        for (x, y) in sq {
225            let needle = format!("{x:.2} {y:.2}");
226            assert!(
227                d.contains(&needle),
228                "missing interpolating vertex {needle} in {d}"
229            );
230        }
231        let m1 = catmull_rom_tangent(sq[3], sq[0], sq[1], 0.0);
232        assert!((m1.0 - 0.5 * (sq[1].0 - sq[3].0)).abs() < 1e-9);
233        assert!((m1.1 - 0.5 * (sq[1].1 - sq[3].1)).abs() < 1e-9);
234    }
235
236    #[test]
237    fn open_emits_cubics() {
238        let d = centripetal_catmull_rom_open_path(&[(0.0, 0.0), (40.0, 0.0), (80.0, 20.0)]);
239        assert!(d.contains('C'), "{d}");
240        assert!(!d.contains('Z'), "{d}");
241        let line = centripetal_catmull_rom_open_path(&[(0.0, 0.0), (10.0, 0.0)]);
242        assert!(line.contains('L'), "{line}");
243        assert!(centripetal_catmull_rom_open_path(&[(0.0, 0.0)]).is_empty());
244        assert!(centripetal_catmull_rom_closed_path(&[(0.0, 0.0), (1.0, 0.0)]).is_empty());
245    }
246
247    #[test]
248    fn open_last_cubic_follows_end_chord() {
249        let d = centripetal_catmull_rom_open_path(&[(0.0, 0.0), (80.0, 0.0), (80.0, 80.0)]);
250        assert!(
251            !d.contains("80.00 80.00 80.00 80.00"),
252            "p3=p2 collapsed the last cubic; head would detach: {d}"
253        );
254        assert!(d.trim_end().ends_with("80.00 80.00"), "{d}");
255    }
256
257    #[test]
258    fn sample_open_follows_control_vertices() {
259        let pts = [(0.0, 0.0), (80.0, 0.0), (80.0, 80.0)];
260        let s = sample_open_catmull(&pts, 4);
261        assert!(s.len() > pts.len(), "{}", s.len());
262        assert!((s[0].0 - 0.0).abs() < 1e-9 && (s[0].1 - 0.0).abs() < 1e-9);
263        let last = *s.last().unwrap();
264        assert!((last.0 - 80.0).abs() < 1e-6 && (last.1 - 80.0).abs() < 1e-6);
265    }
266
267    #[test]
268    fn end_frame_is_the_last_control() {
269        let pts = [(0.0, 0.0), (80.0, 0.0), (80.0, 80.0)];
270        let (tip, (ux, uy)) = open_catmull_end_frame(&pts);
271        assert!((tip.0 - 80.0).abs() < 1e-9 && (tip.1 - 80.0).abs() < 1e-9);
272        assert!(
273            uy > 0.5 && ux.abs() < 0.3,
274            "end tangent should follow last chord: {ux},{uy}"
275        );
276    }
277
278    #[test]
279    fn arrow_base_is_last_chord_not_a_path_parse() {
280        let pts = [(0.0, 0.0), (40.0, 50.0), (90.0, 10.0), (160.0, 80.0)];
281        let head = 18.0;
282        let (d, tip, base, (ux, uy)) = open_catmull_with_arrow(&pts, head);
283        assert!((tip.0 - 160.0).abs() < 1e-9 && (tip.1 - 80.0).abs() < 1e-9);
284        let chord = 70.0_f64.hypot(70.0);
285        assert!((ux - (160.0 - 90.0) / chord).abs() < 1e-9);
286        assert!((uy - (80.0 - 10.0) / chord).abs() < 1e-9);
287        assert!(((tip.0 - base.0).hypot(tip.1 - base.1) - head).abs() < 1e-9);
288        let mut shaft = pts.to_vec();
289        *shaft.last_mut().unwrap() = base;
290        assert_eq!(d, centripetal_catmull_rom_open_path(&shaft));
291        assert!(
292            (base.0 - tip.0 + ux * head).abs() < 1e-9 && (base.1 - tip.1 + uy * head).abs() < 1e-9,
293            "base must sit on the last chord"
294        );
295        let needle = format!("{:.2} {:.2}", base.0, base.1);
296        assert!(
297            d.trim_end().ends_with(&needle),
298            "cubic shaft must interpolate the head base, not a trimmed curve: d={d} base={needle}"
299        );
300    }
301}