按照网上的例子,这里是顶点着色器中的代码:
属性定义如下:
// Option 1:
layout (location = 0) in vec3 colorvec3;
layout (location = 1) in mat4x2 xyInBaseImageMat4x2;
out vec2 xyInElementTextureImage;
out vec3 elementTintColorVec3;
在顶点着色器中,它们被使用:
// Option 1
vec2 xyInBaseImageVec2 = xyInBaseImageMat4x2[gl_VertexID];
gl_Position = vec4(xyInBaseImageVec2, 0.0, 1.0);
elementTintColorVec3 = colorvec3;
但结果很奇怪,完全随机。有时是黑色的,有时是随机的形状。
但如果我改用:
// Option 2:
layout (location = 0) in vec3 colorvec3;
layout (location = 1) in vec2 xyInBaseImageVec2_p0;
layout (location = 2) in vec2 xyInBaseImageVec2_p1;
layout (location = 3) in vec2 xyInBaseImageVec2_p2;
layout (location = 4) in vec2 xyInBaseImageVec2_p3;
out vec2 xyInElementTextureImage;
out vec3 elementTintColorVec3;
在顶点着色器中:
// Option 2:
vec2 xyInBaseImageVec2;
if (gl_VertexID==0) {
xyInBaseImageVec2 = xyInBaseImageVec2_p0;
} else if (gl_VertexID==1) {
xyInBaseImageVec2 = xyInBaseImageVec2_p1;
} else if (gl_VertexID==2) {
xyInBaseImageVec2 = xyInBaseImageVec2_p2;
} else if (gl_VertexID==3) {
xyInBaseImageVec2 = xyInBaseImageVec2_p3;
}
gl_Position = vec4(xyInBaseImageVec2, 0.0, 1.0);
elementTintColorVec3 = colorvec3;
然后它按需要工作。
对于这两个示例,颜色和顶点位置的数据缓冲区是相同的。[更新:在下面添加喂食代码]
// refer to the code in: http://sol.gfxile.net/instancing.html
// refer to the code in: http://www.gamedev.net/page/resources/_/technical/opengl/opengl-instancing-demystified-r3226
// Case: instaced vertex positions. So each instance should have 4 vec2
{
// in mat4x2; later try in vec2[4] xyInBaseImage_vec2list if mat4x2 does not work.
GLuint instanceVBO = instancevbo_4pts;
int pos = 1;
int componentsSize = 2; // vec2 has 2 components
// if it is mat, then componentsNum is the column number of the matrix; for example, for mat4x2 it is 4
int componentsNum = 4; // mat4x2
GLenum type = GL_FLOAT;
GLboolean normalized = GL_FALSE;
GLsizei stride = componentsSize * sizeof(GL_FLOAT) * componentsNum;
char* pointerFirstComponentOffset = 0;
int offsetInteger = 0;
int byteSizeOfOneVertexAttribute = componentsSize * sizeof(GL_FLOAT);
GLuint divisor = 1; // 0 not instance
glBindBuffer(GL_ARRAY_BUFFER, instanceVBO);
for (int i = 0; i < componentsNum; i++) {
glEnableVertexAttribArray(pos + i);
// the offset can also be: (void*) (offsetInteger + i * byteSizeOfOneVertexAttribute)
glVertexAttribPointer(pos + i, componentsSize, type,
normalized, stride, pointerFirstComponentOffset + i * byteSizeOfOneVertexAttribute );
glVertexAttribDivisor(pos + i, divisor);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
第一个选项有什么问题?