我知道还有另一个标题here完全相同的问题,但是在那里提供的解决方案不适用于我的情况。
我正在尝试从我的计算着色器访问像素值。但是imageLoad
函数始终返回0。
这是我加载图像的方式:
void setTexture(GLuint texture_input, const char *fname) {
// set texture related
int width, height, nbChannels;
unsigned char *data = stbi_load(fname, &width, &height, &nbChannels, 0);
if (data) {
GLenum format;
if (nbChannels == 1) {
format = GL_RED;
} else if (nbChannels == 3) {
format = GL_RGB;
} else if (nbChannels == 4) {
format = GL_RGBA;
}
glActiveTexture(GL_TEXTURE0 + 1);
gerr();
glBindTexture(GL_TEXTURE_2D, texture_input);
gerr();
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_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gerr();
glTexImage2D(GL_TEXTURE_2D, // target
0, // level, 0 means base level
format, // internal format of image specifies color
// components
width, height, // what it says
0, // border, should be 0 at all times
format, GL_UNSIGNED_BYTE, // data type of pixel data
data);
gerr();
glBindImageTexture(1, // unit
texture_input, // texture id
0, // level
GL_FALSE, // is layered
0, // layer no
GL_READ_ONLY, // access type
GL_RGBA32F);
// end texture handling
gerr();
glBindTexture(GL_TEXTURE_2D, 0); // unbind
} else {
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
}
这是着色器中的相关声明和调用代码:
layout(rgba32f, location = 1, binding = 1) readonly uniform image2D in_image;
struct ImageTexture {
int width;
int height;
};
vec3 imageValue(ImageTexture im, float u, float v, in vec3 p) {
u = clamp(u, 0.0, 1.0);
v = 1 - clamp(v, 0.0, 1.0);
int i = int(u * im.width);
int j = int(v * im.height);
if (i >= im.width) {
i = im.width - 1;
}
if (j >= im.height) {
j = im.height - 1;
}
vec3 color = imageLoad(in_image, ivec2(i, j)).xyz;
if (color == vec3(0)) {
color = vec3(0, u, v); // debug
}
return color;
}
我看到的是绿色渐变,而不是图像的内容,这意味着我的调试代码有效。
或者纹理的内部格式与glBindImageTexture
中指定的格式不匹配,或者format参数不是有效的枚举器常量,因为对于[[内部格式和[ 格式:
glBindImageTexture
参数是format
的format
glTexImage2D(GL_TEXTURE_2D, // target
0, // level, 0 means base level
format, // internal format of image specifies color
// components
width, height, // what it says
0, // border, should be 0 at all times
format, GL_UNSIGNED_BYTE, // data type of pixel data
data);
:glBindImageTexture
因此,必须为内部格式
GL_RGBA32F
。可能的[[fomrat是glBindImageTexture(1, // unit
texture_input, // texture id
0, // level
GL_FALSE, // is layered
0, // layer no
GL_READ_ONLY, // access type
GL_RGBA32F);
:GL_RGBA32F