@@ -14,7 +14,7 @@ var dot = require('./matrix').dot;
14
14
* Turn an array of [x, y] pairs into a polygon object
15
15
* that can test if points are inside it
16
16
*
17
- * @param pts Array of [x, y] pairs
17
+ * @param ptsIn Array of [x, y] pairs
18
18
*
19
19
* @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains}
20
20
* (x|y)(min|max) are the bounding rect of the polygon
@@ -43,6 +43,47 @@ polygon.tester = function tester(ptsIn) {
43
43
ymax = Math . max ( ymax , pts [ i ] [ 1 ] ) ;
44
44
}
45
45
46
+ // do we have a rectangle? Handle this here, so we can use the same
47
+ // tester for the rectangular case without sacrificing speed
48
+
49
+ var isRect = false ,
50
+ rectFirstEdgeTest ;
51
+
52
+ function onFirstVert ( pt ) { return pt [ 0 ] === pts [ 0 ] [ 0 ] ; }
53
+ function onFirstHorz ( pt ) { return pt [ 1 ] === pts [ 0 ] [ 1 ] ; }
54
+
55
+ if ( pts . length === 5 ) {
56
+ if ( pts [ 0 ] [ 0 ] === pts [ 1 ] [ 0 ] ) { // vert, horz, vert, horz
57
+ if ( pts [ 2 ] [ 0 ] === pts [ 3 ] [ 0 ] &&
58
+ pts [ 0 ] [ 1 ] === pts [ 3 ] [ 1 ] &&
59
+ pts [ 1 ] [ 1 ] === pts [ 2 ] [ 1 ] ) {
60
+ isRect = true ;
61
+ rectFirstEdgeTest = onFirstVert ;
62
+ }
63
+ }
64
+ else if ( pts [ 0 ] [ 1 ] === pts [ 1 ] [ 1 ] ) { // horz, vert, horz, vert
65
+ if ( pts [ 2 ] [ 1 ] === pts [ 3 ] [ 1 ] &&
66
+ pts [ 0 ] [ 0 ] === pts [ 3 ] [ 0 ] &&
67
+ pts [ 1 ] [ 0 ] === pts [ 2 ] [ 0 ] ) {
68
+ isRect = true ;
69
+ rectFirstEdgeTest = onFirstHorz ;
70
+ }
71
+ }
72
+ }
73
+
74
+ function rectContains ( pt , omitFirstEdge ) {
75
+ var x = pt [ 0 ] ,
76
+ y = pt [ 1 ] ;
77
+
78
+ if ( x < xmin || x > xmax || y < ymin || y > ymax ) {
79
+ // pt is outside the bounding box of polygon
80
+ return false ;
81
+ }
82
+ if ( omitFirstEdge && rectFirstEdgeTest ( pt ) ) return false ;
83
+
84
+ return true ;
85
+ }
86
+
46
87
function contains ( pt , omitFirstEdge ) {
47
88
var x = pt [ 0 ] ,
48
89
y = pt [ 1 ] ;
@@ -115,7 +156,8 @@ polygon.tester = function tester(ptsIn) {
115
156
ymin : ymin ,
116
157
ymax : ymax ,
117
158
pts : pts ,
118
- contains : contains
159
+ contains : isRect ? rectContains : contains ,
160
+ isRect : isRect
119
161
} ;
120
162
} ;
121
163
0 commit comments