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