Prevent clipper from merging polygons? - polygons

When I compute the difference between two shapes which touches one another (for example a rectangle A in a bigger rectangle B with a hole at rectangle A) and a clip shape (rectangle C) the two touching shapes are merged because their share the same edges and then the clipping is executed.
Is it possible to avoid merging touching shapes when clipping?
Here is an example of the difference between two shapes (A in green and B in red) and a clip (so the operation is: A & B - Clip), it returns the blue shape:
Instead of the blue rectangle, I would like to have those two shapes:
And the intersection would give:
This would give me the four shapes I want:
I know I could perform the operations on each shape separately, but I am afraid it will be more costly.
Note
Here is the result of a XOR:

In the hand I compute the operation myself:
compute the intersections between edges (of the clip shape and other shapes).
for each vertex: sort its edges by angle (mandatory)
walk through each edge clockwise and counterclockwise to compute the new polygons with their holes
This is efficient enough, but I need a space-partitioning data structure to sort edges and quickly their intersections.

Related

Is there a performant/mathematical way to find which tiles on a grid that a rotated rectangle overlaps?

I'm trying to work out which tiles a rectangle overlaps.
Right now I'm just taking the mix/max bounds of the rect, and iterating through the grid tiles that are within those bounds. And for each tile I check whether the tile rectangle intersects with the other rectangle. This isn't very performant as I still have to iterate a lot of tiles and do a lot of intersection checks.
I'm wondering if theres a more performant or mathematical way to achieve this.
Sort rectangle vertices by Y-coordinate and treat horizontal bands between vertice Y-positions separately (it is possible to get 1, 2 or 3 bands).
For every Y-interval you have left and right sides, walk through them using Bresenham algorithm (for pixels) or Amanatides-Woo algorithm (for cells/voxels).
For every horizontal you have the leftmost and the rightmost cell, fill also all cells between them.
Also look for triangle rasterization algorithms for more ideas.

Get Edges between Vertices (outer polygon)

I'm using THREE.JS and I have a this mesh with different surfaces. Of each surface I got its vertices. Now I want to create edges ( connect the vertices with lines). The vertices are in an arbitrary order, so I can't simply connect v1 with v2, v2 with v3 and so on. I think I have to walk through them with a ray clockwise or counter clockwise and put them in the right order somehow and I have to somehow check their distances, so that the horizontal line between the inner vertices doesn't appear, rather it should go right along the real edges,but I don't know how... Any idea?
(the spheres are the vertices that are the real corners of the surface, the orange lines are the wrong edges that need to be corrected and the blue lines are the edges of each single face)
I need to create these 8 edges (red)
Assuming that you are able to assign a unique number to the vertices and to uniquely associate every triangle to a face, and that the triangulation is watertight, the edges of a face are those edges that are common to a triangle of that face and a triangle of another. When you have all edges of a face, it is a trivial matter to chain them in a polygon.

Clipping and triangulating a triangle with a non convex polygon

I'm starting with a single 2D triangle that I want to clip with a (potentially) convex 2D polygon. It's not self-intersecting, but may 'keep' or 'discard' the intersecting area based on the winding order.
I want to end up with a triangulation, i.e. a list of n vertices and m triangles, defined by 3 vertices each, of the clipped region in 2D space.
What would be the easiest (for me as a developer), and what the fastest (in terms of computation) way to achieve this?
If I a right, you want to clip inside the polygon, i.e. get the intersection between the triangle and the polygon.
As the triangle is a convex shape, the Sutherland-Hodgman algorithm is appropriate and no too difficult to implement (https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm).
Notice that if the intersection is not simply connected, the resulting polygon will be connected, with double edges joining the would-be parts. Some cleanup might be required.
After finding the intersection, you re-triangulate using the ear-clipping method or a more efficient one (https://en.wikipedia.org/wiki/Polygon_triangulation).
Alternatively, you can triangulate the polygon and perform the clipping of every triangle with the original one.
The triangle-triangle clipping problem is again solved with Sutherland-Hodgman, somewhat simplified as the input polygons have a constant size, and their intersection is convex and at worse an hexagon. Trigulation of a convex polygon is immediate.

Dividing space outside of convex polygons into horizontally spanning quadrilaterals

I'm looking for an algorithm that can take an area containing a set of non-overlapping convex polygons as input, and break the space outside of the polygons into a set of non-overlapping convex quadrilaterals. The quadrilaterals need to have the property that they (individually) use as much horizontal space as possible.
Here's the input:
Here's the desired output:
I feel like I have seen some variation of this algorithm used to calculate regions to be flood-filled in very old paint programs. Is there a pleasant way to do this in better than O(n^2) time?
Edit: I realize there are some triangles in the output. I should probably state that quadrilaterals are the desired output, falling back to triangles only when it's physically impossible to use a quad.
I came up with a solution to this. In order to solve this efficiently, some sort of spatial data structure is needed in order to query which polygons are overlapped by a given rectangular area. I used a Quadtree. It's also necessary for the polygon data structure being used to be able to distinguish between internal and external edges. An edge is internal if it is common to two polygons.
The steps are as follows (assuming a coordinate system with the origin in the top-left corner):
Insert all polygons into whatever spatial data structure you're using.
Iterate over all polygons and build a list of all of the Y values upon
which vertices occur. This has the effect of conceptually dividing up
the scene into horizontal strips:
Iterate over the pairs of Y values from top to bottom. For each
pair (y0, y1) of Y values, declare a rectangular area a with
the the top left corner (0, y0) and bottom right corner
(width, y1). Determine the set of polygons S that are
overlapped by a by querying the spatial data structure. For
each polygon p in S, determine the set of edges E of p
that are overlapped by a. For best results, ignore any edge in
E with a normal that points directly up or down. For each
edge e in E, it's then necessary to determine the pair of
points at which e intersects the top and bottom edges of a.
This is achieved with a simple line intersection test,
treating the top and bottom edges of a as simple horizontal
line segments. Join the intersection points to create a set of
new line segments, shown in red:
Create vertical line segments L0 = (0, y0) → (0, y1) and
L1 = (width, y0) → (width, y1). Working from left to right,
gather any line segments created in the preceding step into pairs,
ignoring any line segments that were created from internal edges.
If there were no intersecting external edges, then the only two
edges will be L0 and L1. In this example strip, only four
edges remain:
Join the vertices in the remaining pairs of edges to create
polygons:
Repeating the above process for each horizontal strip achieves
the desired result. Assuming a set of convex, non-overlapping
polygons as input, the created polygons are guaranteed to be
either triangles or quadrilaterals. If a horizontal strip contains
no edges, the algorithm will create a single rectangle. If no
polygons exist in the scene, the algorithm will create a single
rectangle covering the whole scene.

How can a convex polygon be broken down into right triangles aligned on the X- and Y- axes?

Given a convex polygon represented by a set of vertices (we can assume they're in counter-clockwise order), how can this polygon be broken down into a set of right triangles whose legs are aligned with the X- and Y-axes?
Since I probably lack some math terminology, "legs" are what I'm calling those two lines that are not the hypotenuse (apologies in advance if I've stabbed math jargon in the face--brief corrections are extra credit).
I'm not sure about writing an algorithm to do this but it seems entirely possible to do this for any convex polygon on a piece of paper. For each vertex project a line vertically or horizontally from that vertex until it meets another of these vertical or horizontal lines. For vertices with small changes in angle, where adjacent sides are both travelling in the same direction in terms of x and y, you will need to add two lines from the vertex, one horizontal and one vetical.
Once you have done this, you should be left with a polygon in the centre of the origonal polygon but with sides that are either vertical or horizontal because the sides have been formed by the lines drawn from the vertices of the original polygon. Because these sides are either vertical or horizontal, this shape can easily be sub-divided into a number of triangles with one horizontal side, one vertical side and one hypotenuse.
I'm assuming you've already ordered the vertices as you describe above, and that they indeed define a convex polygon.
Each vertex defines a horizontal line. For V vertices, then, you will have a set of V lines. Discard any line that meets one of the following criteria:
The vertex or vertices defining that line has/have the highest or lowest Y component (if one vertex, that line intersects the polygon only at that point; if two, that line coincides with a polygon edge)
If two vertices have equal Y coordinates otherwise, keep only one of those lines (it's duplicated).
The result will resemble a "banding" of the polygon.
Each horizontal line intersects the polygon at two points. One is its defining vertex. The other is either another vertex, or a point on a segment defined by two vertices. You can determine which is the case easily enough - just simple comparison of Y coords. The coordinates of the intersection with a segment is also easy math, which I leave to you.
Each intersection defines a vertical segment. The segment is contained within the polygon (if it coincides with an edge, you can discard it), and the other end meets either another horizontal line, or the edge of the polygon if that edge is itself horizontal. Determining the case is again a matter of mere comparison of coords. Finally, there may be 0-2 additional vertical segments, defined by the vertices with the highest and/or lowest Y coords, if there is only one of either.
The resulting diagram now shows each band with a right triangle trimmed off each end if possible. Each triangle should meet your criteria. The leftover regions are rectangles; draw an arbitrary diagonal to split each into two more right triangles meeting your criteria.
You're done.
I'm not sure if this is possible. Think about a square that's already aligned with the sides on the X and Y axes. How do you draw triangles using the vertices that are also aligned to the X,Y axes?
Or are the actual sides of the polygon allowed to be along the x,y axis. Which means you could just draw a line down the diagonal of the square. If so, it might be difficult to do with a more complex polygon where some sides are aligned to the axes, while others are not.
I'm not convinced there is a general solution to the question as posed. The problem is the aligned with the X- and Y-axes bit. That means that each vertex needs to be projected to the opposite side of the polygon in both the X and Y directions, and new vertices created at those intersection points. But that process must continue on for each new vertex added that way. You might get lucky and have this process terminate (because there's already a vertex appropriately placed on the opposite side), but in the general case it's just going to go on and on.
If you throw out that restriction, then Neil N's suggestion seems good to me.
Neil N is right, I think. Unfortunate that he didn't provide any specific links.
If you have a trapezoid whose top and bottom are parallel to the X axis, you can easily render that with 4 right triangles. Call that shape a horizontal trapezoid.
If you have a triangle with one side parallel to the X axis, you can render that with 2 right triangles -- or you can consider a degenerate case of the trapezoid with the top of bottom having length zero.
Start at either the top or bottom of your convex hull (i.e. search for coordinate with min or max y) and split it into horizontal trapezoids.
It's not to hard to write the code so that it works just as well with non-convex polygons.
I think this is not possible in the general case.
Consider the polygon {(0, 1), (1, 0), (2, 0)}
.
..
This triangle can not be split into a finite number of triangles as you describe.

Resources