I'm writing a graphing app and have been advised to use either a z-buffer or the painters algorithm to handle the visibility problem.
I am writing this in an HTML5 canvas so using a z-buffer seems outrageously expensive. For example, if it were a 500x500 canvas and had to loop over just 10 polygons that would be 2,500,000 iterations per frame done in the CPU. I don't know if that's a big number but it seems like the wrong way to do it for this app.
The painters algorithm seems more appropriate. The basic steps are:
1. Sort polygons based on their "z".
2. Paint all polygons, but paint the ones farthest away first.
But I'm confused about how to find their z. Say we were looking top down at the following polygons:
If I were to just find the maximum z (farthest away from screen) red would be considered farther away. So it would paint red first and then overpaint red with orange even though red is in front of orange.
What is the correct way to sort these polygons? Or more generally, when implementing the painters algorithm how do you determine the order of your polygons?
edit: this is why im afraid of rolling my own z-buffer (goes through each pixel and randomly assigns it a color ~10FPS on this five year old i7).