Improved code readability
[sixth-3d.git] / src / main / java / eu / svjatoslav / sixth / e3d / geometry / Polygon.java
1 /*
2  * Sixth 3D engine. Author: Svjatoslav Agejenko.
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.sixth.e3d.geometry;
6
7 /**
8  * Utility class for polygon operations.
9  */
10 public class Polygon {
11
12
13     /**
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
19      */
20     private static boolean intersectsLine(final Point2D point, Point2D lineP1,
21                                           Point2D lineP2) {
22
23         // Sort line points by y coordinate.
24         if (lineP1.y > lineP2.y) {
25             final Point2D tmp = lineP1;
26             lineP1 = lineP2;
27             lineP2 = tmp;
28         }
29
30         // Check if point is within line y range.
31         if (point.y < lineP1.y || point.y > lineP2.y)
32             return false;
33
34         // Check if point is on the line.
35         final double xp = lineP2.x - lineP1.x;
36         final double yp = lineP2.y - lineP1.y;
37
38         final double crossX = lineP1.x + ((xp * (point.y - lineP1.y)) / yp);
39
40         return point.x >= crossX;
41     }
42
43     public static boolean pointWithinPolygon(final Point2D point,
44                                              final Point2D p1, final Point2D p2, final Point2D p3) {
45
46         int intersectionCount = 0;
47
48         if (intersectsLine(point, p1, p2))
49             intersectionCount++;
50
51         if (intersectsLine(point, p2, p3))
52             intersectionCount++;
53
54         if (intersectsLine(point, p3, p1))
55             intersectionCount++;
56
57         return intersectionCount == 1;
58
59     }
60
61 }