Depth as the distance to the camera plane in GLSL

I have a couple of GLSL shaders that give me a map of the depths of objects in my scene. Now I get the distance from each pixel to the camera. I need the distance from the pixel to the plane of the camera. Let me illustrate with a small drawing.

   *          |--*
  /           |
 /            |
C-----*       C-----*
 \            |
  \           |
   *          |--*

3 asterisks are pixels, and C is a camera. Lines of asterisks are "depth." In the first case, I get the distance from the pixel to the camera. In the second, I want to get the distance from each pixel to the plane.

There must be a way to do this using some forecast matrix, but I'm at a dead end.

Here are the shaders that I use. Note that eyePosition is camera_position_object_space.

Vertex Shader:

void main() {
    position = gl_Vertex.xyz;
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

Pixel Shader:

uniform vec3 eyePosition;
varying vec3 position;


void main(void) {
        vec3 temp = vec3(1.0,1.0,1.0);
        float depth = (length(eyePosition - position*temp) - 1.0) / 49.0;
        gl_FragColor = vec4(depth, depth, depth, 1.0);
}
+5
source share
3

. .

varying float distToCamera;

void main()
{
    vec4 cs_position = glModelViewMatrix * gl_Vertex;
    distToCamera = -cs_position.z;
    gl_Position = gl_ProjectionMatrix * cs_position;
}

(, / ), Z- ( Z ).

, - eyePosition; "" .

+9

, , - . . , , , z . z [-1,1], z- NDC.

, " " ( ) , . . , . . , MVP- , .

. , , . , . , , - , , .

, OpenGL (3.x), , , (gl_Vertex, gl_ModelViewProjectionMatrix ..). , .

, , . , , - :

uniform mat4 orthographicMatrix;
varying vec3 position;

void main(void) {
        vec4 clipSpace = orthographicMatrix * vec4(position, 1.0);
        gl_FragColor = vec4(clipSpace.zzz, 1.0);
}

, w , ( , w 1).

+1

The W component after the projection contains the orthogonal depth in the scene. For this you do not need to use separate models and projection matrices:

varying float distToCamera;

void main()
{
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
    distToCamera = gl_Position.w;
}
+1
source

All Articles