Intersection

Intersections are implemented for various geometries such as Segment, Line, and Box:

using Meshes

s1 = Segment((0.0,0.0), (1.0,0.0))
s2 = Segment((0.5,0.0), (2.0,0.0))

s1 ∩ s2
Segment{2,Float64}
  └─Point(0.5, 0.0)
  └─Point(1.0, 0.0)

First, the intersection function computes the Intersection object, which holds the IntersectionType besides the actual geometry:

I = intersection(s1, s2)
Intersection{Segment{2, Float64, StaticArrays.SVector{2, Point2}}}(OverlappingSegments, Segment(Point(0.5, 0.0), Point(1.0, 0.0)))

This object supports two methods type and get to retrieve the underlying information:

type(I)
OverlappingSegments::IntersectionType = 4
get(I)
Segment{2,Float64}
  └─Point(0.5, 0.0)
  └─Point(1.0, 0.0)

For performance-sensitive code, it is recommended to use the intersection method with three arguments, including a function to reduce the number of output types.

In the example below, we use the do syntax to restrict our attention to a subset of intersection types and to make the return type and Int value in all cases:

intersection(s1, s2) do I
  if type(I) == CrossingSegments
    return 1
  elseif type(I) == OverlappingSegments
    return 2
  else
    return 3
  end
end
2
Meshes.IntersectionTypeType
IntersectionType

The different types of intersection that may occur between geometries. Type IntersectionType in a Julia session to see the full list.

Meshes.IntersectionType
Intersection{G}

An intersection between geometries holding a geometry of type G.

Meshes.intersectionFunction
intersection([f], g1, g2)

Compute the intersection of two geometries g1 and g2 and apply function f to it. Default function is identity.

Examples

intersection(g1, g2) do I
  if I isa CrossingLines
    # do something
  else
    # do nothing
  end
end

Notes

When a custom function f is used that reduces the number of return types, Julia is able to optimize the branches of the code and generate specialized code. This is not the case when f === identity.

Base.intersectMethod
g1 ∩ g2

Return the intersection of two geometries g1 and g2 as a new geometry.

More generally, when the geometries are not convex nor simple, it is still possible to know whether or not they have an intersection:

outer = Point2[(0,0),(1,0),(1,1),(0,1),(0,0)]
hole1 = Point2[(0.2,0.2),(0.4,0.2),(0.4,0.4),(0.2,0.4),(0.2,0.2)]
hole2 = Point2[(0.6,0.2),(0.8,0.2),(0.8,0.4),(0.6,0.4),(0.6,0.2)]
poly  = PolyArea(outer, [hole1, hole2])
ball1 = Ball((0.5,0.5), 0.05)
ball2 = Ball((0.3,0.3), 0.05)
ball3 = Ball((0.7,0.3), 0.05)
ball4 = Ball((0.3,0.3), 0.15)

hasintersect(poly, ball1)
true
hasintersect(poly, ball2)
false
hasintersect(poly, ball3)
false
hasintersect(poly, ball4)
true