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
//! This crate is a tiny utility library for finding the intersection two 2D line segments, rays,
//! or complete lines. You'll need the `geo` crate to use this crate, because this library uses
//! `geo`'s data structures.
//!
//! To use this library, construct a `LineSegment<T: num_traits::Float>` and `relate` it with
//! another `LineSegment`. This will return a `LineRelation<T>`, which covers all the possible
//! relations between those two lines.
//!
//! `LineRelation<T>` provides `unique_intersection`, if all you care about is finding a unique
//! intersection, and (for example) you don't care to distinguish cases where there are zero or an
//! infinite number of intersections.
//!
//! Here's an example of usage:
//!
//! ```
//! extern crate geo;
//! extern crate line_intersection;
//!
//! fn main() {
//!     // find the intersection of a line segment and an infinite line
//!     use line_intersection::{LineInterval, LineRelation};
//!     use geo::{Coordinate, Line, Point};
//!
//!     let segment = LineInterval::line_segment(Line {
//!         start: (0.0, 0.0).into(),
//!         end: (3.0, 3.0).into(),
//!     });
//!
//!     let line = LineInterval::line(Line {
//!         start: (2.0, 0.0).into(),
//!         end: (2.0, 0.1).into(),
//!     });
//!
//!     let intersection = segment.relate(&line).unique_intersection();
//!     assert_eq!(Some(Point(Coordinate { x: 2.0, y: 2.0 })), intersection);
//! }
//! ```

extern crate geo;
extern crate num_traits;

use geo::{Line, Point};
use num_traits::Float;

/// An interval (continuous subset) of a line.
///
/// `interval_of_intersection` represents what subset of a line this `LineInterval` represents. If
/// `interval_of_intersection` is `[-Infinity, Infinity]`, then it's a line going through
/// `line.start` and `line.end`; if it's `[0, Infinity]` it's a ray, starting at `line.start`
/// extending infinitely in the direction of `line.end` and beyond; if it's `[0, 1]`, it's a line
/// segment from `line.from` to `line.end`.
///
/// It should always be the case that `interval_of_intersection.0 < interval_of_intersection.1`,
/// unless you want a degenerate line that cannot be intersected.
#[derive(Debug, PartialEq)]
pub struct LineInterval<T: Float> {
    pub line: Line<T>,
    pub interval_of_intersection: (T, T),
}

/// The relationship between two line segments.
#[derive(Debug, PartialEq)]
pub enum LineRelation<T: Float> {
    /// The line intervals are not parallel (or anti-parallel), and "meet" each other at exactly
    /// one point.
    DivergentIntersecting(Point<T>),
    /// The line intervals are not parallel (or anti-parallel), and do not intersect; they "miss"
    /// each other.
    DivergentDisjoint,
    /// The line intervals lie on the same line. They may or may not overlap, and this intersection
    /// is possibly infinite.
    Collinear,
    /// The line intervals are parallel or anti-parallel.
    Parallel,
}

impl<T: Float> LineRelation<T> {
    pub fn unique_intersection(self) -> Option<Point<T>> {
        match self {
            LineRelation::DivergentIntersecting(p) => Some(p),
            _ => None,
        }
    }
}

impl<T: Float> LineInterval<T> {
    pub fn line_segment(line: Line<T>) -> LineInterval<T> {
        LineInterval {
            line: line,
            interval_of_intersection: (T::zero(), T::one()),
        }
    }

    pub fn ray(line: Line<T>) -> LineInterval<T> {
        LineInterval {
            line: line,
            interval_of_intersection: (T::zero(), T::infinity()),
        }
    }

    pub fn line(line: Line<T>) -> LineInterval<T> {
        LineInterval {
            line: line,
            interval_of_intersection: (T::neg_infinity(), T::infinity()),
        }
    }

    /// Get the relationship between this line segment and another.
    pub fn relate(&self, other: &LineInterval<T>) -> LineRelation<T> {
        // see https://stackoverflow.com/a/565282
        let p = self.line.start;
        let q = other.line.start;
        let r = self.line.end - self.line.start;
        let s = other.line.end - other.line.start;

        let r_cross_s = Self::cross(&r, &s);
        let q_minus_p = q - p;
        let q_minus_p_cross_r = Self::cross(&q_minus_p, &r);

        // are the lines are parallel?
        if r_cross_s == T::zero() {
            // are the lines collinear?
            if q_minus_p_cross_r == T::zero() {
                // the lines are collinear
                LineRelation::Collinear
            } else {
                // the lines are parallel but not collinear
                LineRelation::Parallel
            }
        } else {
            // the lines are not parallel
            let t = Self::cross(&q_minus_p, &Self::div(&s, r_cross_s));
            let u = Self::cross(&q_minus_p, &Self::div(&r, r_cross_s));

            // are the intersection coordinates both in range?
            let t_in_range = self.interval_of_intersection.0 <= t &&
                t <= self.interval_of_intersection.1;
            let u_in_range = other.interval_of_intersection.0 <= u &&
                u <= other.interval_of_intersection.1;

            if t_in_range && u_in_range {
                // there is an intersection
                LineRelation::DivergentIntersecting(Self::t_coord_to_point(&p, &r, t))
            } else {
                // there is no intersection
                LineRelation::DivergentDisjoint
            }
        }
    }

    fn cross(a: &Point<T>, b: &Point<T>) -> T {
        a.x() * b.y() - a.y() * b.x()
    }

    fn div(a: &Point<T>, b: T) -> Point<T> {
        (a.x() / b, a.y() / b).into()
    }

    fn t_coord_to_point(p: &Point<T>, r: &Point<T>, t: T) -> Point<T> {
        (p.x() + t * r.x(), p.y() + t * r.y()).into()
    }
}

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

    #[test]
    fn divergent_intersecting_segments() {
        let a = Line {
            start: (1.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let b = Line {
            start: (0.0, 0.0).into(),
            end: (2.0, 0.5).into(),
        };
        let s1 = LineInterval::line_segment(a);
        let s2 = LineInterval::line_segment(b);
        let relation = LineRelation::DivergentIntersecting((1.0, 0.25).into());

        assert_eq!(relation, s1.relate(&s2));
        assert_eq!(relation, s2.relate(&s1));
    }

    #[test]
    fn divergent_intersecting_segment_and_ray() {
        let a = Line {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let b = Line {
            start: (2.0, 0.0).into(),
            end: (2.0, 3.0).into(),
        };
        let s1 = LineInterval::ray(a);
        let s2 = LineInterval::line_segment(b);
        let relation = LineRelation::DivergentIntersecting((2.0, 2.0).into());

        assert_eq!(relation, s1.relate(&s2));
        assert_eq!(relation, s2.relate(&s1));
    }

    #[test]
    fn divergent_disjoint_segments() {
        let a = Line {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let b = Line {
            start: (3.0, 0.0).into(),
            end: (0.0, 3.0).into(),
        };
        let s1 = LineInterval::line_segment(a);
        let s2 = LineInterval::line_segment(b);
        let relation = LineRelation::DivergentDisjoint;

        assert_eq!(relation, s1.relate(&s2));
        assert_eq!(relation, s2.relate(&s1));
    }

    #[test]
    fn divergent_disjoint_ray_and_line() {
        let a = Line {
            start: (1.0, 1.0).into(),
            end: (0.0, 0.0).into(),
        };
        let b = Line {
            start: (3.0, 0.0).into(),
            end: (0.0, 3.0).into(),
        };
        let s1 = LineInterval::ray(a);
        let s2 = LineInterval::line(b);
        let relation = LineRelation::DivergentDisjoint;

        assert_eq!(relation, s1.relate(&s2));
        assert_eq!(relation, s2.relate(&s1));
    }

    #[test]
    fn parallel_disjoint_segments() {
        let a = Line {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let b = Line {
            start: (0.0, 1.0).into(),
            end: (1.0, 2.0).into(),
        };
        let s1 = LineInterval::line(a);
        let s2 = LineInterval::line(b);
        let relation = LineRelation::Parallel;

        assert_eq!(relation, s1.relate(&s2));
        assert_eq!(relation, s2.relate(&s1));
    }

    #[test]
    fn collinear_overlapping_segment_and_line() {
        let a = Line {
            start: (0.0, 0.0).into(),
            end: (0.0, 1.5).into(),
        };
        let b = Line {
            start: (0.0, 4.0).into(),
            end: (0.0, 5.0).into(),
        };
        let s1 = LineInterval::line(a);
        let s2 = LineInterval::ray(b);
        let relation = LineRelation::Collinear;

        assert_eq!(relation, s1.relate(&s2));
        assert_eq!(relation, s2.relate(&s1));
    }
}