Raycasting with PostGIS

I recently developed a function in PostGIS that performs simple 2D raycasting. Raycasting is the process of drawing lines from a single point which radiate outwards until they intersect a boundary. It is used quite often in video game development, particularly in first-person shooter (FPS) games. There’s a ton of literature and videos out there on developing raycasting engines for games, but this one I think gives a great overview about how it works while giving a very interesting dive into how early FPSs “cheated” by using a 2D raycaster and some visual trickery.

I was surprised to not find any straight-up application of raycasting in GIS, except for the common use case of determining if a point is inside a polygon, or doing line-of-sight analysis, and that one is almost always done using a raster dataset. I thought it would be an interesting topic to tackle so I went ahead and developed a 2D raycasting function in PostGIS. The function is pretty straightforward, give it some points and some lines and it will cast rays outwards from the points until they intersect one of the lines, and abruptly stop, returning the set of either points where the rays intersected the lines, or the lines defining the rays themselves.

Each point’s colour-coded rays and intersection points with the black boundaries.

I’m pretty happy with how it turned out. You can specify the number of rays to cast, as well as maximum distance that a ray can be casted to control the resolution and the distance that the points can “see”, respectively. In order to use it, all you have to do is run the function definition query on your database and start calling it as you would any other PostGIS function. It returns a GEOMETRY data type, always either a MULTIPOINT or MULTILINE, which represent aggregations of points or lines corresponding to its source point.

The source code, usage and examples can be found at the Github page.

Leave a Reply

Your email address will not be published. Required fields are marked *