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
use fnv::{FnvHashMap, FnvHashSet};
use grid::{Grid, GridShape};
use intersect::Intersect;
use line_path::LinePath;
use ordered_float::OrderedFloat;
use segments::LineSegment;
use stable_vec::StableVec;
use std::collections::hash_map::Entry;
use util::SmallSortedSet;
use {P2, V2, VecLike, N};

#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct PieceSegmentIndex {
    pub piece_idx: usize,
    pub segment_idx: usize,
}

#[derive(Clone)]
pub struct Embedding<L: Clone> {
    piece_segment_grid: Grid<PieceSegmentIndex>,
    pub pieces: StableVec<(LinePath, L)>,
}

struct PieceIntersection {
    segment_idx: usize,
    along: N,
    position: P2,
}

impl<L: Clone> Embedding<L> {
    pub fn new(cell_width: N) -> Self {
        Embedding {
            piece_segment_grid: Grid::new(cell_width),
            pieces: StableVec::new(),
        }
    }

    pub fn insert(&mut self, new_path: LinePath, label: L) {
        let mut intersections_on_new: Vec<PieceIntersection> = Vec::new();
        let mut intersections_on_others: FnvHashMap<usize, Vec<PieceIntersection>> =
            FnvHashMap::default();

        for (new_segment_idx, new_segment) in new_path.segments().enumerate() {
            let mut seen_other_piece_segments = SmallSortedSet::<[PieceSegmentIndex; 16]>::new();

            self.piece_segment_grid.visit(&new_segment, |cell_content| {
                for other_piece_segment_idx in cell_content.iter() {
                    if !seen_other_piece_segments.contains(other_piece_segment_idx) {
                        let other_segment = self.pieces[other_piece_segment_idx.piece_idx]
                            .0
                            .nth_segment(other_piece_segment_idx.segment_idx);

                        for intersection in (new_segment, other_segment).intersect() {
                            intersections_on_new.push(PieceIntersection {
                                segment_idx: new_segment_idx,
                                along: intersection.along_a,
                                position: intersection.position,
                            });

                            let other_intersection = PieceIntersection {
                                segment_idx: other_piece_segment_idx.segment_idx,
                                along: intersection.along_b,
                                position: intersection.position,
                            };

                            match intersections_on_others.entry(other_piece_segment_idx.piece_idx) {
                                Entry::Vacant(vacant) => {
                                    vacant.insert(vec![other_intersection]);
                                }
                                Entry::Occupied(mut occupied) => {
                                    occupied.into_mut().push(other_intersection);
                                }
                            }
                        }

                        seen_other_piece_segments.insert(*other_piece_segment_idx);
                    }
                }
            })
        }

        for (other_piece_idx, other_intersections) in intersections_on_others.into_iter() {
            let (other_piece, other_label) = self.remove_piece(other_piece_idx);
            self.insert_piece_splits(other_piece, other_intersections, other_label)
        }

        if intersections_on_new.is_empty() {
            self.insert_whole_piece(new_path, label);
        } else {
            self.insert_piece_splits(new_path, intersections_on_new, label);
        }
    }

    fn insert_piece_splits(
        &mut self,
        initial_piece: LinePath,
        mut intersections: Vec<PieceIntersection>,
        label: L,
    ) {
        intersections.sort_unstable_by(|intersection_a, intersection_b| {
            intersection_a
                .segment_idx
                .cmp(&intersection_b.segment_idx)
                .then(OrderedFloat(intersection_a.along).cmp(&OrderedFloat(intersection_b.along)))
        });
        let mut original_points_iter = initial_piece.points.iter().enumerate().peekable();
        let mut intersections_iter = intersections.into_iter().peekable();

        let mut new_point_groups = vec![VecLike::new()];

        loop {
            let take_point = {
                let maybe_next_point_with_idx = original_points_iter.peek();
                let maybe_next_intersection = intersections_iter.peek();

                match (maybe_next_point_with_idx, maybe_next_intersection) {
                    (Some((next_point_idx, _next_point)), Some(next_intersection)) => {
                        if *next_point_idx <= next_intersection.segment_idx {
                            true
                        } else {
                            false
                        }
                    }
                    (Some(_), None) => true,
                    (None, Some(_)) => false,
                    (None, None) => break,
                }
            };

            if take_point {
                new_point_groups
                    .last_mut()
                    .expect("should have last point group")
                    .push(
                        original_points_iter
                            .next()
                            .expect("already peeked point!")
                            .1
                            .clone(),
                    );
            } else {
                let intersection_point = intersections_iter
                    .next()
                    .expect("already peeked intersetion!")
                    .position;
                new_point_groups
                    .last_mut()
                    .expect("should have last point group")
                    .push(intersection_point);
                new_point_groups.push(Some(intersection_point).into_iter().collect());
            }
        }

        for points_group in new_point_groups.into_iter() {
            if let Some(split_piece) = LinePath::new(points_group) {
                self.insert_whole_piece(split_piece, label.clone())
            }
        }
    }

    fn insert_whole_piece(&mut self, path: LinePath, label: L) {
        let piece_idx = self.pieces.next_index();

        for (segment_idx, segment) in path.segments().enumerate() {
            self.piece_segment_grid.insert_unchecked(
                PieceSegmentIndex {
                    piece_idx,
                    segment_idx,
                },
                &segment,
            );
        }

        self.pieces.push((path, label));
    }

    fn remove_piece(&mut self, piece_idx: usize) -> (LinePath, L) {
        let (path, label) = self
            .pieces
            .remove(piece_idx)
            .expect("Tried to remove non-existing piece");

        // TODO: this might redundantly try to remove several times from the same grid cells
        for segment in path.segments() {
            self.piece_segment_grid
                .retain(segment, |piece_segment_idx: &mut PieceSegmentIndex| {
                    piece_segment_idx.piece_idx != piece_idx
                })
        }

        (path, label)
    }

    pub fn query_pieces<S: GridShape>(
        &self,
        shape: &S,
    ) -> Vec<(LineSegment, &L, PieceSegmentIndex)> {
        let mut unique_piece_segment_indices =
            FnvHashSet::with_capacity_and_hasher(100, Default::default());

        self.piece_segment_grid.visit(shape, |cell_content| {
            unique_piece_segment_indices.extend(cell_content.iter().cloned());
        });

        unique_piece_segment_indices
            .into_iter()
            .map(|piece_segment_idx| {
                let (path, label) = &self.pieces[piece_segment_idx.piece_idx];
                (
                    path.nth_segment(piece_segment_idx.segment_idx),
                    label,
                    piece_segment_idx,
                )
            })
            .collect()
    }

    pub fn query_ray_along_x(&self, start_point: P2) -> Vec<(LineSegment, &L, PieceSegmentIndex)> {
        let ray_length = (self.piece_segment_grid.max_bounds.0
            - (start_point.x / self.piece_segment_grid.cell_width) as i32)
            .max(1) as f32 * self.piece_segment_grid.cell_width;
        let ray = LineSegment::new(start_point, start_point + V2::new(ray_length, 0.0));

        self.query_pieces(&ray)
    }

    pub fn map_labels<L2: Clone, M: FnMut(&LinePath, &L, &Self) -> L2>(
        &mut self,
        mut mapper: M,
    ) -> Embedding<L2> {
        let mut new_pieces = StableVec::new();
        new_pieces.grow(self.pieces.capacity());

        for piece_idx in self.pieces.keys() {
            let (piece, old_label) = &self.pieces[piece_idx];
            let new_label = mapper(&piece, &old_label, self);
            new_pieces
                .insert_into_hole(piece_idx, (piece.clone(), new_label))
                .ok()
                .expect("Index in clone should be free!");
        }

        Embedding {
            piece_segment_grid: self.piece_segment_grid.clone(),
            pieces: new_pieces,
        }
    }

    pub fn map_labels_in_place<M: FnMut(&LinePath, &L, &Self) -> L>(&mut self, mut mapper: M) {
        let mut new_pieces = StableVec::new();
        new_pieces.grow(self.pieces.capacity());

        for piece_idx in self.pieces.keys() {
            let (piece, old_label) = &self.pieces[piece_idx];
            let new_label = mapper(&piece, &old_label, self);
            new_pieces
                .insert_into_hole(piece_idx, (piece.clone(), new_label))
                .ok()
                .expect("Index in clone should be free!");
        }

        self.pieces = new_pieces;
    }

    pub fn retain_pieces<P: FnMut(&LinePath, &L, &Self) -> bool>(&mut self, mut predicate: P) {
        for piece_idx in 0..self.pieces.next_index() {
            let (existed, keep) = self
                .pieces
                .get(piece_idx)
                .map(|(path, label)| (true, predicate(path, label, self)))
                .unwrap_or((false, false));

            if existed && !keep {
                self.remove_piece(piece_idx);
            }
        }
    }
}

#[test]
fn embedding_test() {
    let mut embedding = Embedding::new(0.25);

    #[derive(Clone, PartialEq, Eq, Debug)]
    enum Label {
        A,
        B,
    }

    //        |
    //     .--x--- B
    // A --x--'
    //     |
    embedding.insert(
        LinePath::new(vec![
            P2::new(0.0, 0.0),
            P2::new(1.0, 0.0),
            P2::new(1.0, 1.0),
        ]).unwrap(),
        Label::A,
    );
    embedding.insert(
        LinePath::new(vec![
            P2::new(0.5, -0.5),
            P2::new(0.5, 0.5),
            P2::new(1.5, 0.5),
        ]).unwrap(),
        Label::B,
    );

    assert_eq!(
        embedding.pieces.iter().cloned().collect::<Vec<_>>(),
        vec![
            (
                LinePath::new(vec![P2::new(0.0, 0.0), P2::new(0.5, 0.0)]).unwrap(),
                Label::A,
            ),
            (
                LinePath::new(vec![
                    P2::new(0.5, 0.0),
                    P2::new(1.0, 0.0),
                    P2::new(1.0, 0.5),
                ]).unwrap(),
                Label::A,
            ),
            (
                LinePath::new(vec![P2::new(1.0, 0.5), P2::new(1.0, 1.0)]).unwrap(),
                Label::A,
            ),
            (
                LinePath::new(vec![P2::new(0.5, -0.5), P2::new(0.5, 0.0)]).unwrap(),
                Label::B,
            ),
            (
                LinePath::new(vec![
                    P2::new(0.5, 0.0),
                    P2::new(0.5, 0.5),
                    P2::new(1.0, 0.5),
                ]).unwrap(),
                Label::B,
            ),
            (
                LinePath::new(vec![P2::new(1.0, 0.5), P2::new(1.5, 0.5)]).unwrap(),
                Label::B,
            ),
        ]
    )
}