OpenGL:从GLSL中的窗口空间坐标计算出眼睛空间坐标? [英] OpenGL: Compute eye space coord from window space coord in GLSL?

查看:195
本文介绍了OpenGL:从GLSL中的窗口空间坐标计算出眼睛空间坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从GLSL中的窗口空间(帧缓冲区中的像素)坐标+像素深度值(例如GLSL中的gluUnproject)计算出眼睛空间坐标?

How do I compute an eye space coordinate from window space (pixel in the frame buffer) coordinates + pixel depth value in GLSL please (gluUnproject in GLSL so to speak)?

推荐答案

好,opengl.org上的一个人指出,投影生成的剪辑空间坐标被clipPos.w除以计算归一化的设备坐标.将步骤从ndc上的片段反转到剪辑空间坐标时,您需要重建w(恰好是从对应的视图空间(相机)坐标开始的-z),并将ndc坐标与该值相乘以计算适当的剪辑空间坐标(您可以通过将其乘以逆投影矩阵将其转换为视图空间坐标).

Well, a guy on opengl.org has pointed out that the clip space coordinates the projection produces are divided by clipPos.w to compute the normalized device coordinates. When reversing the steps from fragment over ndc to clip space coordinates, you need to reconstruct that w (which happens to be -z from the corresponding view space (camera) coordinate), and multiply the ndc coordinate with that value to compute the proper clip space coordinate (which you can turn into a view space coordinate by multiplying it with the inverse projection matrix).

以下代码假定您正在后期处理中处理帧缓冲区.在渲染几何图形时对其进行处理时,可以使用gl_FragCoord.z代替texture2D(sceneDepth,ndcPos.xy).r.

The following code assumes that you are processing the frame buffer in a post process. When processing it while rendering geometry, you can use gl_FragCoord.z instead of texture2D (sceneDepth, ndcPos.xy).r.

这是代码:

uniform sampler2D sceneDepth;
uniform mat4 projectionInverse;
uniform vec2 clipPlanes; // zNear, zFar
uniform vec2 windowSize; // window width, height

#define ZNEAR clipPlanes.x
#define ZFAR clipPlanes.y

#define A (ZNEAR + ZFAR)
#define B (ZNEAR - ZFAR)
#define C (2.0 * ZNEAR * ZFAR)
#define D (ndcPos.z * B)
#define ZEYE -(C / (A + D))

void main() 
{
vec3 ndcPos;
ndcPos.xy = gl_FragCoord.xy / windowSize;
ndcPos.z = texture2D (sceneDepth, ndcPos.xy).r; // or gl_FragCoord.z
ndcPos -= 0.5;
ndcPos *= 2.0;
vec4 clipPos;
clipPos.w = -ZEYE;
clipPos.xyz = ndcPos * clipPos.w;
vec4 eyePos = projectionInverse * clipPos;
}

基本上,这是gluUnproject的GLSL版本.

Basically this is a GLSL version of gluUnproject.

这篇关于OpenGL:从GLSL中的窗口空间坐标计算出眼睛空间坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆