From 7a6641a5aada6892015b7001f97901806f22d92a Mon Sep 17 00:00:00 2001 From: Bryan Housel Date: Tue, 12 Aug 2014 22:40:43 -0400 Subject: [PATCH] Better polygon intersection test (see also my comment on 83030be) --- js/id/geo.js | 13 ++++++++++++- test/spec/geo.js | 8 +++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/js/id/geo.js b/js/id/geo.js index 9ce5d9575..059953d3a 100644 --- a/js/id/geo.js +++ b/js/id/geo.js @@ -180,9 +180,20 @@ iD.geo.polygonContainsPolygon = function(outer, inner) { }; iD.geo.polygonIntersectsPolygon = function(outer, inner) { + function testSegments(outer, inner) { + for (var i = 0; i < outer.length - 1; i++) { + for (var j = 0; j < inner.length - 1; j++) { + var a = [ outer[i], outer[i+1] ], + b = [ inner[j], inner[j+1] ]; + if (iD.geo.lineIntersection(a, b)) return true; + } + } + return false; + } + return _.some(inner, function(point) { return iD.geo.pointInPolygon(point, outer); - }); + }) || testSegments(outer, inner); }; iD.geo.pathLength = function(path) { diff --git a/test/spec/geo.js b/test/spec/geo.js index ef2c9e0e1..b0919e8ff 100644 --- a/test/spec/geo.js +++ b/test/spec/geo.js @@ -294,12 +294,18 @@ describe('iD.geo', function() { expect(iD.geo.polygonIntersectsPolygon(outer, inner)).to.be.true; }); - it('says a polygon that partially intersects does', function() { + it('says a polygon that partially intersects does when some points are contained', function() { var outer = [[0, 0], [0, 3], [3, 3], [3, 0], [0, 0]]; var inner = [[-1, -1], [1, 2], [2, 2], [2, 1], [1, 1]]; expect(iD.geo.polygonIntersectsPolygon(outer, inner)).to.be.true; }); + it('says a polygon that partially intersects does when no points are contained', function() { + var outer = [[0, 0], [0, 3], [3, 3], [3, 0], [0, 0]]; + var inner = [[1, -1], [1, 4], [2, 4], [2, -1], [1, -1]]; + expect(iD.geo.polygonIntersectsPolygon(outer, inner)).to.be.true; + }); + it('says totally disjoint polygons do not intersect', function() { var outer = [[0, 0], [0, 3], [3, 3], [3, 0], [0, 0]]; var inner = [[-1, -1], [-1, -2], [-2, -2], [-2, -1], [-1, -1]];