Refactured rendering algotrithm for layer sorting