1
$\begingroup$

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.

$\endgroup$

1 Answer 1

2
$\begingroup$

There's a subtle difference between depth and what your t variable is (normally referred to as distance). Depth is distance along the camera z direction (=view direction), while t is euclidean distance. You need to first calculate the distance along the z direction, this is

rayOrigin.z + rayDirection.z * t

(rayOrigin and rayDirection being the origin and direction of the ray in view coordinates) and then apply the formula you found.

If you only have your ray parameters in world space, you will need to calculate the full hit position and multiply it by a view matrix.

$\endgroup$
3
  • $\begingroup$ For more context, this is just multiplying by a perspective projection matrix, doing the depth division (dividing the result by its w value) and taking the z coordinate of the result, but since the x and y coordinates don't matter for this, you can simplify it a lot. $\endgroup$ Aug 7, 2022 at 15:46
  • $\begingroup$ 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? $\endgroup$
    – Cascades
    Aug 7, 2022 at 19:28
  • $\begingroup$ @Cascades No, you need to apply the formula you found on github or a projection matrix after you converted it to view space $\endgroup$ Aug 9, 2022 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.