curvo 0.1.88

NURBS modeling library
Documentation
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::{cell::RefCell, cmp::Ordering, rc::Rc};

use itertools::Itertools;
use nalgebra::{Point2, U2, U3};

use crate::{
    boolean::{
        degeneracies::Degeneracy, has_parameter::HasParameter, node::Node, status::Status,
        vertex::Vertex,
    },
    curve::NurbsCurve2D,
    misc::{EndPoints, FloatingPoint},
    prelude::{CompoundCurveIntersection, Contains, HasIntersection, HasIntersectionParameter},
    region::{CompoundCurve, Region},
    trim::TrimRange,
};

use super::operation::BooleanOperation;

#[derive(Clone, Debug)]
#[allow(clippy::type_complexity)]
pub struct ClipDebugInfo<T>
where
    T: FloatingPoint,
{
    pub chunks: Vec<((Point2<T>, Status), (Point2<T>, Status))>,
    pub spans: Vec<NurbsCurve2D<T>>,
}

impl<T: FloatingPoint> Default for ClipDebugInfo<T> {
    fn default() -> Self {
        Self {
            chunks: vec![],
            spans: vec![],
        }
    }
}

#[allow(clippy::type_complexity)]
impl<T: FloatingPoint> ClipDebugInfo<T> {
    pub fn add_node_chunk(&mut self, chunk: ((Point2<T>, Status), (Point2<T>, Status))) {
        self.chunks.push(chunk);
    }

    pub fn node_chunks(&self) -> &Vec<((Point2<T>, Status), (Point2<T>, Status))> {
        &self.chunks
    }

    pub fn add_span(&mut self, span: NurbsCurve2D<T>) {
        self.spans.push(span);
    }

    pub fn spans(&self) -> &Vec<NurbsCurve2D<T>> {
        &self.spans
    }
}

/// A clip result
pub struct Clip<T: FloatingPoint> {
    regions: Vec<Region<T>>,
    info: ClipDebugInfo<T>,
}

impl<T: FloatingPoint> Clip<T> {
    pub fn new(regions: Vec<Region<T>>, info: ClipDebugInfo<T>) -> Self {
        Self { regions, info }
    }

    pub fn regions(&self) -> &Vec<Region<T>> {
        &self.regions
    }

    pub fn regions_mut(&mut self) -> &mut Vec<Region<T>> {
        &mut self.regions
    }

    pub fn into_regions(self) -> Vec<Region<T>> {
        self.regions
    }

    pub fn info(&self) -> &ClipDebugInfo<T> {
        &self.info
    }
}

/// Boolean operation for two curves.
/// Base algorithm reference: Efficient clipping of arbitrary polygons (https://www.inf.usi.ch/hormann/papers/Greiner.1998.ECO.pdf)
pub fn clip<'a, T: FloatingPoint, S, C, O: Clone>(
    subject: &'a S,
    clip: &'a C,
    operation: BooleanOperation,
    option: O,
    intersections: Vec<CompoundCurveIntersection<'a, T, U3>>,
) -> anyhow::Result<Clip<T>>
where
    S: Clone
        + Contains<C, Option = O>
        + EndPoints<T, U2>
        + Into<CompoundCurve<T, U3>>
        + TrimRange<T, U3>,
    C: Clone
        + Contains<S, Option = O>
        + EndPoints<T, U2>
        + Into<CompoundCurve<T, U3>>
        + TrimRange<T, U3>,
{
    let deg = intersections
        .into_iter()
        .map(|it| {
            let deg = Degeneracy::new(&it, it.a_curve(), it.b_curve());
            (it, deg)
        })
        .collect_vec();

    let (regular, deg): (Vec<_>, Vec<_>) = deg
        .into_iter()
        .partition(|(_, deg)| matches!(deg, Degeneracy::None));

    let regular = regular.into_iter().map(|(it, _)| it).collect_vec();
    let intersections = if regular.len() % 2 == 0 {
        regular
    } else {
        let max = deg.into_iter().max_by(|x, y| match (x.1, y.1) {
            (Degeneracy::Angle(x), Degeneracy::Angle(y)) => {
                x.partial_cmp(&y).unwrap_or(Ordering::Equal)
            }
            _ => Ordering::Equal,
        });
        match max {
            Some((max, _)) => [regular, vec![max]].concat(),
            _ => regular,
        }
    };

    anyhow::ensure!(
        intersections.len() % 2 == 0,
        "found odd number of intersections: {}",
        intersections.len()
    );

    let clip_contains_subject = clip.contains(subject, option.clone())?;
    let subject_contains_clip = subject.contains(clip, option.clone())?;
    // println!("clip contains subject: {}, subject contains clip: {}", clip_contains_subject, subject_contains_clip);

    let indexed = intersections.into_iter().enumerate().collect_vec();

    if indexed.is_empty() {
        let res = match (subject_contains_clip, clip_contains_subject) {
            (true, false) => match operation {
                BooleanOperation::Union => vec![Region::new(subject.clone().into(), vec![])],
                BooleanOperation::Intersection => {
                    vec![Region::new(clip.clone().into(), vec![])]
                }
                BooleanOperation::Difference => {
                    vec![Region::new(
                        subject.clone().into(),
                        vec![clip.clone().into()],
                    )]
                }
            },
            (false, true) => match operation {
                BooleanOperation::Union => vec![Region::new(clip.clone().into(), vec![])],
                BooleanOperation::Intersection => {
                    vec![Region::new(subject.clone().into(), vec![])]
                }
                BooleanOperation::Difference => {
                    vec![]
                }
            },
            (false, false) => match operation {
                BooleanOperation::Union => vec![
                    Region::new(subject.clone().into(), vec![]),
                    Region::new(clip.clone().into(), vec![]),
                ],
                BooleanOperation::Intersection => vec![],
                BooleanOperation::Difference => {
                    vec![Region::new(subject.clone().into(), vec![])]
                }
            },
            _ => {
                anyhow::bail!("Invalid case");
            }
        };
        // return Ok(res);
        return Ok(Clip::new(res, Default::default()));
    }

    // create linked list
    let mut a = indexed
        .iter()
        .sorted_by(|(_, i0), (_, i1)| i0.a_parameter().partial_cmp(&i1.a_parameter()).unwrap())
        .map(|(i, it)| {
            let (curve, p, t) = it.a();
            let v = Vertex::new(std::borrow::Borrow::borrow(curve), *p, *t);
            (*i, Rc::new(RefCell::new(Node::new(true, v))))
        })
        .collect_vec();

    let mut b = indexed
        .iter()
        .sorted_by(|(_, i0), (_, i1)| i0.b_parameter().partial_cmp(&i1.b_parameter()).unwrap())
        .map(|(i, it)| {
            let (curve, p, t) = it.b();
            let v = Vertex::new(std::borrow::Borrow::borrow(curve), *p, *t);
            (*i, Rc::new(RefCell::new(Node::new(false, v))))
        })
        .collect_vec();

    // connect neighbors
    a.iter_mut().for_each(|(index, node)| {
        if let Some((_, neighbor)) = b.iter().find(|(i, _)| i == index) {
            node.borrow_mut().set_neighbor(Rc::downgrade(neighbor));
        }
    });
    b.iter_mut().for_each(|(index, node)| {
        if let Some((_, neighbor)) = a.iter().find(|(i, _)| i == index) {
            node.borrow_mut().set_neighbor(Rc::downgrade(neighbor));
        }
    });

    // remove indices
    let a = a.into_iter().map(|(_, n)| n).collect_vec();
    let b = b.into_iter().map(|(_, n)| n).collect_vec();

    // connect cyclically
    [&a, &b].iter().for_each(|list| {
        list.iter()
            .cycle()
            .take(list.len() + 1)
            .collect_vec()
            .windows(2)
            .for_each(|w| {
                w[0].borrow_mut().set_next(Rc::downgrade(w[1]));
                w[1].borrow_mut().set_prev(Rc::downgrade(w[0]));
            });
    });

    let mut a_flag = !clip_contains_subject;
    let mut b_flag = !subject_contains_clip;

    a.iter().for_each(|list| {
        let mut node = list.borrow_mut();
        *node.status_mut() = if a_flag { Status::Enter } else { Status::Exit };
        a_flag = !a_flag;
    });

    b.iter().for_each(|list| {
        let mut node = list.borrow_mut();
        *node.status_mut() = if b_flag { Status::Enter } else { Status::Exit };
        b_flag = !b_flag;
    });

    match operation {
        BooleanOperation::Union | BooleanOperation::Difference => {
            // invert a status
            a.iter().for_each(|node| {
                node.borrow_mut().status_mut().invert();
            });
        }
        _ => {}
    }

    if operation == BooleanOperation::Union {
        // invert b status
        b.iter().for_each(|node| {
            node.borrow_mut().status_mut().invert();
        });
    }

    let mut regions: Vec<Region<T>> = vec![];

    fn non_visited<T: FloatingPoint>(
        node: Rc<RefCell<Node<Vertex<'_, T>>>>,
    ) -> Option<Rc<RefCell<Node<Vertex<'_, T>>>>> {
        let mut non_visited = node.clone();

        if non_visited.borrow().visited() {
            loop {
                let next = non_visited.borrow().next()?;
                non_visited = next;
                if Rc::ptr_eq(&node, &non_visited) || !non_visited.borrow().visited() {
                    break;
                }
            }
        }

        if non_visited.borrow().visited() {
            None
        } else {
            Some(non_visited)
        }
    }

    let subject_head_node = &a[0];

    /*
    println!(
        "a statues: {:?}",
        a.iter().map(|n| n.borrow().status()).collect_vec()
    );
    println!(
        "a parameters: {:?}",
        a.iter()
            .map(|n| n.borrow().vertex().parameter())
            .collect_vec()
    );
    println!(
        "b statues: {:?}",
        b.iter().map(|n| n.borrow().status()).collect_vec()
    );
    */

    let mut info = ClipDebugInfo::default();

    while let Some(start) = non_visited(subject_head_node.clone()) {
        let mut nodes = vec![];
        let mut current = start.clone();
        loop {
            if current.borrow().visited() {
                break;
            }

            current.borrow_mut().visit();
            nodes.push(current.clone());

            let node = current.borrow().clone();
            let next = match node.status() {
                Status::Enter => node.next(),
                Status::Exit => node.prev(),
                Status::None => todo!(),
            };

            if let Some(next) = next {
                next.borrow_mut().visit();
                nodes.push(next.clone());
                if let Some(neighbor) = next.borrow().neighbor() {
                    current = neighbor.clone();
                } else {
                    break;
                }
            } else {
                break;
            }
        }

        let mut spans = vec![];
        for chunk in nodes.chunks(2) {
            if chunk.len() != 2 {
                break;
            }
            let n0 = chunk[0].borrow();
            let n1 = chunk[1].borrow();

            info.add_node_chunk((
                (*n0.vertex().position(), n0.status()),
                (*n1.vertex().position(), n1.status()),
            ));

            /*
            println!(
                "{:?} {:?} -> {:?} {:?}",
                n0.subject(),
                n0.status(),
                n1.subject(),
                n1.status()
            );
            */

            let params = match (n0.status(), n1.status()) {
                (Status::Enter, Status::Exit) => (n0.vertex().parameter(), n1.vertex().parameter()),
                (Status::Exit, Status::Enter) => (n1.vertex().parameter(), n0.vertex().parameter()),
                _ => {
                    anyhow::bail!("Invalid status");
                }
            };

            anyhow::ensure!(n0.subject() == n1.subject(), "Invalid condition");

            let trimmed = if n0.subject() {
                subject.try_trim_range(params)
            } else {
                clip.try_trim_range(params)
            }?;
            spans.extend(trimmed);
        }

        if !spans.is_empty() {
            spans.iter().for_each(|span| {
                info.add_span(span.clone());
            });

            // filter out degenerated spans
            let spans = spans
                .into_iter()
                .filter_map(|span| {
                    if span.degree() == 1 {
                        let mut pts = span.dehomogenized_control_points();
                        pts.dedup();
                        if pts.len() >= 2 {
                            Some(NurbsCurve2D::polyline(&pts, false))
                        } else {
                            None
                        }
                    } else {
                        Some(span)
                    }
                })
                .collect_vec();
            let region = Region::new(CompoundCurve::try_new(spans)?, vec![]);
            regions.push(region);
        }
    }

    Ok(Clip::new(regions, info))
}