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     private static boolean intersectsLine(final Point2D point, Point2D p1,
13                                           Point2D p2) {
14
15         if (p1.y > p2.y) {
16             final Point2D tmp = p1;
17             p1 = p2;
18             p2 = tmp;
19         }
20
21         if (point.y < p1.y)
22             return false;
23         if (point.y > p2.y)
24             return false;
25
26         final double xp = p2.x - p1.x;
27         final double yp = p2.y - p1.y;
28
29         final double yp2 = point.y - p1.y;
30
31         final double crossX = p1.x + ((xp * yp2) / yp);
32
33         return point.x >= crossX;
34
35     }
36
37     public static boolean pointWithinPolygon(final Point2D point,
38                                              final Point2D p1, final Point2D p2, final Point2D p3) {
39
40         int intersectionCount = 0;
41
42         if (intersectsLine(point, p1, p2))
43             intersectionCount++;
44
45         if (intersectsLine(point, p2, p3))
46             intersectionCount++;
47
48         if (intersectsLine(point, p3, p1))
49             intersectionCount++;
50
51         return intersectionCount == 1;
52
53     }
54
55 }