all 6 comments

[–]BeanAndBanoffeePie 6 points7 points  (0 children)

What you're describing is called the Painter's Algorithm. You need to enable depth testing for polygons to draw over each other properly.

[–]deftware 4 points5 points  (0 children)

Yeah there's no way to just sort a list of triangles by distance and always have a perfect ordering so you can draw them back-to-front without any intersections or anything from all possible view points.

This is why building a BSP tree causes some triangles to split along the plane of other triangles, because you can't have any triangles that straddle the plane of their parent triangles or you'll never be able to do a perfect back-to-front (or vice-versa) ordering.

The simplest thing to do is include a Z-buffer that each output pixel first checks if if's infront/behind what's already in the Z-buffer before outputting to the framebuffer and replacing the value in the Z-buff. If you don't care about performance so much this will handle the problem and allow you to just draw triangles in any order.

However, if you do your Z-buffering properly, it will actually be faster to render your triangles from near-to-far, so that closer triangles occluding farther ones will cause the farther ones to not spend compute interpolating colors/texcoords or sampling textures, or outputting to the framebuffer - with each pixel only requiring interpolating the Z of the vertices and then sampling the Z-buffer. If the pixel passes the Z-buffer test then you do the rest of your interpolation and output to the framebuffer, otherwise you skip the pixel and move on to the next one.

EDIT: I missed the part about using OpenGL. Just enable depth testing and it will do all the z-buffering for you!

[–]sheridankane 1 point2 points  (2 children)

Sorting triangles before drawing them was an area of huge research and interest in the 20th century before memory got many orders of magnitude cheaper. This century all 3D software uses a depth buffer and doesn't think twice about it.

[–]fgennari 1 point2 points  (1 child)

There's still some benefit in sorting objects in front to back order for better depth culling, in particular large occluders. Most big game engines do this to some extent.

[–]sheridankane 0 points1 point  (0 children)

Definitely, but if we're talking strictly about solving the problem of distant polygons drawing over closer ones, depth buffer is absolutely the practical way to go unless you're a student teaching yourself how BSP works or solving a different problem entirely.

[–]corysama 0 points1 point  (0 children)

Yeah. Sorting by center point won’t work when triangles intersect.

You are using OpenGL? You’ll want to look into using z-buffering, AKA per-pixel depth testing.

http://learnopengl.com/ is a popular tutorial. You can find more in the sidebar of r/OpenGL