line Segments Intersect - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

line Segments Intersect

Demo Code

/**/* w  ww  . j a v a2  s  .  c o m*/
 * Java Modular Image Synthesis Toolkit (JMIST)
 * Copyright (C) 2008-2013 Bradley W. Kimmel
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

public class Main{
    public static boolean lineSegmentsIntersect(Point2 a1, Point2 a2,
            Point2 b1, Point2 b2) {
        return rayIntersectsRay(new Ray2(a1, a2), new Ray2(b1, b2));
    }
    public static boolean rayIntersectsRay(Ray2 r1, Ray2 r2) {
        Vector2 r = rayIntersectRay(r1, r2);
        return MathUtil.inRangeOO(r.x, 0.0, r1.limit())
                && MathUtil.inRangeOO(r.y, 0.0, r2.limit());
    }
    public static Vector2 rayIntersectRay(Ray2 r1, Ray2 r2) {
        Vector2 d1 = r1.direction();
        Vector2 d2 = r2.direction();
        LinearMatrix2 T = new LinearMatrix2(d1.x, -d2.x, d1.y, -d2.y);
        Vector2 o12 = r1.origin().vectorTo(r2.origin());

        return T.inverse().times(o12);
    }
}

Related Tutorials