Skip to content

Commit deafe2c

Browse files
authored
Simplified surrounds function (#140)
Fixed bug and simplified function
1 parent f4c805d commit deafe2c

File tree

2 files changed

+15
-18
lines changed

2 files changed

+15
-18
lines changed

src/extras/BuildingShapeUtils.js

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -411,40 +411,36 @@ class BuildingShapeUtils extends ShapeUtils {
411411
* @return {boolean}
412412
*/
413413
static surrounds(shape, point) {
414-
var count = 0;
414+
var inside = false;
415415
const vecs = shape.extractPoints().shape;
416416
var vec;
417417
var nextvec;
418418
for (let i = 0; i < vecs.length; i++) {
419419
vec = vecs[i];
420420
nextvec = vecs[(i + 1) % vecs.length];
421+
// If the point is one of the corners, it's inside.
421422
if (vec.x === point[0] && vec.y === point[1]) {
422423
return true;
423424
}
424-
if (nextvec.x === vec.x) {
425-
// vertical line
426-
if (vec.x === point[0]) {
425+
// If the edge is horizonal and the point is on the line between the ends it's inside
426+
if (nextvec.y === vec.y){
427+
const a = vec.x > point[0];
428+
const b = nextvec.x > point[0];
429+
// xor
430+
if (nextvec.y === point[1] && (a || b) && !(a && b)) {
427431
return true;
428432
}
429-
if (vec.x > point[0] && (vec.y > point[1] || nextvec.y > point[1]) && !(vec.y > point[1] && nextvec.y > point[1])){
430-
count++;
431-
}
432-
} else if (nextvec.y === vec.y) {
433-
if (vec.y === point[1] && (vec.x > point[0] || nextvec.x > point[0]) && !(vec.x > point[0] && nextvec.x > point[0])){
433+
} else if ((vec.y > point[1] && nextvec.y < point[1]) || (vec.y < point[1] && nextvec.y > point[1])) {
434+
const crossing = vec.x + (point[1] - vec.y) * (nextvec.x - vec.x) / (nextvec.y - vec.y);
435+
if (point[0] === crossing) {
434436
return true;
435437
}
436-
} else {
437-
const slope = (nextvec.y - vec.y) / (nextvec.x - vec.x);
438-
const intercept = vec.y - slope * vec.x;
439-
const intersection = (point[1] - intercept) / slope;
440-
if (intersection > point[0] && intersection < Math.max(nextvec.x, vec.x) && intersection > Math.min(nextvec.x, vec.x)) {
441-
count++;
442-
} else if (intersection === point[0]) {
443-
return true;
438+
if (point[0] < crossing) {
439+
inside = !inside;
444440
}
445441
}
446442
}
447-
return count % 2 === 1;
443+
return inside;
448444
}
449445

450446
/**

test/utils.test.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ describe.each([
166166
describe.each([
167167
[[-.5, -.5], false, 'Outside but crossing'],
168168
[[-1.5, -1.5], false, 'Outside no crossings'],
169+
[[1, -2], false, 'Outside but colinear with vertical edge.'],
169170
[[1, 1], true, 'Share Node'],
170171
[[.5, .5], true, 'Inside'],
171172
[[0, 0], true, 'Border'],

0 commit comments

Comments
 (0)