I’m doing some mesh generation for a spare time project, and I’ve come to a point where I really need to be able to triangulate any specified 2D polygon - i.e. split a 2D polygon (convex or not) into triangles so that I can use those to generate a mesh.
I’ve looked a bit on what’s already available on the Net, and I found these two projects written in C#:
However, I’ve tested both, and they’re both buggy, meaning that they produce incorrect results for many polygons, where some triangles are outside the polygon.
There are much more promising projects with source code floating around, but unfortunately not in C#. For example:
Yeah, the script I posted uses the ear clipping method too. It’s not the most efficient method. I believe it’s O(n * n) and there are more advanced methods that can do it in O(n log n) - but it gets the job done.
Also, what if the polygon is 3D with vertices having (x,y,z) values?! Does it really matter if the object is or is not in 3d. From what I understand the trinagles’ corners attach to the vertices in the order they are added. Is this right?!
I desparately need a working JS code, please.
Thanks for your reponse, in advance.
A polygon is planar by definition. If you have points in 3d space that are not co-planar then it’s not a polygon and the algorithm won’t apply.
For example, the algorithm needs to be able to test whether a certain point is on one side or the other side of a line defined by two other points. Such a test makes sense in 2d but not in 3d.
If you have points in 3d space that are co-planar, you can convert them into 2d points, then use the algorithm on those, and then use the returned vertex indices on the original 3d points.
I’m not sure what you mean. How the triangels are formed depend on the shape of the polygon.
If you’re desperate, it should be no problem to learn the small differences between C# and JavaScript to be able to translate the script yourself.
I just wanted to share the following code. It allows both 2d and 3d points to be added to it. It’s not the fastest method, I am sure there are improvements possible. Dear runevision, do you have any improvements ready?
btw it’s C#.
Adding holes to the ear clipping is not as hard as it seems. If your edge finding tool is good enough, you will be able to make a difference between CCW and CW edges. Then sort these edges on their bounding box size (big to small) and cut a non visible line from the closest point of the inside to the outside edge (connecting the edges as a line). Then it’s just a matter of triangulating.
The version I am posting only tests if a point is inside a triangle, not on a triangle. If this is a problem, change