OpenGL ES3 帧缓冲区以红色比例绘制深度

OpenGL ES3 framebuffer draw depth in red scale

所以在努力使定向光阴影贴图工作之后,我终于可以看到在四边形上渲染的阴影贴图,但它仅使用深度 GL_DEPTH_COMPONENT16 和类型 GL_UNSIGNED_SHORTGL_DEPTH_COMPONENT32F 并键入 GL_FLOAT 但它是红色比例而不是灰色比例

问题是我用了很多方法计算深度来绘制阴影,但没有出现阴影。

glCullFace(GL_FRONT);
            glGenFramebuffers(1, &depthMapFBO);
            glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
            glGenTextures(1, &depthMap);
            glBindTexture(GL_TEXTURE_2D, depthMap);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, NULL);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);

            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
            glDrawBuffers(1, GL_NONE);
            glReadBuffer(GL_NONE);
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
            glBindTexture(GL_TEXTURE_2D, 0);
            glCullFace(GL_BACK);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    LOGI("framebuffer incomplete");
}

片段是:

uniform mediump sampler2DShadow  shadowMap;
......
float bias = 0.005;
float visibility = 1.0;
for (int i=0;i<4;i++){
    int index = i;
    visibility -= 0.2*(1.0-texture( shadowMap, vec3(FragPosLightSpace.xy + poissonDisk[index]/700.0,  (FragPosLightSpace.z-bias)/FragPosLightSpace.w) ));           
}
result =light.intensity* (visibility * (diffuse + specular));

...but it is in red scale not gray scale

具有深度分量格式的纹理,例如GL_DEPTH_COMPONENT16GL_DEPTH_COMPONENT32F只有1个颜色通道,红色颜色通道。
如果您从绑定了深度分量纹理的纹理采样器读取数据,则会自动设置绿色、蓝色和 alpha 通道。

Khronos group的Image Format规范说:

Image formats do not have to store each component. When the shader samples such a texture, it will still resolve to a 4-value RGBA vector. The components not stored by the image format are filled in automatically. Zeros are used if R, G, or B is missing, while a missing Alpha always resolves to 1.

Note: Texture swizzling can change what the missing values are.

因此,设置了红色,绿色和蓝色设置为 0,alpha 通道为 1。导致不透明的红色表面。

如果你想从深度分量纹理中读取灰度颜色,那么你必须读取红色颜色通道并且你必须将红色通道应用到绿色还有蓝色。

您必须像这样调整代码:

float depth          = texture( shadowMap, ..... ).r;
vec3  depthGrayscale = vec3( depth );

或者这个:

vec3  depthGrayscale = texture( shadowMap, ..... ).rrr;