简体   繁体   English

如何在WebGL2中读取附加到FBO的深度纹理

[英]How to read depth texture attached to FBO in WebGL2

I'm now working on the deferred shading using WebGL2.0. 我现在正在使用WebGL2.0进行延迟着色。 One primary problem I'm now facing is that I can't read the depth value from the DEPTH_ATTACHMENT. 我现在面临的一个主要问题是我无法从DEPTH_ATTACHMENT中读取深度值。 Actually I creat my own GBuffer with a DEPTH24_STENCIL8 texture as DEPTH_ATTACHMENT, then I bind this texture to the sampler and try to read the value in my fragment shader in deferred shading part like this: 实际上,我创建了一个带有DEPTH24_STENCIL8纹理的GBuffer作为DEPTH_ATTACHMENT,然后将该纹理绑定到采样器,并尝试在片段着色器中的延迟着色部分读取值,如下所示:

uniform sampler2D u_depthSampler;
vec4 depthValue = texture(u_depthSampler, v_uv);

Then I set the depthValue as output in my shading fragment shader: 然后在我的着色片段着色器中将depthValue设置为输出:

layout(location = 0) out vec4 o_fragOut;
o_fragColor.xyz = depthValue.xyz;
o_fragColor.w = 1.0;

When doing this on firefox, it didn't report any error, but the output color is just pure red.(which means vec3(1.0, 0.0, 0.0) I think). 在Firefox上执行此操作时,它没有报告任何错误,但输出颜色只是纯红色(我认为这意味着vec3(1.0,0.0,0.0))。 This really confuse me a lot. 这真的让我很困惑。 Can anyone provide some instruction? 谁能提供一些指导? Is there any problem with my glsl code? 我的glsl代码有什么问题吗? THX~ THX〜

The depth buffer is not linear. 深度缓冲区不是线性的。 To linearize it use this formula: 要使其线性化,请使用以下公式:

float f = 1000.0; //far plane
float n = 1.0; //near plane
float z = (2.0 * n) / (f + n - texture2D( diffuse, texCoord ).x * (f - n));

gl_FragColor = vec4(z,z,z, 255)

Sorry that I may made a big mistake that the depth texture is acutually nearly pure red but not really red. 抱歉,我可能犯了一个大错误,即深度纹理实际上几乎是纯红色,但不是真正的红色。 I tried this: 我尝试了这个:

float depthPow = pow(depthValue.x, 10.0);
o_fragOut.xyz = vec3(depthPow);

And I get the right result I think. 我认为我得到了正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM