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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Supporting public types used in the core polyline trait methods.

use super::{internal::pline_intersects::OverlappingSlice, PlineVertex, PlineView, PlineViewData};
use crate::{
    core::{
        math::Vector2,
        traits::{ControlFlow, Real},
    },
    polyline::{PlineCreation, PlineSource, ViewDataValidation},
};
use static_aabb2d_index::StaticAABB2DIndex;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Represents the orientation of a polyline.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PlineOrientation {
    /// Polyline is open.
    Open,
    /// Polyline is closed and directionally clockwise.
    Clockwise,
    /// Polyline is closed and directionally counter clockwise.
    CounterClockwise,
}

/// Result from calling [PlineSource::closest_point].
#[derive(Debug, Copy, Clone)]
pub struct ClosestPointResult<T = f64>
where
    T: Real,
{
    /// The start vertex index of the closest segment.
    pub seg_start_index: usize,
    /// The closest point on the closest segment.
    pub seg_point: Vector2<T>,
    /// The distance between the points.
    pub distance: T,
}

/// Struct to hold options parameters when performing polyline offset.
#[derive(Debug, Clone)]
pub struct PlineOffsetOptions<'a, T = f64>
where
    T: Real,
{
    /// Spatial index of all the polyline segment bounding boxes (or boxes no smaller, e.g. using
    /// [PlineSource::create_approx_aabb_index] is valid). If `None` is given then it will be
    /// computed internally. [PlineSource::create_approx_aabb_index] or
    /// [PlineSource::create_aabb_index] may be used to create the spatial index, the only
    /// restriction is that the spatial index bounding boxes must be at least big enough to contain
    /// the segments.
    pub aabb_index: Option<&'a StaticAABB2DIndex<T>>,
    /// If true then self intersects will be properly handled by the offset algorithm, if false then
    /// self intersecting polylines may not offset correctly. Handling self intersects of closed
    /// polylines requires more memory and computation.
    pub handle_self_intersects: bool,
    /// Fuzzy comparison epsilon used for determining if two positions are equal.
    pub pos_equal_eps: T,
    /// Fuzzy comparison epsilon used for determining if two positions are equal when stitching
    /// polyline slices together.
    pub slice_join_eps: T,
    /// Fuzzy comparison epsilon used when testing distance of slices to original polyline for
    /// validity.
    pub offset_dist_eps: T,
}

impl<'a, T> PlineOffsetOptions<'a, T>
where
    T: Real,
{
    #[inline]
    pub fn new() -> Self {
        Self {
            aabb_index: None,
            handle_self_intersects: false,
            pos_equal_eps: T::from(1e-5).unwrap(),
            slice_join_eps: T::from(1e-4).unwrap(),
            offset_dist_eps: T::from(1e-4).unwrap(),
        }
    }
}

impl<'a, T> Default for PlineOffsetOptions<'a, T>
where
    T: Real,
{
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
/// Boolean operation to apply to polylines.
pub enum BooleanOp {
    /// Return the union of the polylines.
    Or,
    /// Return the intersection of the polylines.
    And,
    /// Return the exclusion of a polyline from another.
    Not,
    /// Exclusive OR between polylines.
    Xor,
}

#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "camelCase"),
    serde(bound(
        serialize = "P: Serialize, P::Num: Serialize",
        deserialize = "P: Deserialize<'de>, P::Num: Deserialize<'de>",
    ))
)]
/// Represents one of the polyline results from a boolean operation between two polylines.
#[derive(Debug, Clone, Default)]
pub struct BooleanResultPline<P>
where
    P: PlineCreation,
{
    /// Resultant polyline.
    pub pline: P,
    /// Slices that were stitched together to form the `pline` result. If boolean result info is not
    /// [BooleanResultInfo::Intersected] this collection may be empty.
    pub subslices: Vec<BooleanPlineSlice<P::Num>>,
}

impl<P> BooleanResultPline<P>
where
    P: PlineCreation,
{
    #[inline]
    pub fn new(pline: P, subslices: Vec<BooleanPlineSlice<P::Num>>) -> Self {
        Self { pline, subslices }
    }
}

/// Information about what happened during the boolean operation.
#[derive(Debug, Clone)]
pub enum BooleanResultInfo {
    /// Input was not valid to perform boolean operation.
    InvalidInput,
    /// Pline1 entirely inside of pline2 with no intersects.
    Pline1InsidePline2,
    /// Pline2 entirely inside of pline1 with no intersects.
    Pline2InsidePline1,
    /// Pline1 is disjoint from pline2 (no intersects and neither polyline is inside of the other).
    Disjoint,
    /// Pline1 exactly overlaps pline2 (same geometric path).
    Overlapping,
    /// Pline1 intersects with pline2 but is not exactly overlapping with the same geometric path.
    Intersected,
}

#[derive(Debug, Clone)]
/// Result of performing a boolean operation between two polylines.
pub struct BooleanResult<P>
where
    P: PlineCreation,
{
    /// Positive remaining space polylines.
    pub pos_plines: Vec<BooleanResultPline<P>>,
    /// Negative subtracted space polylines.
    pub neg_plines: Vec<BooleanResultPline<P>>,
    /// Information about what happened during the boolean operation.
    pub result_info: BooleanResultInfo,
}

impl<P> BooleanResult<P>
where
    P: PlineCreation,
{
    #[inline]
    pub fn new(
        pos_plines: Vec<BooleanResultPline<P>>,
        neg_plines: Vec<BooleanResultPline<P>>,
        result_info: BooleanResultInfo,
    ) -> Self {
        Self {
            pos_plines,
            neg_plines,
            result_info,
        }
    }

    #[inline]
    pub fn empty(result_info: BooleanResultInfo) -> Self {
        Self::new(Vec::new(), Vec::new(), result_info)
    }

    #[inline]
    pub fn from_whole_plines<I>(
        pos_plines: I,
        neg_plines: I,
        result_info: BooleanResultInfo,
    ) -> Self
    where
        I: IntoIterator<Item = P>,
    {
        Self {
            pos_plines: pos_plines
                .into_iter()
                .map(|p| BooleanResultPline::new(p, Vec::new()))
                .collect(),
            neg_plines: neg_plines
                .into_iter()
                .map(|p| BooleanResultPline::new(p, Vec::new()))
                .collect(),
            result_info,
        }
    }
}

#[derive(Debug)]
pub struct PlineBooleanOptions<'a, T = f64>
where
    T: Real,
{
    /// Spatial index for `self` or first polyline argument for the boolean operation.
    pub pline1_aabb_index: Option<&'a StaticAABB2DIndex<T>>,
    /// Fuzzy comparison epsilon used for determining if two positions are equal.
    pub pos_equal_eps: T,
}

impl<'a, T> PlineBooleanOptions<'a, T>
where
    T: Real,
{
    #[inline]
    pub fn new() -> Self {
        Self {
            pline1_aabb_index: None,
            pos_equal_eps: T::from(1e-5).unwrap(),
        }
    }
}

impl<'a, T> Default for PlineBooleanOptions<'a, T>
where
    T: Real,
{
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Enum to control which self intersects to include.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SelfIntersectsInclude {
    /// Include all (local and global) self intersects.
    All,
    /// Include only local self intersects (defined as being between two adjacent polyline
    /// segments).
    Local,
    /// Include only global self intersects (defined as being between two non-adjacent polyline
    /// segments).
    Global,
}

#[derive(Debug)]
pub struct PlineSelfIntersectOptions<'a, T = f64>
where
    T: Real,
{
    /// Spatial index for the polyline.
    pub aabb_index: Option<&'a StaticAABB2DIndex<T>>,
    /// Fuzzy comparison epsilon used for determining if two positions are equal.
    pub pos_equal_eps: T,
    /// Controls whether to include all (local + global), only local, or only global self
    /// intersects.
    pub include: SelfIntersectsInclude,
}

impl<'a, T> PlineSelfIntersectOptions<'a, T>
where
    T: Real,
{
    #[inline]
    pub fn new() -> Self {
        Self {
            aabb_index: None,
            pos_equal_eps: T::from(1e-5).unwrap(),
            include: SelfIntersectsInclude::All,
        }
    }
}

impl<'a, T> Default for PlineSelfIntersectOptions<'a, T>
where
    T: Real,
{
    #[inline]

    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug)]
pub struct FindIntersectsOptions<'a, T = f64>
where
    T: Real,
{
    /// Spatial index for `self` or first polyline argument to find intersects.
    pub pline1_aabb_index: Option<&'a StaticAABB2DIndex<T>>,
    /// Fuzzy comparison epsilon used for determining if two positions are equal.
    pub pos_equal_eps: T,
}

impl<'a, T> FindIntersectsOptions<'a, T>
where
    T: Real,
{
    #[inline]
    pub fn new() -> Self {
        Self {
            pline1_aabb_index: None,
            pos_equal_eps: T::from(1e-5).unwrap(),
        }
    }
}

impl<'a, T> Default for FindIntersectsOptions<'a, T>
where
    T: Real,
{
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Represents a polyline intersect at a single point.
#[derive(Debug, Clone, Copy)]
pub struct PlineBasicIntersect<T = f64> {
    /// Starting vertex index of the first polyline segment involved in the intersect.
    pub start_index1: usize,
    /// Starting vertex index of the second polyline segment involved in the intersect.
    pub start_index2: usize,
    /// Point at which the intersect occurs.
    pub point: Vector2<T>,
}

impl<T> PlineBasicIntersect<T> {
    #[inline]
    pub fn new(start_index1: usize, start_index2: usize, point: Vector2<T>) -> Self {
        Self {
            start_index1,
            start_index2,
            point,
        }
    }
}

/// Represents an overlapping polyline intersect segment.
#[derive(Debug, Clone, Copy)]
pub struct PlineOverlappingIntersect<T = f64> {
    /// Starting vertex index of the first polyline segment involved in the overlapping intersect.
    pub start_index1: usize,
    /// Starting vertex index of the second polyline segment involved in the intersect.
    pub start_index2: usize,
    /// First end point of the overlapping intersect (closest to the second segment start).
    pub point1: Vector2<T>,
    /// Second end point of the overlapping intersect (furthest from the second segment start).
    pub point2: Vector2<T>,
}

impl<T> PlineOverlappingIntersect<T> {
    #[inline]
    pub fn new(
        start_index1: usize,
        start_index2: usize,
        point1: Vector2<T>,
        point2: Vector2<T>,
    ) -> Self {
        Self {
            start_index1,
            start_index2,
            point1,
            point2,
        }
    }
}

/// Represents a polyline intersect that may be either a [PlineBasicIntersect] or
/// [PlineOverlappingIntersect].
#[derive(Debug, Clone, Copy)]
pub enum PlineIntersect<T = f64> {
    Basic(PlineBasicIntersect<T>),
    Overlapping(PlineOverlappingIntersect<T>),
}

impl<T> PlineIntersect<T> {
    #[inline]
    pub fn new_basic(start_index1: usize, start_index2: usize, point: Vector2<T>) -> Self {
        PlineIntersect::Basic(PlineBasicIntersect::new(start_index1, start_index2, point))
    }

    #[inline]
    pub fn new_overlapping(
        start_index1: usize,
        start_index2: usize,
        point1: Vector2<T>,
        point2: Vector2<T>,
    ) -> Self {
        PlineIntersect::Overlapping(PlineOverlappingIntersect::new(
            start_index1,
            start_index2,
            point1,
            point2,
        ))
    }
}

/// Trait for visiting polyline intersects.
pub trait PlineIntersectVisitor<T, C>
where
    T: Real,
    C: ControlFlow,
{
    fn visit_basic_intr(&mut self, intr: PlineBasicIntersect<T>) -> C;
    fn visit_overlapping_intr(&mut self, intr: PlineOverlappingIntersect<T>) -> C;
}

impl<T, C, F> PlineIntersectVisitor<T, C> for F
where
    T: Real,
    C: ControlFlow,
    F: FnMut(PlineIntersect<T>) -> C,
{
    #[inline]
    fn visit_basic_intr(&mut self, intr: PlineBasicIntersect<T>) -> C {
        self(PlineIntersect::Basic(intr))
    }

    #[inline]
    fn visit_overlapping_intr(&mut self, intr: PlineOverlappingIntersect<T>) -> C {
        self(PlineIntersect::Overlapping(intr))
    }
}

/// Trait for visiting polyline vertexes.
pub trait PlineVertexVisitor<T, C>
where
    T: Real,
    C: ControlFlow,
{
    fn visit_vertex(&mut self, vertex: PlineVertex<T>) -> C;
}

impl<T, C, F> PlineVertexVisitor<T, C> for F
where
    T: Real,
    C: ControlFlow,
    F: FnMut(PlineVertex<T>) -> C,
{
    #[inline]
    fn visit_vertex(&mut self, vertex: PlineVertex<T>) -> C {
        self(vertex)
    }
}

/// Trait for visiting polyline segments (two consecutive vertexes).
pub trait PlineSegVisitor<T, C>
where
    T: Real,
    C: ControlFlow,
{
    fn visit_seg(&mut self, v1: PlineVertex<T>, v2: PlineVertex<T>) -> C;
}

impl<T, C, F> PlineSegVisitor<T, C> for F
where
    T: Real,
    C: ControlFlow,
    F: FnMut(PlineVertex<T>, PlineVertex<T>) -> C,
{
    #[inline]
    fn visit_seg(&mut self, v1: PlineVertex<T>, v2: PlineVertex<T>) -> C {
        self(v1, v2)
    }
}

/// Represents a collection of basic and overlapping polyline intersects.
#[derive(Debug, Clone)]
pub struct PlineIntersectsCollection<T = f64> {
    pub basic_intersects: Vec<PlineBasicIntersect<T>>,
    pub overlapping_intersects: Vec<PlineOverlappingIntersect<T>>,
}

impl<T> PlineIntersectsCollection<T> {
    #[inline]
    pub fn new(
        basic_intersects: Vec<PlineBasicIntersect<T>>,
        overlapping_intersects: Vec<PlineOverlappingIntersect<T>>,
    ) -> Self {
        Self {
            basic_intersects,
            overlapping_intersects,
        }
    }

    #[inline]
    pub fn new_empty() -> Self {
        Self::new(Vec::new(), Vec::new())
    }
}

#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "camelCase")
)]
/// Open polyline slice created in the process of performing a polyline boolean operation.
#[derive(Debug, Copy, Clone)]
pub struct BooleanPlineSlice<T = f64> {
    /// View data for the slice, can be used with source polyline to form a view of the vertexes for
    /// the slice.
    pub view_data: PlineViewData<T>,
    /// If true then the source polyline for this slice is pline1 from the boolean operation
    /// otherwise it is pline2.
    pub source_is_pline1: bool,
    /// Whether the slice is an overlapping slice or not (both polylines in the boolean operation
    /// overlapped along this slice).
    pub overlapping: bool,
}

impl<T> BooleanPlineSlice<T>
where
    T: Real,
{
    #[inline]
    pub fn from_open_pline_slice(
        data: &PlineViewData<T>,
        source_is_pline1: bool,
        inverted: bool,
    ) -> Self {
        Self {
            view_data: PlineViewData {
                start_index: data.start_index,
                end_index_offset: data.end_index_offset,
                updated_start: data.updated_start,
                updated_end_bulge: data.updated_end_bulge,
                end_point: data.end_point,
                inverted_direction: inverted,
            },
            source_is_pline1,
            overlapping: false,
        }
    }

    #[inline]
    pub fn from_overlapping<P>(
        source: &P,
        overlapping_slice: &OverlappingSlice<T>,
        inverted: bool,
    ) -> Self
    where
        P: PlineSource<Num = T> + ?Sized,
    {
        let result = Self {
            view_data: PlineViewData {
                start_index: overlapping_slice.start_indexes.1,
                end_index_offset: overlapping_slice.view_data.end_index_offset,
                updated_start: overlapping_slice.view_data.updated_start,
                updated_end_bulge: overlapping_slice.view_data.updated_end_bulge,
                end_point: overlapping_slice.view_data.end_point,
                inverted_direction: inverted,
            },
            source_is_pline1: false,
            overlapping: true,
        };
        debug_assert_eq!(
            result.view_data.validate_for_source(source),
            ViewDataValidation::IsValid
        );
        result
    }

    #[inline]
    pub fn view<'a, P>(&self, source: &'a P) -> PlineView<'a, P>
    where
        P: PlineSource<Num = T> + ?Sized,
    {
        self.view_data.view(source)
    }
}