Generic Vertex Attribute - examples

From OpenGL Wiki
Revision as of 04:46, 30 May 2009 by V-man (talk | contribs)
Jump to navigation Jump to search

With GL 2.0, a new way to specify your vertex information became available : glVertexAttribPointer
You could of course continue to use glVertexPointer, glTexCoordPointer, glNormalPointer, glColorPointer.
If you create a GL 3.0 forward context, you won't be able to use glVertexPointer, glTexCoordPointer, glNormalPointer, glColorPointer.
You must use the generic version in this case : glVertexAttribPointer

One of the requirements is to use shaders. Here is a GLSL example.

 //Vertex Shader
 uniform mat4 ProjectionModelviewMatrix;
 uniform mat4 ModelviewMatrix;
 attribute vec4 InVertex;  //w will be set to 1.0 automatically
 attribute vec2 InTexCoord0;
 attribute vec3 InNormal;
 varying vec2 OutTexCoord0;
 void main()
   gl_Position = ProjectionModelviewMatrix * InVertex;
   OutTexCoord0 = InTexCoord0;
   vec3 normal = vec3(ModelviewMatrix * vec4(InNormal, 0.0);
   //Do lighting computation

Once you compile and link your GLSL shader, you can query the attrib locations :
vertexLoc = glGetAttribLocation(MyShader, "InVertex");
texCoord0Loc = glGetAttribLocation(MyShader, "InTexCoord0");
normalLoc = glGetAttribLocation(MyShader, "InNormal");

The alternative way is to specify the locations yourself :
glBindAttribLocation(MyShader, 0, "InVertex");
glBindAttribLocation(MyShader, 1, "InNormal");
glBindAttribLocation(MyShader, 2, "InTexCoord0");
but in the case you must link the shader AFTER those glBindAttribLocation calls :

and don't forget to check for errors.
int linked;
glGetProgramiv(MyShader, GL_LINK_STATUS, &linked);

int maxLength;
glGetProgramiv(MyShader, GL_INFO_LOG_LENGTH, &maxLength);
maxLength = maxLength + 1;
uchar *pLinkInfoLog = new uchar[maxLength];
glGetProgramInfoLog(MyShader, maxLength, &maxLength, pLinkInfoLog);

For rendering, VBO is recommended. See the VBO page for more info :

glBindBuffer(GL_ARRAY_BUFFER, VertexVBOID);

//Vertices, XYZ, FLOAT. We give GL_FALSE since we don't want normalization
glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex), XXX);
//Normals, XYZ, FLOAT.
glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex), XXX);
//TexCoord0, XY, FLOAT.
glVertexAttribPointer(texCoord0Loc, 2, GL_FLOAT, GL_FALSE, sizeof(MyVertex), XXX);

and the vertex structure would like this :

 struct MyVertex
   float x, y, z;
   float nx, ny, nz;
   float s0, t0;