Skip to content

Commit

Permalink
fix is_segment_intersection
Browse files Browse the repository at this point in the history
  • Loading branch information
exoji2e committed Oct 6, 2024
1 parent e35314e commit 264f99b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
13 changes: 9 additions & 4 deletions src/geometry/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,20 @@ def cross(u, v):
# Point : (x, y)
# returns true if intersecting s1 & s2 shares at least 1 point.
def is_segment_intersection(s1, s2):
u = vec(*s1)
v = vec(*s2)
p1, p2 = s1
q1, q2 = s2
u = vec(p1, p2)
v = vec(q1, q2)
d1 = cross(u, vec(p1, q1))
d2 = cross(u, vec(p1, q2))
d3 = cross(v, vec(q1, p1))
d4 = cross(v, vec(q1, p2))
# at least one point is on other segment's line
if d1 * d2 * d3 * d4 == 0:
p1, p2 = min(p1, p2), max(p1, p2)
return p1 <= q1 <= p2 or p1 <= q2 <= p2
items = [(d1, q1, s1), (d2, q2, s1), (d3, p1, s2), (d4, p2, s2)]
for dv, p, seg in items:
if dv == 0:
s, t = min(seg), max(seg)
if s <= p <= t: return True
return False
return sign(d1) != sign(d2) and sign(d3) != sign(d4)
11 changes: 8 additions & 3 deletions src/geometry/test_geometry.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import unittest
from . import geometry
try:
from . import geometry
except ImportError:
import geometry

class GeometryTest(unittest.TestCase):
def test_line_intersect(self):
Expand All @@ -10,10 +13,12 @@ def test_line_intersect(self):
(((0,0),(3,3)), ((3,0), (0,3)), True), # orthogonal regular
(((0,0),(3,3)), ((6,0), (0,6)), True), # orthogonal touch
(((0,0),(3,3)), ((7,0), (0,7)), False), # orthogonal outside
(((0,1),(1,10)), ((1,1), (2,1)), False), # one point on same line outside segment
(((1,10),(0,1)), ((1,1), (2,1)), False), # one point on same line outside segment
]
for s1, s2, res in segment_tests:
self.assertEqual(geometry.is_segment_intersection(s1, s2), res)
self.assertEqual(geometry.is_segment_intersection(s1, s2), res, f'{s1} {s2} should give {res}')


if __name__ == '__main__':
unittest.main()
unittest.main()

0 comments on commit 264f99b

Please sign in to comment.