I'm trying to constrain a LineString to a Polygon. Here's an example of what I'm looking for:
In the left figure (the input), the green LineString travels beyond the border of the Polygon for a bit before returning and continuing inside. In the right figure (the output), the part of the LineString that was beyond the Polygon border is removed, and in its place, the LineString hugs the Polygon boundary.
This output would also be acceptable:
How can I do this in a way that is not terribly slow and/or with code that is not terribly complex and ugly?
The LineString can be an arbitrary meandering path, and as seen in the example, it might have self-intersections. It is not necessarily possible to convert it to a Polygon and use Polygon/Polygon intersection. One example would be a Hilbert curve which has no interior or exterior.
I can imagine a brute-force approach that involves splitting the Polygon exterior and the LineString with each other (perhaps using complex_split()) then piecing things together. I think this will involve a lot of project()
and interpolate()
which can become quite computationally expensive. And it starts to get even more painful when you consider a LineString with multiple overlapping excursions outside of the Polygon. Got any better ideas? Or maybe you can implement the brute-force approach elegantly?
What's this for? I want to use this algorithm in Ink/Stitch, an open source machine embroidery design platform. The LineString is a stitch path that should be inside a fill region, but may occasionally wander out. The excursions are undesirable and we need to eliminate them. One might also imagine a GPS trace that should be constrained inside a boundary area.