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
// Copyright (c) 2018-2021 Thomas Kramer.
// SPDX-FileCopyrightText: 2022 Thomas Kramer
// SPDX-FileCopyrightText: 2020 Fabian Keller <github.100.fkeller@spamgourmet.com> (contributions under MIT licence)
// SPDX-FileCopyrightText: 2020 Bodo Junglas <junglas@objectcode.de> (contributions under MIT licence)
//
// SPDX-License-Identifier: AGPL-3.0-or-later

use iron_shapes::edge::{Edge, Side};
use iron_shapes::point::Point;
use iron_shapes::CoordinateType;
use std::cell::RefCell;
use std::rc::{Rc, Weak};

use std::cmp::Ordering;

/// Distinguish between the left and right operand of the boolean operation.
/// This matters for the boolean intersection and difference only.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Ord, PartialOrd)]
pub enum PolygonType {
    /// Left operand.
    Subject,
    /// Right operand.
    Clipping,
}

/// Mutable data of a sweep event.
#[derive(Debug, Clone)]
struct MutablePart<T, Ctr, Property> {
    /// Reference to the event associated with the other endpoint of the edge.
    other_event: Weak<SweepEvent<T, Ctr, Property>>,
    /// Edge below this event. This is used to find polygon-hole relationships.
    prev: Weak<SweepEvent<T, Ctr, Property>>,
    counter: Ctr,
    /// Index of this event in an array.
    /// In a later step of the algorithm this will hold the index of the other event.
    pos: usize,
}

#[derive(Debug, Clone)]
pub struct SweepEvent<T, Ctr, Property = ()> {
    /// Mutable part of the sweep event. Borrow checking happens at runtime.
    mutable: RefCell<MutablePart<T, Ctr, Property>>,
    /// Point associated with the event. Starting point or end point of the edge.
    pub p: Point<T>,
    /// Original edge from which this SweepEvent was created
    pub original_edge: Edge<T>,
    /// Is p the left endpoint of the edge (p, other.p)?
    is_left_event: bool,
    /// Is this edge an upper boundary of the input polygon?
    pub is_upper_boundary: bool,
    /// Unique ID of the edge. Used to break ties and guarantee ordering for overlapping edges.
    edge_id: usize,
    /// Property associated with this event.
    /// Only left events store a property. The field is 'None' for right events.
    /// Can be used to store an ID of the polygon.
    /// For binary boolean operations this field is used to store the polygon type ('clipping' or 'subject').
    pub property: Option<Property>,
}

#[cfg(test)]
impl<T, Ctr> SweepEvent<T, Ctr, ()>
where
    T: CoordinateType,
    Ctr: Default,
{
    /// Create a new sweep event wrapped into a `Rc`.
    pub fn new_rc(
        edge_id: usize,
        point: Point<T>,
        other_point: Point<T>,
        is_left_event: bool,
        other_event: Weak<SweepEvent<T, Ctr>>,
        is_upper_boundary: bool,
    ) -> Rc<SweepEvent<T, Ctr>> {
        Self::new_rc_with_property(
            edge_id,
            point,
            other_point,
            is_left_event,
            other_event,
            is_upper_boundary,
            Some(()),
        )
    }
}

impl<T, Ctr, Property> SweepEvent<T, Ctr, Property>
where
    T: CoordinateType,
    Ctr: Default,
{
    /// Create a new sweep event wrapped into a `Rc`.
    pub fn new_rc_with_property(
        edge_id: usize,
        point: Point<T>,
        other_point: Point<T>,
        is_left_event: bool,
        other_event: Weak<SweepEvent<T, Ctr, Property>>,
        is_upper_boundary: bool,
        property: Option<Property>,
    ) -> Rc<SweepEvent<T, Ctr, Property>> {
        Rc::new(SweepEvent {
            mutable: RefCell::new(MutablePart {
                other_event,
                prev: Weak::new(),
                counter: Default::default(),
                pos: 0,
            }),
            p: point,
            original_edge: Edge::new(point, other_point),
            is_left_event,
            is_upper_boundary,
            edge_id,
            property,
        })
    }
}

impl<T, Ctr, Property> SweepEvent<T, Ctr, Property>
where
    T: CoordinateType,
{
    pub fn is_left_event(&self) -> bool {
        self.is_left_event
    }

    /// Get the event that represents the other end point of this segment.
    pub fn get_other_event(&self) -> Option<Rc<Self>> {
        self.mutable.borrow().other_event.upgrade()
    }

    /// Set the event that represents the other end point of this segment.
    pub fn set_other_event(&self, other_event: &Rc<Self>) {
        debug_assert_ne!(self.is_left_event(), other_event.is_left_event());
        self.mutable.borrow_mut().other_event = Rc::downgrade(other_event);
    }

    /// Get the segment associated with the event.
    /// The `start` point will be the point of the first event,
    /// `end` will be the point of the second event.
    pub fn get_edge(&self) -> Option<Edge<T>> {
        self.get_other_event().map(|other| {
            let p1 = self.p;
            let p2 = other.p;

            debug_assert!(self.is_left_event() ^ other.is_left_event());

            Edge::new(p1, p2)
        })
    }

    /// Get the original edge associated with this event. Start and end point are sorted.
    pub fn get_original_edge(&self) -> Edge<T> {
        let e = self.original_edge;

        if e.start < e.end {
            e
        } else {
            e.reversed()
        }
    }

    pub fn with_counter<F, R>(&self, mut f: F) -> R
    where
        F: FnMut(&Ctr) -> R,
    {
        f(&self.mutable.borrow().counter)
    }

    pub fn with_counter_mut<F, R>(&self, mut f: F) -> R
    where
        F: FnMut(&mut Ctr) -> R,
    {
        f(&mut self.mutable.borrow_mut().counter)
    }

    pub fn get_pos(&self) -> usize {
        self.mutable.borrow().pos
    }

    pub fn set_pos(&self, pos: usize) {
        self.mutable.borrow_mut().pos = pos
    }

    pub fn get_edge_id(&self) -> usize {
        self.edge_id
    }

    pub fn get_prev(&self) -> Weak<Self> {
        self.mutable.borrow().prev.clone()
    }

    pub fn set_prev(&self, prev: Weak<Self>) {
        self.mutable.borrow_mut().prev = prev;
    }

    /// Lower boundaries have a weight `1`, upper boundaries have a weight `-1`.
    pub fn edge_weight(&self) -> i32 {
        if self.is_upper_boundary {
            -1
        } else {
            1
        }
    }
}

impl<'a, T, Ctr, P> PartialEq for SweepEvent<T, Ctr, P>
where
    T: CoordinateType,
{
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl<T, Ctr, P> Eq for SweepEvent<T, Ctr, P> where T: CoordinateType {}

impl<T, Ctr, P> PartialOrd for SweepEvent<T, Ctr, P>
where
    T: CoordinateType,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a, T, Ctr, P> Ord for SweepEvent<T, Ctr, P>
where
    T: CoordinateType,
{
    fn cmp(&self, other: &Self) -> Ordering {
        // Note that the order is reversed at the end because this is used in a max-heap.

        let point_ordering = self.p.partial_cmp(&other.p).unwrap();

        match point_ordering {
            Ordering::Equal => {
                debug_assert!(self.p == other.p);

                // Points are equal. Break the tie!
                // Prefer right events over left events (This is needed to efficiently connect the edges later on).
                match self.is_left_event.cmp(&other.is_left_event) {
                    Ordering::Equal => {
                        // Break the tie by the edges.
                        let edge1 = self.get_original_edge();
                        let edge2 = other.get_original_edge();

                        debug_assert!(edge1.start == edge2.start || edge1.end == edge2.end);

                        let reference_point = if other.is_left_event {
                            edge2.end
                        } else {
                            edge2.start
                        };

                        match edge1.side_of(reference_point) {
                            // Prefer the lower edge (which has the other end point on the left side).
                            Side::Left => {
                                debug_assert!(!edge1.is_collinear(&edge2));
                                Ordering::Less
                            }
                            Side::Right => {
                                debug_assert!(!edge1.is_collinear(&edge2));
                                Ordering::Greater
                            }
                            Side::Center => {
                                debug_assert!(edge1.is_collinear(&edge2));

                                // Lower boundaries before upper boundaries
                                // then break ties by the edge_id.
                                self.is_upper_boundary
                                    .cmp(&other.is_upper_boundary)
                                    .then_with(|| self.get_edge_id().cmp(&other.get_edge_id()))
                            }
                        }
                    }
                    less_or_greater => less_or_greater,
                }
            }
            less_or_greater => less_or_greater,
        }
        .reverse()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::collections::BinaryHeap;

    #[test]
    fn test_prefer_right_events_over_left_events() {
        let left: Rc<SweepEvent<_, ()>> = SweepEvent::new_rc(
            0,
            (0, 0).into(),
            (0, 0).into(),
            true, // left
            Weak::new(),
            false,
        );
        let right = SweepEvent::new_rc(
            0,
            (0, 0).into(),
            (0, 0).into(),
            false, // right
            Weak::new(),
            false,
        );

        assert!(right > left);
    }

    #[test]
    fn test_prefer_right_events_over_left_events_in_binary_heap() {
        let left: Rc<SweepEvent<_, ()>> = SweepEvent::new_rc(
            0,
            (0, 0).into(),
            (0, 0).into(),
            true, // left
            Weak::new(),
            false,
        );
        let right = SweepEvent::new_rc(
            0,
            (0, 0).into(),
            (0, 0).into(),
            false, // right
            Weak::new(),
            false,
        );

        let mut heap = BinaryHeap::new();
        heap.push(right);
        heap.push(left);

        let e1 = heap.pop().unwrap();
        let e2 = heap.pop().unwrap();
        assert!(!e1.is_left_event);
        assert!(e2.is_left_event);
    }

    #[test]
    fn test_on_equal_x_sort_y() {
        let lower: Rc<SweepEvent<_, ()>> = SweepEvent::new_rc(
            0,
            (0, 0).into(),
            (0, 0).into(),
            true, // left
            Weak::new(),
            false,
        );
        let upper = SweepEvent::new_rc(
            0,
            (0, 1).into(),
            (0, 1).into(),
            false, // right
            Weak::new(),
            false,
        );

        assert!(lower > upper);
    }
}