# Depth from Graphics3D

Consider this simple 3D rendering with some geometric primitives:

Graphics3D[{Cylinder[{{-1, -1, 0}, {-1, -1, 1}}, .42], Cuboid[],
Polygon[{{-2, -2, 0}, {2, -2, 0}, {2, 2, 0}, {-2, 2, 0}}],
Sphere[{.3, -.6, .5}, .5]}, Boxed -> False]


How can I get the depth of each pixel of the rendering, i.e. the distance of the corresponding point to the camera?

Edit: The required depth image would be something like the OpenGL z-buffer. Vertices alone are not enough - I need the depth of every pixel in the rendered image.

-
I have two applications: One where there are half a million (full image) and one with around 1000 (test points). – Danvil Jul 25 '13 at 10:42
Pixels or vertices? – cormullion Jul 25 '13 at 11:09
You might interested in this question. See, mathematica.stackexchange.com/questions/24211/… – s.s.o Jul 25 '13 at 11:22
@cormullion: Pixel! – Danvil Jul 25 '13 at 12:21

It would certainly be helpful if you could specify your input data. As an example I'll use the scene you proposed above.

Let's first extract the vertices of the 3D scene. One way to achieve this is to export the scene as an .obj and then reimport the vertex data only. Let's neglect the fact that the vertices aren't uniformly distributed over the surfaces.

scene = Graphics3D[{Cylinder[{{-1, -1, 0}, {-1, -1, 1}}, .42], Cuboid[],
Polygon[{{-2, -2, 0}, {2, -2, 0}, {2, 2, 0}, {-2, 2, 0}}], Sphere[{.3, -.6, .5}, .5]},
Boxed -> False, ViewPoint -> {5, 5, 5}]

Export["scene.obj", scene];
impScene = Import["scene.obj", "VertexData"];


The camera location is at position $(5,5,5)$ as defined by ViewPoint above:

cameraLoc = {5, 5, 5};


These are all the lines connecting the camera to the vertices:

Graphics3D[Line[{cameraLoc, #}] & /@ impScene]


The distance from the camera to each of the vertices is easily obtained by:

dist = EuclideanDistance[cameraLoc, #] & /@ impScene;

-
Thanks for the answer, but I need the depth of every pixel not only of vertices. Much like the OpenGL z-Buffer. – Danvil Jul 25 '13 at 12:00