Algorithm to compute the remaining polygon after subtraction - c#

I have a big polygon (Pa). Inside the polygon there are a lot of small "holes", as shown:
Here are a few condition for the holes:
The holes cannot overlap one another
The holes cannot go outside the outer polygon
However, the holes can touch the outer polygon edge
How to obtain the remaining polygon ( or the polygon list) in an efficient manner? The easiest way ( brute force way) is to take the Pa, and gradually computing the remaining polygon by subtracting out the holes. Although this idea is feasible, but I suspect that there is a more efficient algorithm.
Edit: I'm not asking about how to perform polygon clipping ( or subtraction) algorithm! In fact that's something I would do by brute force. I'm asking in addition to the polygon clipping method ( take the main polygon and then gradually clip the holes out), is there other more efficient way?

This is very hard to do in a general manner. You can find source code for a solution here:
General Polygon Clipper (GPC)

Well, if you use the right representation for your polygon you would not need to do anything. Just append the list of edges of the holes to the list of edges of Pa.
The only consideration you should have is that if some hole vertex or edge can touch Pa edge, you will have to perform some simplification there.
A different problem is rendering that polygon into a bitmap!

You can do like this.
Draw the main polygon with a color in a bitmap.
Draw the holes with another color in the same bitmap.
Then extract the polygon by running marching square algorithm with the main polygons color as threshold.
The output will contain all the points that belong to that polygon.
You can sort the points if you want it as a continous closed polygon.

I agree with salva, but my post is going to address the drawing part. Basically, you can add up all lines of the main and the hole polygons together and thereby get a single complex polygon.
The algorithm itself is not very complicted and it is nicely explained in the Polygon Fill Teaching Tool.

Related

3D z-buffer c# GDI plus

Im writting very simple 3d engine in c# and GDI+, just for render some models (I think Directx or OpenGL is like shovel to eat soup). So far I have succesfully implemented drawing Wireframe of my model, but next step is of course Faces. And there is my problem, for now I just project my 3d points to 2d point and then drawn it using simple
for each faceg.DrawPolygon(Pens.Red, projected_points); and for wireframe its ok.
It is possible to calculate overlapping part of polygon? and then draw FilledPolygon,
Or better idea is drawing pixel by pixel and if z-buffer of my pixel is further then set new pixel.
If first option is possible, which one is faster (for implement and calculating)?
It is possible to calculate overlapping part of polygon? and then draw FilledPolygon, Or
better idea is drawing pixel by pixel and if z-buffer of my pixel is further then set
new pixel.
If first option is possible, which one is faster (for implement and calculating)?
Yes, it is possible. You can test every polygon with every other of your list. The complexity depends on the type of the polygon (of course, it's easiest with triangles). But the performance may drop drastically with high count of polygons. And even if you find the overlapping areas, you will need to interpolate colors, or texture coordinates (if you plan to use such). Also I'm not sure about the API you use for drawing, but GDI doesn't support fill polygon with interpolated colors.
I have heard that this was the approach used in 3d graphics before inventing the Z buffer. :)
I once tried to realize similar project and used Z-buffer + my own routine to fill triangles with interpolated colors (which uses the Z-buffer). I drawed directly to a GDI bitmap's pixel data buffer. Then after all polygons has been rendered, I bitblt'ed the result to the screen.

Detect mouseover of non-square part of an Image

So I am working on a Risk type game in XNA/C#. I have a map, similar this one, and I need to be able to detect mouseovers on each territory (number). If these areas were squares, it would be easy, as they could each be represented by a rectangle. However, they are different size polygons. Is there a polygon shape that behaves similar to a square? If there isn't, how would I go about doing this?
I sugest this:attach color to each number, recreate your picture in these colors: every shape will be in its particular color. Dont draw it onscreen, use it only as reference map. And when the user clicks or moves mouse over your original map, you just simply project mouse coordinates into the color map, check the color of pixel laying under the mouse and because you have each color associated to number of territory...
This is not c# specific (as I've never written anything in the language, so no idea of what apis there are), though there are 2 algorithms that come to mind for detecting if a point is inside a polygon (which can be used to detect if a mouse point is over another polygon/map shape).
One is based on raycasting, where you cast a ray in 1 direction from the (mouse) point to "infinity" (edge of the board in this case) and count the number of times it crosses the polygon's edges. If it is odd, then the point is inside the polygon, if it is even, then the point is outside of the polygon.
A wiki link to it: http://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm
The other algorithm that comes to mind works only for triangles I think but it can be more simple to implement I think (taking a quick glance at your shapes, I think they can easily be broken down into triangles and some are already triangles). It is to do with checking if the point is on the same (internal) "side" of all the edges in the triangle. To find out what "side" a point is on vs an edge, you'd take create 2 vectors, the first vector would be the edge itself (made up of 2 points) and the other vector would be the first point of that edge to the input point, then calculate the cross product of those 2 vectors. The result will be negative or positive, which can be used to determine the "direction".
A link to it: http://www.blackpawn.com/texts/pointinpoly/default.html
(On that page is another algorithm that can also work for triangles)
Hit testing on a polygon is not so difficult to do in real time. You could use a KD-Tree for optimisation if the map is huge. Otherwise find a simple Contains method for a polygon and use that. I have one on another computer. Let me know if you'd like it.

how to correct scan mistakes, like rotation?

I'm trying to scan some pictures together (personal 3x4 cm images) and then split them into separated images. the first step about scanning is done but about second step (edge detection and splitting) I've some problems.
1- Normally when they scan pictures, some pictures rotate some degrees and its preventing me to have straight edges.
2- How do I remove big noises? (Imagine when they scan those pictures, they put a paper behind them. sometimes the paper makes some edges in the scanned picture... how can I understand that its not the edge I'm looking for?)
Here is a sample image:
The sample images within the scan are all rectangular, and they are all roughly the same size. There are a variety of techniques for finding rectangles in an image (even at completely arbitrary rotation), but I'll start with the more fundamental techniques.
Hough line fit can be used to find lines in an image, even when the background is noisy. From the Hough line fits you can find intersection points and perhaps compare those intersection points to points found with corner detections (see 3 below).
Edge points on lines have gradients perpendicular to those lines. When searching for edge points, you can favor edge points that are roughly a distance L or a distance W from other edge points with gradients in the parallel direction, where L and W are the known length and width of your images.
Corner detectors can help identify corners of your small rectangular images. You know the length and width of the pictures, which should help you accept/reject corners.
If you want to get fancy (which I don't recommend), then a simple normalized cross-correlation technique could detect all instances of a "template" subimage within a larger image. The technique is a bit crude, but it works okay if there isn't much rotation. Since the subimages have well-defined borders of known shape and (presumably) consistent size, it'd be easier just to find the edges rather than try to match the image content.
Once you've identified the location and orientation of each rectangular subimage, then a simple rotational transform + interpolation could generate a "right side up" version of each image. With scanners you won't have problems with perspective distortion, but if at some point in the future you would take pictures of pictures (?) at an angle, then an affine transform can map the distorted, trapezoidal images to rectangular images.
Hough transform
http://en.wikipedia.org/wiki/Hough_transform
Corner detection
http://en.wikipedia.org/wiki/Corner_detection
For simple edge detection that should work sufficiently well for your application, see the section "Other first-order methods" in the Edge Detection article on Wikipedia. The technique is easy to understand and simple to implement.
http://en.wikipedia.org/wiki/Edge_detection
Good luck, and once again Happy New Year!

Subdividing 3D mesh into arbitrarily sized pieces

I have a mesh defined by 4 points in 3D space. I need an algorithm which will subdivide that mesh into subdivisions of an arbitrary horizontal and vertical size. If the subdivision size isn't an exact divisor of the mesh size, the edge pieces will be smaller.
All of the subdivision algorithms I've found only subdivide meshes into exact powers of 2. Does anyone know of one that can do what I want?
Failing that, my thoughts about a possible implementation is to rotate the mesh so that it is flat on the Z axis, subdivide in 2D and then translate back into 3D. That's because my mind finds 3D hard ;) Any better suggestions?
Using C# if that makes any difference.
If you only have to work with a rectangle in 3D, then you simply need to obtain the two edge vectors and then you can generate all the interior points of the subdivided rectangle. For example, say your quad is defined by (x0,y0),...,(x3,y3), in order going around the quad. The edge vectors relative to point (x0,y0) are u = (x1-x0,y1-y0) and v = (x3-x0,y3-y0).
Now, you can generate all the interior points. Suppose you want M edges along the first edge, and N along the second, then the interior points are just
(x0,y0) + i/(M -1)* u + j/(N-1) * v
where i and j go from 0 .. M-1 and 0 .. N-1, respectively. You can figure out which vertices need to be connected together by just working it out on paper.
This kind of uniform subdivision works fine for triangular meshes as well, but each edge must have the same number of subdivided edges.
If you want to subdivide a general mesh, you can just do this to each individual triangle/quad. This kind of uniform subdivision results in poor quality meshes since all the original flat facets remain flat. If you want something more sophisticated, you can look at Loop subidivision, Catmull-Clark, etc. Those are typically constrained to power-of-two levels, but if you research the original formulations, I think you can derive subdivision stencils for non-power-of-two divisions. The theory behind that is a bit more involved than I can reasonably describe here.
Now that you've explained things a bit more clearly, I don't see your problem: you have a rectangle and you want to divide it up into rectangular tiles. So the mesh points you want are regularly spaced in both orthogonal directions. In 2D this is trivial, surely ? In 3D it's also trivial though the maths is a little trickier.
Off the top of my head I would guess that transforming from 3D to 2D (and aligning the rectangle with the coordinate axes at the same time) then calculating the mesh points, then transforming back to 3D is probably about as simple (and CPU-time consuming) as working it all out in 3D in the first place.
Yes, using C# means that I'm not able to propose a code to help you.
Comment or edit you question if I've missed the point.

Building an "inner stroke" effect from a Polygon

I'm drawing a whole bunch of Polygons onto a canvas, most of which share an edge with at least one other Polygon. I'd like to indicate a Polygon is "special" by outlining it, however due to the overlapping edges the Stroke on a Polygon tends to be partially drawn over by another Polygon causing the Stroke to look thinner than it should in places. Additionally, depending on draw order, a Polygon may have its Stroke almost entirely covered by those around it. Spacing the Polygons out is not a very attractive option, as visible gaps between Polygons are much less preferable to this "thin stroke" problem.
I reason that the effect I'm looking for can be achieved by generating each Polygon as a pair of Polygons instead, such that one Polygon is completely contained within the other and this smaller Polygon's Stroke runs up to (but does not overlap) the outer Polygon's Stroke. The inner Polygon would have a transparent Fill at all times, and a non-transparent Stroke only when I wish to indicate that the now pair of Polygons are "special".
My question boils down to; how can I derive such an inner Polygon from the outer one, or failing that how else might I achieve this effect?
The Polygon's in question can be constrained to the regular polygons if need be, and the Strokes are simple 1 thickness solid lines with no fancy miters or the like. I'd like to be able to adjust the thickness of the Stroke at some point, but nothing fancier than that.
I think there's actually a few ways to achieve what you want.
First, going with your original idea of drawing a second, slightly smaller polygon within the original polygon; it's not a bad idea. To answer your original question as to how to generate the smaller polygon: you can find the centroid of each polygon, and offset each vertex by a percentage of the distance to that centroid point of the polygon to get the smaller polygon. This should give a pleasing effect.
Another way you could go would be to use z-order, and offset the "thicker" polygon by a slight negative z-distance.
Yet another way to go would be to exploit draw order; draw your thicker polygons last, which will prevent them from being overdrawn by the surrounding polygons.
Yet another idea that might work depending on your needs might be not to draw polygons at all, but to draw a series of lines, simply thickening some of the lines.
There's a lot of options for you to try; hope you find one that works out well!

Categories