Updated readability of the code.
[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)
32             return false;
33         if (point.y > lineP2.y)
34             return false;
35
36         // Check if point is on the line.
37         final double xp = lineP2.x - lineP1.x;
38         final double yp = lineP2.y - lineP1.y;
39
40         final double yp2 = point.y - lineP1.y;
41
42         final double crossX = lineP1.x + ((xp * yp2) / yp);
43
44         return point.x >= crossX;
45
46     }
47
48     public static boolean pointWithinPolygon(final Point2D point,
49                                              final Point2D p1, final Point2D p2, final Point2D p3) {
50
51         int intersectionCount = 0;
52
53         if (intersectsLine(point, p1, p2))
54             intersectionCount++;
55
56         if (intersectsLine(point, p2, p3))
57             intersectionCount++;
58
59         if (intersectsLine(point, p3, p1))
60             intersectionCount++;
61
62         return intersectionCount == 1;
63
64     }
65
66 }