C++ 为什么我必须切换纹理单元才能让片段着色器识别要使用的纹理?

C++ 为什么我必须切换纹理单元才能让片段着色器识别要使用的纹理?,c++,glsl,textures,fragment-shader,multitexturing,C++,Glsl,Textures,Fragment Shader,Multitexturing,我有这个程序是为了简单的测试目的。程序将创建两个1-D纹理并将其传递给着色器。片段着色器非常简单。它只是拉出第一个纹理索引4处的纹理,并使该纹理成为颜色片段: #extension GL_EXT_gpu_shader4 : enable uniform sampler1D firstTexture; uniform sampler1D secondTexture; uniform int max_index; void main() { vec4 texel = te

我有这个程序是为了简单的测试目的。程序将创建两个1-D纹理并将其传递给着色器。片段着色器非常简单。它只是拉出第一个纹理索引4处的纹理,并使该纹理成为颜色片段:

 #extension GL_EXT_gpu_shader4 : enable

 uniform sampler1D firstTexture;
 uniform sampler1D secondTexture;

 uniform int max_index;

 void main()
 {
     vec4 texel = texture1D( firstTexture, float(4.0) / float(max_index));

     gl_FragColor = texel;
 }
我正在画一个正方形,第一个纹理中索引为4的纹理包含红色。因此,上面着色器的结果是一个红色正方形。当我创建第二个1-D纹理并将其传递给着色器时,问题就出现了。出于未知原因,着色器不喜欢它,并且不再工作,并且绘制了一个黑色正方形而不是红色正方形。下面是C++代码:(函数内部的代码“MaxGLASH”如下) 通过函数“makeGLTexture”完成纹理绑定。这是里面的代码

// Define an array that stores the texture's information.
Texel* const texelArray = new Texel[texels.size()];

// Copy information from the vector of texels into the array of texels.
for (unsigned int index = 0; index < texels.size(); index++)
    texelArray[index] = texels[index];



/* ====================
 * Generate the texture.
 * ====================*/

// ID of the texture.
GLuint textureID;

// Generate a texture object ID for this texture.
glGenTextures( 1, &textureID );

// Bind the texture object to the texture identifier.
glBindTexture( GL_TEXTURE_1D, textureID );

// Define the texture image.
glTexImage1D( GL_TEXTURE_1D, 0, GL_RGBA, texels.size(), 0, GL_RGBA, GL_FLOAT, texelArray );

// ===================== //



// Free the memory allocated for the texture array (array of texels).
delete[] texelArray;

// Return the texture ID.
return textureID;
然后,程序将再次工作


我的问题是为什么会这样?着色器不是独立于纹理单元吗?我们不是只需要将纹理单元传递给采样器变量,就这样吗?在这种情况下,为什么必须将纹理单位更改回纹理单位零,着色器才能再次运行?发生了什么事?

我有点担心你的索引代码。IIRC如果你想得到纹理的精确值,你必须击中它的中心,而不是左边缘。基本上是在像素边界上采样。你想做些更像

 vec4 texel = texture1D( firstTexture, float(4.0 + 0.5) / float(max_index + 1));
我假设max_index是纹理的最高有效索引,而不是计数


您使用的是GL_NEAREST,但您现在正在texel 3和texel 4的边界上采样。因此,它可能会选择texel 3作为替代。

我应该补充一点,只有在对相同维度的两个纹理(均为1-D)执行多重纹理时,才会发生这种情况。3-D和1-D纹理似乎工作正常。我不知道二维纹理。听起来像是某种驱动程序错误。您使用的硬件和驱动程序版本是什么?
/* =========================================
 * Set up the second one-dimensional texture.
 * =========================================*/

...

**glActiveTexture(GL_TEXTURE0);**
 vec4 texel = texture1D( firstTexture, float(4.0 + 0.5) / float(max_index + 1));