我想使用一维纹理(颜色渐变)来纹理一个简单的三角形。
我的片段着色器如下所示:
#version 420
uniform sampler1D colorRamp;
in float height;
out vec4 FragColor;
void main()
{
FragColor = texture(colorRamp, height).rgba;
}
我的顶点着色器如下所示:
#version 420
layout(location = 0) in vec3 position;
out float height;
void main()
{
height = (position.y + 0.75f) / (2 * 0.75f);
gl_Position = vec4( position, 1.0);
}
绘制三角形时,我以这种方式进行(为了更好的可读性,我删除了错误检查表单代码):
glUseProgram(program_);
GLuint samplerLocation = glGetUniformLocation(program_, name.toCString());
glUniform1i(samplerLocation, currentTextureUnit_);
glActiveTexture( GL_TEXTURE0 + currentTextureUnit_ );
glBindTexture(GL_TEXTURE_1D, textureId);
不幸的是,我的三角形只有黑色。任何想法如何解决这个问题?
我很确定分配的纹理填充了正确的数据,因为我读回glGetTexImage
并检查了它。我需要调用其他函数来绑定和激活纹理吗?对于 2d 纹理,我有几乎相同的代码。
当我以这种方式更改着色器代码时:
#version 420
uniform sampler1D colorRamp;
in float height;
out vec4 FragColor;
void main()
{
FragColor = vec4(height, height, height, 1.0); // change!
}
我得到这个输出:
我准备了一些重现错误的演示源代码。来源可以在这里找到。它生成以下输出:
一维纹理以这种方式创建 - 只有红色像素:
static GLuint Create1DTexture()
{
GLuint textureId_;
// generate the specified number of texture objects
glGenTextures(1, &textureId_);
assert(glGetError() == GL_NO_ERROR);
// bind texture
glBindTexture(GL_TEXTURE_1D, textureId_);
assert(glGetError() == GL_NO_ERROR);
// tells OpenGL how the data that is going to be uploaded is aligned
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
assert(glGetError() == GL_NO_ERROR);
float data[] =
{
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f
};
glTexImage1D(
GL_TEXTURE_1D, // Specifies the target texture. Must be GL_TEXTURE_1D or GL_PROXY_TEXTURE_1D.
0, // Specifies the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image.
GL_RGBA32F,
3*sizeof(float)*4,
0, // border: This value must be 0.
GL_RGBA,
GL_FLOAT,
data
);
assert(glGetError() == GL_NO_ERROR);
// texture sampling/filtering operation.
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
assert(glGetError() == GL_NO_ERROR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_REPEAT);
assert(glGetError() == GL_NO_ERROR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
assert(glGetError() == GL_NO_ERROR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
assert(glGetError() == GL_NO_ERROR);
glBindTexture(GL_TEXTURE_1D, 0);
assert(glGetError() == GL_NO_ERROR);
return textureId_;
}
纹理绑定是这样完成的:
GLuint samplerLocation = glGetUniformLocation(rc.ToonHandle, "ColorRamp");
glUniform1i(samplerLocation, 0);
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_1D, rc.texure1d);