2 * Sixth 3D engine. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.sixth.e3d.geometry;
8 * Utility class for polygon operations.
10 public class Polygon {
14 * Checks if point is on the right side of the line.
15 * @param point point to check
16 * @param lineP1 line start point
17 * @param lineP2 line end point
18 * @return true if point is on the right side of the line
20 private static boolean intersectsLine(final Point2D point, Point2D lineP1,
23 // Sort line points by y coordinate.
24 if (lineP1.y > lineP2.y) {
25 final Point2D tmp = lineP1;
30 // Check if point is within line y range.
31 if (point.y < lineP1.y || point.y > lineP2.y)
34 // Check if point is on the line.
35 final double xp = lineP2.x - lineP1.x;
36 final double yp = lineP2.y - lineP1.y;
38 final double crossX = lineP1.x + ((xp * (point.y - lineP1.y)) / yp);
40 return point.x >= crossX;
43 public static boolean pointWithinPolygon(final Point2D point,
44 final Point2D p1, final Point2D p2, final Point2D p3) {
46 int intersectionCount = 0;
48 if (intersectsLine(point, p1, p2))
51 if (intersectsLine(point, p2, p3))
54 if (intersectsLine(point, p3, p1))
57 return intersectionCount == 1;