The most interesting part of the code deals with the key issue of sorting the scene objects according to the "is behind" relation:
depth_sortcan be seen as a very crude implementation of topological sorting where an edge from object A to object B exists if A is behind B.
depth_sortrunning time is O(n3), acceptable only for low values of n. During the execution of the routine, the variable
separates the elements that have been sorted so far from those that still have not. The observant reader might have noticed that the presence of the following line:
is an expedient hack that acts just in case the pivot did not advance after a pass through the elements; this happens when there are "is behind" cycles as we discussed previously. You can try yourself to move the blocks into such cyclic positions and see the effect on rendering.