Refactors and adding 3D distance function.