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
use rin_math::{
    Pnt2, zero, clamp, map, lerp, AsVec, ToVec, ToPnt,
    RealField, distance, distance_squared, Vec2, one, iwrap, NumCast, cast,
};
use std::ops::Index;
use std::convert::AsRef;
use std::slice;
use std::iter::IntoIterator;
use std::fmt::Debug;
use super::Polyline;

/// An open or closed collection of vertices that
/// represents a polyline or polygon
///
/// Has methods to do calculations over such geometrical
/// shapes
///
/// This type doesn't own the points and is usually a view on
/// a `PolylineSlice`
#[derive(Clone, Debug, Copy)]
pub struct PolylineSlice<'a, T: RealField + Debug + 'static = f32>{
    points: &'a [Pnt2<T>],
    closed: bool
}

impl<'a, T: RealField + NumCast> PolylineSlice<'a, T>{
    /// creates a new polyline from the vector of points that must be ordered for the polyline
    /// methods to work correctly
    pub fn new(points: &[Pnt2<T>], closed: bool) -> PolylineSlice<T>{
        PolylineSlice{points: points, closed: closed}
    }

    /// returns the area of the polygon, only works if the polyline represents
    /// a polygon
    pub fn area(&self) -> T{
        let mut area: T = zero();
        for i in 0 .. self.len()-1{
            area = area + (self.points[i].x * self.points[i+1].y - self.points[i+1].x * self.points[i].y);
        }
        area = area + (self.points[self.len()-1].x * self.points[0].y - self.points[0].x * self.points[self.len()-1].y);
        area = area * cast(0.5).unwrap();
        area
    }

    /// centroid of the polyline, should work for any collection of points
    /// although it will only make sense if it's a polygon
    pub fn centroid(&self) -> Pnt2<T>{
        let mut centroid = Pnt2::origin();
        if self.points.len()<3{
            return centroid;
        }

        let area = self.area();

        for i in 0 .. self.len()-1{
            let p = self.points[i];
            let next_p = self.points[i+1];
            centroid.x = centroid.x + ((p.x + next_p.x) * (p.x*next_p.y - next_p.x*p.y));
            centroid.y = centroid.y + ((p.y + next_p.y) * (p.x*next_p.y - next_p.x*p.y));
        }

        let p = self.points.last().unwrap();
        let next_p = self.points[0];
        centroid.x = centroid.x + ((p.x + next_p.x) * (p.x*next_p.y - next_p.x*p.y));
        centroid.y = centroid.y + ((p.y + next_p.y) * (p.x*next_p.y - next_p.x*p.y));

        let six: T = cast(6.0).unwrap();
        centroid.x = centroid.x / (six*area);
        centroid.y = centroid.y / (six*area);
        centroid
    }

    /// mark this polyline as being a closed shape, although not necesarily a
    /// polygon. Any rendering or calculation will take into account that the
    /// first and last points are joined
    pub fn close(&mut self){
        self.closed = true;
    }

    /// returns true if the polyline is closed
    pub fn is_closed(&self) -> bool{
        self.closed
    }

    /// returns total number of points
    pub fn len(&self) -> usize{
        self.points.len()
    }

    pub fn to_owned(&self) -> Polyline<T> {
        Polyline { points: self.points.to_vec(), closed: self.closed }
    }

    /// Returns a smoothed version of the polyline.
	///
	/// `window_size` is the size of the smoothing window. So if
	/// `window_size` is 2, then 2 points from the left, 1 in the center,
	/// and 2 on the right (5 total) will be used for smoothing each point.
    ///
	/// `window_shape` describes whether to use a triangular window (0) or
	/// box window (1) or something in between (for example, .5).
    pub fn smoothed(&self, window_size: usize, window_shape: T) -> Polyline<T>{
        let n = self.points.len();
        let size = clamp(window_size, 0, n);
        let shape = clamp(window_shape, zero(), one());

        let weights = (0..size).map(|i| map(cast(i).unwrap(), zero(), cast(size).unwrap(), one(), shape))
            .collect::<Vec<_>>();

        let mut result = self.to_owned();
        for i in 0..n {
            let mut sum: T = one();
            for j in 1..size{
                let mut cur = Pnt2::origin();
                let mut left = i as isize - j as isize;
                let mut right = i + j;
                if left < 0 && self.closed{
                    left += n as isize;
                }
                if left >= 0 {
                    cur += self.points[left as usize].as_vec();
                    sum += weights[j];
                }
                if right > n && self.closed {
                    right -= n;
                }
                if right < n{
                    cur += self.points[right].as_vec();
                    sum += weights[j];
                }
                result[i] += cur.as_vec() * weights[j];
            }
            result[i] /= sum;
        }

        result
    }

    pub fn subdivide_linear(&self, resolution: usize) -> Polyline<T>{
        let points = self.points.windows(2).enumerate()
            .flat_map(|(segment, current_next)| (0..resolution).map(move |i|{
                let i_f: T = cast(i).unwrap();
                let t: T = i_f / if segment == self.points.len() - 2{
                    cast(resolution - 1).unwrap()
                }else{
                    cast(resolution).unwrap()
                };
                lerp(current_next[0].to_vec(), current_next[1].to_vec(), t).to_pnt()
            }));

        Polyline {
            points: points.collect(),
            closed: self.closed
        }
    }

    pub fn iter(&self) -> slice::Iter<Pnt2<T>>{
        self.points.iter()
    }

    pub fn first(&self) -> Option<&Pnt2<T>>{
        self.points.first()
    }

    pub fn last(&self) -> Option<&Pnt2<T>>{
        self.points.last()
    }

    pub fn is_empty(&self) -> bool {
        self.points.is_empty()
    }

    /// Returns the point at an index + a normalized pct
    pub fn lerped_point_at(&self, fidx: T) -> Option<Pnt2<T>>{
        let idx1 = fidx.floor();
        let pct = fidx - idx1;
        let idx1 = self.wrap_index(cast(idx1).unwrap())?;
        let idx2 = self.wrap_index(idx1 as isize + 1)?;
        Some(lerp(self[idx1].to_vec(), self[idx2].to_vec(), pct).to_pnt())
    }

    /// Returns the length of the segment at the passed index
    /// or None if such segment doesn't exist
    pub fn segment_length(&self, idx: usize) -> Option<T>{
        let idx2 = self.wrap_index(idx as isize + 1)?;
        let p1 = self.points.get(idx)?;
        let p2 = self.points.get(idx2)?;
        Some(distance(p2, p1))
    }

    /// Returns the square length of the segment at the passed index
    /// or None if such segment doesn't exist
    pub fn segment_length_squared(&self, idx: usize) -> Option<T>{
        let idx2 = self.wrap_index(idx as isize + 1)?;
        let p1 = self.points.get(idx)?;
        let p2 = self.points.get(idx2)?;
        Some(distance_squared(p2, p1))
    }

    /// Returns an index wrapped around a closed polygon or clamped
    /// on a polyline. Will return None if the polyline is empty
    pub fn wrap_index(&self, idx: isize) -> Option<usize> {
        if self.is_empty() {
            None
        } else if self.is_closed() {
            Some(iwrap(idx, 0, self.points.len() as isize) as usize)
        } else {
            Some(clamp(idx, 0, self.points.len() as isize - 1) as usize)
        }
    }

    /// Finds the next segment which length is different than 0
    /// starting from the passed index and wrapping around on
    /// closed polygons
    pub fn next_non_zero_segment(&self, idx: usize) -> Option<usize>{
        let mut next_idx = self.wrap_index(idx as isize)?;
        loop {
            let segment_length = self.segment_length_squared(next_idx);
            if segment_length.map(|s| s > zero()).unwrap_or(false) {
                return Some(next_idx)
            }else if next_idx < self.len() - 1 {
                next_idx += 1;
            }else if self.is_closed(){
                next_idx = self.wrap_index(next_idx as isize + 1).unwrap();
            }else{
                return None;
            }
            if next_idx != idx {
                return None
            }
        }
    }

    /// Finds the previous segment which length is different than 0
    /// starting from the passed index and wrapping around on
    /// closed polygons
    pub fn prev_non_zero_segment(&self, idx: usize) -> Option<usize>{
        let mut next_idx = self.wrap_index(idx as isize - 1)?;
        while next_idx != idx {
            let segment_length = self.segment_length_squared(next_idx);
            if segment_length.map(|s| s > zero()).unwrap_or(false) {
                return Some(next_idx)
            }else if next_idx > 0 {
                next_idx -= 1;
            }else if self.is_closed(){
                next_idx = self.wrap_index(next_idx as isize - 1).unwrap();
            }else{
                return None;
            }
        }
        None
    }
}

impl<'a, T: NumCast + RealField> PolylineSlice<'a, T>{
    /// Tangent at the point in the passed index if it exists
    pub fn tangent_at(&self, idx: usize) -> Option<Vec2<T>>{
        let idx1 = self.prev_non_zero_segment(idx);
        let idx2 = self.wrap_index(idx as isize)?;
        let idx3 = self.next_non_zero_segment(idx + 1);

        let p2 = &self[idx2];
        match (idx1, idx3) {
            (Some(idx1), Some(idx3)) => {
                let p1 = &self[idx1];
                let p3 = &self[idx3];
                let v1 = (p1 - p2).normalize();
                let v2 = (p3 - p2).normalize();
                let tangent = if (v2 - v1).norm_squared() > zero() {
                    (v2 - v1).normalize()
                }else{
                    -v1
                };
                Some(tangent)
            }
            (Some(idx1), None) => {
                let p1 = &self[idx1];
                Some((p2 - p1).normalize())
            }
            (None, Some(idx3)) => {
                let p3 = &self[idx3];
                Some((p3 - p2).normalize())
            }
            _ => None
        }
    }

    /// Tangent at the lerped point at the passed index + normalized pct
    pub fn lerped_tangent_at(&self, fidx: T) -> Option<Vec2<T>>{
        let idx1 = fidx.floor();
        let pct = fidx - idx1;
        let idx1 = self.wrap_index(cast(idx1).unwrap())?;
        let idx2 = self.wrap_index(idx1 as isize + 1)?;
        Some(lerp(self.tangent_at(idx1)?, self.tangent_at(idx2)?, pct))
    }
}

impl<'a, T: RealField> AsRef<[Pnt2<T>]> for PolylineSlice<'a, T>{
	fn as_ref(&self) -> &[Pnt2<T>]{
		self.points.as_ref()
	}
}

impl<'a, T: RealField> Index<usize> for PolylineSlice<'a, T>{
	type Output = Pnt2<T>;
    fn index(&self, idx: usize) -> &Pnt2<T>{
        self.points.index(idx)
    }
}

impl<'a, T: RealField> IntoIterator for PolylineSlice<'a, T>{
    type Item = &'a Pnt2<T>;
    type IntoIter = slice::Iter<'a, Pnt2<T>>;
    fn into_iter(self) -> slice::Iter<'a, Pnt2<T>>{
        self.points.into_iter()
    }
}

impl<'a, T> Into<&'a [Pnt2<T>]> for PolylineSlice<'a, T>
    where T: RealField
{
    fn into(self) -> &'a [Pnt2<T>]{
        self.points
    }
}