Hello everyone,
I am writing a post-processing filter shader (using glsl), where I need to calculate the world xyz coordinates of the objects from the pixels. To do that, I am fetching the color and the depth buffers of the scene. THe code for the creation of my filter looks like that.
manager = FilterManager(self.win, self.cam)
color_texture = Texture()
depth_buffer = Texture()
quad = manager.renderSceneInto(colortex = color_texture)
quad = manager.renderSceneInto(depthtex = depth_buffer)
quad.setShader(Shader.load(Shader.SL_GLSL , "vshader.glsl", "fshader.glsl"))
quad.setShaderInput("u_resolution" , self.getSize())
quad.setShaderInput("color_texture", color_texture)
quad.setShaderInput("depth_buffer", depth_buffer)
My vertex shader is very simple. (In fact I would expect not to need a vertex shader for a post-processing filter, but without one I get only black screen) So here it is.
void main(){
gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;}
The magic is meant to happen in the fragment shader, where (among others) I try to calculate the xyz world coordinates in the following way.
void main(){
vec2 st = gl_FragCoord.xy / u_resolution.xy;
// ------------- get information from buffers
float aspect_ratio = u_resolution.y / u_resolution.x;
vec2 texture_uv = st * aspect_ratio;
vec4 color_pixel = texture2D(color_texture, texture_uv.xy);
vec4 depth_pixel = texture2D(depth_buffer, texture_uv.xy);
vec3 world_pos_object = World_position_from_depth(depth_pixel.x, st.xy);
....}
and the function World_position_from_depth(in float depth, in vec2 uv) is as follows:
vec3 World_position_from_depth(in float depth, in vec2 st){
vec2 st_ = st * 2.0 - 1.0; //translate 0s at the center of the image, range [-1,1]
depth = depth * 2.0 - 1.0; //do the same for depth values
vec4 clipSpacePosition = vec4( st_.x, st_.y, depth, 1.);
vec4 viewSpacePosition = p3d_ProjectionMatrixInverse * clipSpacePosition;
viewSpacePosition /= viewSpacePosition.w; // Perspective division
vec4 worldSpacePosition = p3d_ViewMatrixInverse * viewSpacePosition;
return worldSpacePosition.xyz;
}
However when I color my pbjects according to their distance from the camera-eye, the results I get seem wrong. Does anyone have an idea how I can get the world xyz coordinates using the depth buffer?