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
//! This library implements a wrapper for the poly2tri C++ implementation
//! of the constrained Delaunay triangulation.
extern crate libc;

use std::mem;
use libc::{c_void, c_int, size_t};


#[link(name="poly2tri")]
extern "C" {
    fn p2t_polyline_new() -> *mut c_void;
    fn p2t_polyline_free(polygon: *mut c_void);
    fn p2t_polyline_add_point(polygon: *mut c_void, x: f64, y: f64);
    fn p2t_polyline_get_point(polygon: *mut c_void, idx: size_t,
                              x_out: *mut f64, y_out: *mut f64) -> c_int;
    fn p2t_polyline_size(polygon: *const c_void) -> size_t;

    fn p2t_cdt_new(polygon: *mut c_void) -> *mut c_void;
    fn p2t_cdt_free(cdt: *mut c_void);
    fn p2t_cdt_triangulate(cdt: *mut c_void);
    fn p2t_cdt_get_triangles(cdt: *mut c_void) -> *mut c_void;
    fn p2t_cdt_add_hole(cdt: *mut c_void, polygon: *mut c_void);
    fn p2t_cdt_add_point(cdt: *mut c_void, x: f64, y: f64);

    fn p2t_triangles_free(triangles: *mut c_void);
    fn p2t_triangles_count(triangles: *mut c_void) -> size_t;
    fn p2t_triangles_get_triangle(triangles: *const c_void, idx: size_t) -> *const c_void;

    fn p2t_triangle_get_point(triangle: *const c_void, idx: size_t,
                              x_out: *mut f64, y_out: *mut f64);
}

/// Basic polygon interface
pub struct Polygon {
    ll: *mut c_void,
}

/// The Constrained Delaunay triangulation state
pub struct CDT {
    ll: *mut c_void,
}

/// An immutable vector of triangles
pub struct TriangleVec {
    ll: *mut c_void,

    // hold on to the cdt until we no longer need the triangle vector
    #[allow(dead_code)]
    cdt: CDT,
}

/// A single triangle
#[derive(Copy, Clone, PartialEq)]
pub struct Triangle {
    pub points: [[f64; 2]; 3],
}


/// This struct implements a polygon.  Note that this is currently
/// a wrapper around a c library and as such it's bubbles through
/// some of the underlying implementation details such as panicking
/// on duplicated points.
impl Polygon {

    /// Creates a new empty polygon.
    pub fn new() -> Polygon {
        unsafe {
            Polygon {
                ll: p2t_polyline_new()
            }
        }
    }

    /// Creates a polygon from an iterator of points.
    pub fn from_iterator<'a, I>(points: I) -> Polygon
        where I: Iterator<Item=&'a [f64; 2]>
    {
        let mut rv = Polygon::new();
        for point in points {
            rv.add_point(point[0], point[1]);
        }
        rv
    }

    /// Adds a single point to the polygon.  These points must not
    /// be repeated!
    pub fn add_point(&mut self, x: f64, y: f64) {
        unsafe {
            p2t_polyline_add_point(self.ll, x, y);
        }
    }

    /// Looks up a point at a certain index.
    pub fn get_point(&self, idx: usize) -> [f64; 2] {
        unsafe {
            let mut x: f64 = 0.0;
            let mut y: f64 = 0.0;
            if p2t_polyline_get_point(self.ll, idx as size_t, &mut x, &mut y) == 0 {
                [x, y]
            } else {
                panic!("Out of range");
            }
        }
    }

    /// Returns the size of the polygon (number of points).
    pub fn size(&self) -> usize {
        unsafe {
            p2t_polyline_size(self.ll) as usize
        }
    }
}

impl Drop for Polygon {

    fn drop(&mut self) {
        unsafe {
            p2t_polyline_free(self.ll);
        }
    }
}


/// This holds the basic state of the constrained Delaunay triangulation
/// algorithm.  Once the triangulation was kicked off the triangles are
/// returned and this no longer has a purpose.
impl CDT {

    /// Creates a new constrained Delaunay triangulation from a polygon.
    pub fn new(polygon: Polygon) -> CDT {
        unsafe {
            let rv = CDT {
                ll: p2t_cdt_new(polygon.ll)
            };
            mem::forget(polygon);
            rv
        }
    }

    /// Adds a hole into the CDT.
    pub fn add_hole(&mut self, polygon: Polygon) {
        unsafe {
            p2t_cdt_add_hole(self.ll, polygon.ll);
            mem::forget(polygon);
        }
    }

    /// Adds a steiner point to the CDT.
    pub fn add_steiner_point(&mut self, x: f64, y: f64) {
        unsafe {
            p2t_cdt_add_point(self.ll, x, y);
        }
    }

    /// Triangulates the polygon.
    pub fn triangulate(self) -> TriangleVec {
        unsafe {
            p2t_cdt_triangulate(self.ll);
            let ll = p2t_cdt_get_triangles(self.ll);
            TriangleVec {
                cdt: self,
                ll: ll,
            }
        }
    }
}

impl Drop for CDT {

    fn drop(&mut self) {
        unsafe {
            p2t_cdt_free(self.ll);
        }
    }
}


/// Implements a read only interface to a triangle vector.
impl TriangleVec {

    /// The number of triangles.
    pub fn size(&self) -> usize {
        unsafe {
            p2t_triangles_count(self.ll) as usize
        }
    }

    /// Returns a copy of the triangle at a certain point.
    pub fn get_triangle(&self, idx: usize) -> Triangle {
        assert!(idx < self.size(), "Out of range");
        let mut p0 = [0.0; 2];
        let mut p1 = [0.0; 2];
        let mut p2 = [0.0; 2];
        unsafe {
            let tri = p2t_triangles_get_triangle(self.ll, idx as size_t);
            p2t_triangle_get_point(tri, 0, &mut p0[0], &mut p0[1]);
            p2t_triangle_get_point(tri, 1, &mut p1[0], &mut p1[1]);
            p2t_triangle_get_point(tri, 2, &mut p2[0], &mut p2[1]);
        }
        Triangle {
            points: [p0, p1, p2]
        }
    }
}

impl Drop for TriangleVec {

    fn drop(&mut self) {
        unsafe {
            p2t_triangles_free(self.ll);
        }
    }
}

/// Triangulates an iterator of points.  This is a shortcut
/// for the most common operation.
pub fn triangulate_points<'a, I>(points: I) -> TriangleVec
    where I: Iterator<Item=&'a [f64; 2]>
{
    CDT::new(Polygon::from_iterator(points)).triangulate()
}


#[test]
fn test_basics() {
    let mut polygon = Polygon::new();
    let min = 0.01f64;
    let max = 2.50f64;
    polygon.add_point(min, min);
    polygon.add_point(min, max);
    polygon.add_point(max, max);
    polygon.add_point(max, min);
    assert_eq!(polygon.size(), 4);

    let cdt = CDT::new(polygon);
    let triangles = cdt.triangulate();
    assert_eq!(triangles.size(), 2);

    let tri = triangles.get_triangle(0);
    assert_eq!(tri.points[0], [min, max]);
    assert_eq!(tri.points[1], [max, min]);
    assert_eq!(tri.points[2], [max, max]);

    let tri = triangles.get_triangle(1);
    assert_eq!(tri.points[0], [min, max]);
    assert_eq!(tri.points[1], [min, min]);
    assert_eq!(tri.points[2], [max, min]);
}

#[test]
fn test_iter() {
    let points : [[f64; 2]; 4] = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
    let triangles = triangulate_points(points.into_iter());
    assert_eq!(triangles.size(), 2);
}