ase2ttf_core 0.2.0

ase2ttf core crate
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
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
use std::collections::{HashMap, HashSet};

type Point = (usize, usize);
type Line = (Point, Point);

struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        UnionFind {
            parent: (0..n).collect(),
            rank: vec![0; n],
        }
    }

    fn find(&mut self, i: usize) -> usize {
        if self.parent[i] == i {
            return i;
        }
        self.parent[i] = self.find(self.parent[i]);
        self.parent[i]
    }

    fn union(&mut self, i: usize, j: usize) -> bool {
        let root_i = self.find(i);
        let root_j = self.find(j);

        if root_i != root_j {
            if self.rank[root_i] < self.rank[root_j] {
                self.parent[root_i] = root_j;
            } else if self.rank[root_i] > self.rank[root_j] {
                self.parent[root_j] = root_i;
            } else {
                self.parent[root_j] = root_i;
                self.rank[root_i] += 1;
            }
            true
        } else {
            false
        }
    }
}

fn group(grid: &[f64], width: usize, height: usize) -> HashMap<usize, Vec<usize>> {
    if width == 0 || height == 0 {
        return HashMap::new();
    }

    let n_cells = width * height;
    let mut uf = UnionFind::new(n_cells);

    for x in 0..width {
        for y in 0..height {
            let current_idx = x + y * width;
            if grid[current_idx] > 0.0 {
                // right
                if x + 1 < width {
                    let right_idx = current_idx + 1;
                    if grid[right_idx] > 0.0 {
                        uf.union(current_idx, right_idx);
                    }
                }

                // bottom
                if y + 1 < height {
                    let bottom_idx = current_idx + width;
                    if grid[bottom_idx] > 0.0 {
                        uf.union(current_idx, bottom_idx);
                    }
                }
            }
        }
    }

    let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
    for i in 0..n_cells {
        if grid[i] > 0.0 {
            let root = uf.find(i);
            groups.entry(root).or_default().push(i);
        }
    }

    groups
}

pub fn get_edges(grid: &[f64], width: usize, height: usize) -> HashMap<usize, Vec<Line>> {
    let group_map = group(&grid, width, height);
    let mut group_boundaries: HashMap<usize, Vec<Line>> = HashMap::new();

    for (root_id, indices) in group_map.iter() {
        let mut lines: Vec<Line> = Vec::new();

        for &idx in indices {
            let x = idx % width;
            let y = idx / width;

            // top
            if y == 0 || grid[idx - width] == 0.0 {
                lines.push(((x, y), (x + 1, y)));
            }
            // bottom
            if y == height - 1 || grid[idx + width] == 0.0 {
                lines.push(((x, y + 1), (x + 1, y + 1)));
            }
            // left
            if x == 0 || grid[idx - 1] == 0.0 {
                lines.push(((x, y), (x, y + 1)));
            }
            // right
            if x == width - 1 || grid[idx + 1] == 0.0 {
                lines.push(((x + 1, y), (x + 1, y + 1)));
            }
        }

        // remove duplicate boundary segments
        let mut unique_boundaries = HashSet::new();
        for line in lines {
            let normalized_line = if line.0 <= line.1 {
                line
            } else {
                (line.1, line.0)
            };
            unique_boundaries.insert(normalized_line);
        }

        group_boundaries.insert(*root_id, unique_boundaries.into_iter().collect());
    }

    let mut root_to_id: HashMap<usize, usize> = HashMap::new();
    let mut next_id = 1;

    let mut result: HashMap<usize, Vec<Line>> = HashMap::new();

    for (root, boundaries) in group_boundaries {
        let entry = root_to_id.entry(root).or_insert_with(|| {
            let id = next_id;
            next_id += 1;
            id
        });
        result.insert(*entry, boundaries);
    }

    result
}

pub fn edges_to_paths(edges: &Vec<Line>) -> Vec<Vec<Point>> {
    let mut point_to_edges: HashMap<Point, Vec<Point>> = HashMap::new();
    let mut edge_set: HashSet<Line> = HashSet::new();

    for &(a, b) in edges {
        point_to_edges.entry(a).or_default().push(b);
        point_to_edges.entry(b).or_default().push(a);
        edge_set.insert(if a <= b { (a, b) } else { (b, a) });
    }

    let mut paths = Vec::new();
    let mut used = HashSet::new();

    for &(start, end) in edges {
        let key = if start <= end {
            (start, end)
        } else {
            (end, start)
        };
        if used.contains(&key) {
            continue;
        }
        let mut path = Vec::new();
        let mut curr = end;
        path.push(start);
        used.insert(key);
        while curr != start {
            path.push(curr);
            let neighbors = &point_to_edges[&curr];
            let mut found = false;
            for &next in neighbors {
                let k = if curr <= next {
                    (curr, next)
                } else {
                    (next, curr)
                };
                if !used.contains(&k) && edge_set.contains(&k) {
                    used.insert(k);
                    curr = next;
                    found = true;
                    break;
                }
            }
            if !found {
                break; // not closed
            }
        }

        // separate inner loop
        let mut visited_point = HashMap::new();
        let mut l = path.len();
        let mut i = 0;
        while i < l - 1 {
            let insert_ret = visited_point.insert(path[i], i);
            if let Some(p) = insert_ret {
                paths.push(path.drain(p..i).rev().collect());
                l = path.len();
            }
            i += 1;
        }

        // only closed paths
        if path.len() > 2 && path[0] == *path.last().unwrap() {
            paths.push(path);
        } else if path.len() > 2 {
            path.push(path[0]);
            paths.push(path);
        }
    }

    for path in paths.iter_mut() {
        simplify_collinear_points(path);
    }

    let n = paths.len();
    for i in 0..n {
        let mut inside_count = 0;
        for j in 0..n {
            if i == j || paths[j].is_empty() {
                continue;
            }
            if point_in_polygon(paths[i][0], &paths[j]) {
                inside_count += 1;
            }
        }

        let area = signed_area(&paths[i]);
        if inside_count % 2 == 1 {
            if area < 0.0 {
                paths[i].reverse();
            }
        } else {
            if area > 0.0 {
                paths[i].reverse();
            }
        }
    }
    paths
}

fn simplify_collinear_points(path: &mut Vec<Point>) {
    if path.len() <= 4 {
        return;
    }

    let is_closed = path[0] == *path.last().unwrap();
    if !is_closed {
        path.dedup_by(|a, b| a == b);
        if path.len() <= 2 {
            return;
        }

        let mut simplified = Vec::with_capacity(path.len());
        simplified.push(path[0]);
        for window in path.windows(3) {
            if !is_collinear(window[0], window[1], window[2]) {
                simplified.push(window[1]);
            }
        }
        simplified.push(*path.last().unwrap());
        *path = simplified;
        return;
    }

    let mut vertices = path[..path.len() - 1].to_vec();
    vertices.dedup_by(|a, b| a == b);
    if vertices.len() <= 2 {
        return;
    }

    let mut simplified = Vec::with_capacity(vertices.len() + 1);
    for i in 0..vertices.len() {
        let prev = vertices[(i + vertices.len() - 1) % vertices.len()];
        let curr = vertices[i];
        let next = vertices[(i + 1) % vertices.len()];
        if !is_collinear(prev, curr, next) {
            simplified.push(curr);
        }
    }

    if simplified.len() >= 3 {
        simplified.push(simplified[0]);
        *path = simplified;
    }
}

fn is_collinear(a: Point, b: Point, c: Point) -> bool {
    let ab_x = b.0 as isize - a.0 as isize;
    let ab_y = b.1 as isize - a.1 as isize;
    let bc_x = c.0 as isize - b.0 as isize;
    let bc_y = c.1 as isize - b.1 as isize;
    ab_x * bc_y == ab_y * bc_x
}

fn point_in_polygon(point: Point, polygon: &[Point]) -> bool {
    let (x, y) = (point.0 as isize, point.1 as isize);
    let mut inside = false;
    let n = polygon.len();
    for i in 0..n {
        let (x0, y0) = (polygon[i].0 as isize, polygon[i].1 as isize);
        let (x1, y1) = (
            polygon[(i + 1) % n].0 as isize,
            polygon[(i + 1) % n].1 as isize,
        );
        if (y0 > y) != (y1 > y) {
            let denom = y1 - y0;
            if denom == 0 {
                continue;
            }
            let intersect_x = (x1 - x0) * (y - y0) / denom + x0;
            if x < intersect_x {
                inside = !inside;
            }
        }
    }
    inside
}

fn signed_area(path: &[Point]) -> f64 {
    let n = path.len();
    let mut area = 0.0;
    for i in 0..n {
        let (x0, y0) = (path[i].0 as f64, path[i].1 as f64);
        let (x1, y1) = (path[(i + 1) % n].0 as f64, path[(i + 1) % n].1 as f64);
        area += (x0 * y1) - (x1 * y0);
    }
    area * 0.5
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sandbox() {
        let (grid, width, height) = parse_grid(
            "
--##--
-##---
##----
-##---
--##--
",
        );

        println!("Group:");
        println!("{:?}", group(&grid, width, height));

        let boundaries = get_edges(&grid, width, height);
        let paths = edges_to_paths(&Vec::from_iter(boundaries.into_values().flatten()));

        println!("Path:");
        println!("{:?}", paths);

        assert_eq!(paths.len(), 1);

        let areas: Vec<_> = paths.iter().map(|p| signed_area(p)).collect();
        assert_eq!(areas.iter().filter(|&a| *a < 0.0).count(), 1);
        assert_eq!(areas.iter().filter(|&a| *a > 0.0).count(), 0);
    }

    #[test]
    fn edges_to_paths_removes_collinear_points_from_rectangle() {
        let paths = paths_from_grid(
            "
###
###
",
        );

        assert_eq!(
            normalize_closed_path(&paths[0]),
            vec![(0, 0), (0, 2), (3, 2), (3, 0), (0, 0)]
        );
    }

    #[test]
    fn edges_to_paths_keeps_corner_points() {
        let paths = paths_from_grid(
            "
#-
##
",
        );

        assert_eq!(
            normalize_closed_path(&paths[0]),
            vec![(0, 0), (0, 2), (2, 2), (2, 1), (1, 1), (1, 0), (0, 0)]
        );
    }

    #[test]
    fn edges_to_paths_removes_collinear_points_from_single_row() {
        let paths = paths_from_grid(
            "
####
",
        );

        assert_eq!(
            normalize_closed_path(&paths[0]),
            vec![(0, 0), (0, 1), (4, 1), (4, 0), (0, 0)]
        );
    }

    #[test]
    fn edges_to_paths_removes_collinear_points_from_single_column() {
        let paths = paths_from_grid(
            "
#
#
#
",
        );

        assert_eq!(
            normalize_closed_path(&paths[0]),
            vec![(0, 0), (0, 3), (1, 3), (1, 0), (0, 0)]
        );
    }

    #[test]
    fn edges_to_paths_keeps_stair_step_corners() {
        let paths = paths_from_grid(
            "
#--
##-
###
",
        );

        assert_eq!(
            normalize_closed_path(&paths[0]),
            vec![
                (0, 0),
                (0, 3),
                (3, 3),
                (3, 2),
                (2, 2),
                (2, 1),
                (1, 1),
                (1, 0),
                (0, 0),
            ]
        );
    }

    #[test]
    fn edges_to_paths_handles_hole_with_simplified_outer_and_inner_paths() {
        let paths = paths_from_grid(
            "
###
#-#
###
",
        );

        assert_eq!(paths.len(), 2);

        let mut normalized_paths: Vec<_> = paths
            .iter()
            .map(|path| normalize_closed_path(path))
            .collect();
        normalized_paths.sort();

        assert_eq!(
            normalized_paths,
            vec![
                vec![(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)],
                vec![(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)],
            ]
        );
    }

    #[test]
    fn edges_to_paths_keeps_disconnected_rectangles_separate() {
        let paths = paths_from_grid(
            "
##-#
##-#
",
        );

        assert_eq!(paths.len(), 2);

        let mut normalized_paths: Vec<_> = paths
            .iter()
            .map(|path| normalize_closed_path(path))
            .collect();
        normalized_paths.sort();

        assert_eq!(
            normalized_paths,
            vec![
                vec![(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)],
                vec![(3, 0), (3, 2), (4, 2), (4, 0), (3, 0)],
            ]
        );
    }

    fn paths_from_grid(src: &str) -> Vec<Vec<Point>> {
        let (grid, width, height) = parse_grid(src);
        let boundaries = get_edges(&grid, width, height);
        edges_to_paths(&Vec::from_iter(boundaries.into_values().flatten()))
    }

    fn parse_grid(src: &str) -> (Vec<f64>, usize, usize) {
        let rows: Vec<_> = src.trim().lines().map(str::trim).collect();
        let height = rows.len();
        let width = rows.first().map(|row| row.len()).unwrap_or(0);
        assert!(rows.iter().all(|row| row.len() == width));

        let grid = rows
            .iter()
            .flat_map(|row| {
                row.as_bytes()
                    .iter()
                    .map(|x| if *x == b'#' { 1.0f64 } else { 0.0 })
            })
            .collect();

        (grid, width, height)
    }

    fn normalize_closed_path(path: &[Point]) -> Vec<Point> {
        let vertices = &path[..path.len() - 1];
        let start = vertices
            .iter()
            .enumerate()
            .min_by_key(|(_, point)| *point)
            .map(|(i, _)| i)
            .unwrap();
        let mut normalized = Vec::with_capacity(path.len());
        normalized.extend(vertices[start..].iter().copied());
        normalized.extend(vertices[..start].iter().copied());
        normalized.push(normalized[0]);
        normalized
    }
}