# How do I convert pathtraced distance to value that is usable by OpenGL's depthbuffer?

I was hoping someone could check my understanding.

I've got a pipeline that does some path tracing, and then draws some debugging rays using standard rasterization. I'm trying to get depth to work between the two.

In my path tracer I have t, the distance from the camera position to the closest surface intersection or the ray in world space. I want this t to be converted to something that can be directly used by the standard OpenGL/glsl depth buffer. Am I correct in thinking that using the z buffer formulae from Wikipedia directly on my t should work?

float far = 10000.0;
float near = 0.1;

// From Wikipedia
float depth_value = (far + near) / (far - near) + ((1.0 / t)*((-2.0 * far * near)/(far - near)));

depth_value = (depth_value + 1.0) / 2.0; // I did this to convert from (-1,1) to (0,1)


This gives me something close to working, but not quite correct. However, if my logic is correct, my issue could lie elsewhere in my code. For the record, I'm using OpenGL with gl_FragDepth at the end of the pathtracing step.

rayOrigin.z + rayDirection.z * t

• vec4 world_space_point = vec4(ray_pos + ray_dir * t, 1.0); vec4 view_space_point = view_matrix * world_space_point; view_space_point /= view_space_point[3]; float depth_value = world_space_point.z; Just to check, this should be correct in your opinion? Aug 7, 2022 at 19:28