我正在研究使用纹理贴图来保存网格值的 OpenGL ES流体模拟。我需要遍历模仿以下循环的网格:
for (int r = 0; r < 128; r++)
for (int c = 0; c < 128; c++)
process grid element at (c,r)
为了遍历网格,我只是填充了一个四边形,这会导致为每个片段调用我的片段程序。纹理坐标 (0,0), (1,0), (0,1), (1,1) 与顶点 (-1,-1), (+1,-1), (-1 ,+1), (+1,+1) 并将四边形(作为三角形条带)渲染为附加到 FBO 的 128x128 纹理贴图,如下所示:
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, texFrameBuffer);
glViewport(0, 0, TEX_IMAGE_WIDTH, TEX_IMAGE_HEIGHT); // 128 x 128
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glEnableVertexAttribArray(positionAttr);
glVertexAttribPointer(positionAttr, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer);
glEnableVertexAttribArray(texCoordAttr);
glVertexAttribPointer(texCoordAttr, 2, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
顶点着色器仅通过未修改的位置和纹理坐标。为了了解正在生成什么纹理坐标,我决定将纹理坐标捕获到图像中。片段程序将其给定的 2D 纹理坐标分配给输出颜色的红色和绿色通道:
varying vec4 texCoord;
void main() {
gl_FragColor = vec4(texCoord.st,0,1);
}
然后我使用glGetTexImage()
将纹理图像读回客户端空间。以下是图像中每个像素的生成纹理坐标 (s,t) 的示例:
(column, row) = [s, t] -> (128*s, 128*t)
(0,0) = [0.00392157, 0.00392157] -> (0,0)
(1,0) = [0.01176471, 0.00392157] -> (1,0)
(2,0) = [0.01960784, 0.00392157] -> (2,0)
(3,0) = [0.02745098, 0.00392157] -> (3,0)
(4,0) = [0.03529412, 0.00392157] -> (4,0)
(5,0) = [0.04313726, 0.00392157] -> (5,0)
(6,0) = [0.05098040, 0.00392157] -> (6,0)
(7,0) = [0.05882353, 0.00392157] -> (7,0)
(8,0) = [0.06666667, 0.00392157] -> (8,0)
(9,0) = [0.07450981, 0.00392157] -> (9,0)
(10,0) = [0.08235294, 0.00392157] -> (10,0)
<snip>
(125,0) = [0.98039222, 0.00392157] -> (125,0)
(126,0) = [0.98823535, 0.00392157] -> (126,0)
(127,0) = [0.99607849, 0.00392157] -> (127,0)
(0,1) = [0.00392157, 0.01176471] -> (0,1)
(1,1) = [0.01176471, 0.01176471] -> (1,1)
(2,1) = [0.01960784, 0.01176471] -> (2,1)
<snip>
(124,127) = [0.97254908, 0.99607849] -> (124,127)
(125,127) = [0.98039222, 0.99607849] -> (125,127)
(126,127) = [0.98823535, 0.99607849] -> (126,127)
(127,127) = [0.99607849, 0.99607849] -> (127,127)
现在的问题。我试图理解这些生成的坐标。魔法值0.00392157
是(0.5 * 1/127.5)
。我了解 0.5 因子,它充当预先添加的舍入值,但为什么是 127.5? (0.5 * 1/128.0)
会更有意义吗?谁能解释一下这些坐标?我只想从纹理坐标生成整数网格坐标(sampler2Drect
在 OpenGL ES 中没有)。