# Sorting Triangle vertices based on indices for alpha blending (back to front) C++, OpenGL

I have implemented in OpenGL alpha blending for a triangle mesh. I render this mesh using a vector of indices that indicate which vertex from a vertices vector should be drawn. The problem is to correctly apply the translucency triangles should be sorted from back to front (based on the distance from the camera). Sorting just the indices list wont do it because i need 3 indices to create a triangle everytime. Is there a way to sort the vertices list so that the indices point correctly to that list without changing the order of the indices?

Thank you very much,

Any help appreciated!

You can use a stable sorting algorithm. Take the array $$[1,\ldots,3n]$$, and sort it according to a rule like $$\text{sorts-before}(i, j) = \text{in-front-of}\big(\text{triangle}(\lfloor\tfrac{i}{3}\rfloor), \text{triangle}(\lfloor\tfrac{j}{3}\rfloor)\big).$$ (Here $$\text{sorts-before}$$ is the comparator function $$i\prec j$$ you pass to the sort function.)
If the algorithm is stable, it has the property that when both $$\text{sorts-before}(i,j)$$ and $$\text{sorts-before}(j,i)$$ are false, the order of $$i$$ and $$j$$ will be preserved in the sorted array. In particular, if you make sure that $$\text{sorts-before}(i,j)$$ is always false when $$i,j$$ belong to the same triangle, the stable sorting algorithm will be required to keep the triples of indices together in the right order, and only reorder the triples.