Raycasting
Raycasting is used in computational geometry and is much simpler than Raytracing.
Raycasting in 2D shoots a ray from a point to see which edges it intersects.
Similar to in Raytracing, we have a ray of origin with a direction (which has parametric form ).
We cast rays because they help us answer geometric questions like:
- Does a point lie inside a polygon
- Does a shape intersect the polygon edge
- Where does the ray hit the polygon boundary
- What are the interior spans of a polygon?
The Algorithm
In general, given a ray , and a list of polygon edges. We want to know which segments the ray intersects.
- Solve the intersection between the ray and line segment for each polygon edge
- Discard intersections behind the ray origin and intersections outside the segment bounds
- Collect valid intersection points
- Sort by distance from ray origin Now we would have a list of boundary crossings.
Point-in-Polygon
The fundamental rule here isβ¦
- If a ray crosses the polygon boundary an odd amount of times, it is inside the polygon
- If a ray crosses the polygon boundary an even amount of times, it is outside the polygon
For example if we have a polygonβ¦
y=1: ######
y=2: # #
y=3: # #
y=4: ###### and we drop a ray into x=5β¦
y=0: |
y=1: | hits boundary (top edge)
y=2: | inside
y=3: | inside
y=4: | hits boundary (bottom edge)
y=5: | outsideMathematically, we are looking for t such that or such that a ray intersects a segment. A segment is defined as where and .
- We solve for t and u, if there is no solution, there is no intersection. If is not between there the ray intersects beyond the segment. We typically in most cases only care if a solution exists.
Double counting
If a vertical ray exactly hits a vertex where two horizontal edges or a horizontal and vertical edge meet, its easy to count that crossing twice. To fix this, we make the interval half-open on one side.
Interior Spans
We can expand this idea beyond a single point to as if a continuous interval is inside a polygon.
From here, we will know the valid x and y coordinates for row y, and column x.
We now know the interior span for column x=6 is or and .
We drop a ray at every column in the polygon to get the rest of our ranges.
This works because each column x is a slice of the polygon where the polygon interior is continuous inside the range.
Now that we have interior spans, we can take an arbitrary axis-aligned bounding box and check if that bounding box is within the polygon.
AABB
If we choose two arbitrary
A = (5,2)
B = (14,3)and snag the boundsβ¦
xmin = 5
xmax = 14
ymin = 2
ymax = 3We want to check that for every x in our rangeβ¦
which we know from our interior spans in the previous step. If this is always true, the entire rectangle is inside the polygon.