Tuesday, July 22, 2008

Drawing primitives on OpenGL ES

Unlike the OpenGL, the OpenGL ES do not provide glBegin and glEnd for drawing primitives, such as triangles and quads. Instead, one has to use vertex array. 

First we have to specify the vertices in an array. 

// Four vertices of a simple rectangle 
GLfloat vertices = {0,0, 1,0, 0,1, 1,1} ;
// Texture coordinates 
GLfloat tex_coords = {0,0, 1,0, 0,1, 1,1} ; 

//Set vertex pointer and texture coordinate pointer
glVertexPointer(2, GL_FLOAT, 0, vertices) ;
glTexCoordPointer(2, GL_SHORT, 0, tex_coords) ;

glVertexPointer indicate the array of vertices. the 1st argument represents the number of coordinates (dimensions) of a vertex, 2nd one means the type of coordinate values. The 3rd argument describes there is a stride between two consecutive vertex coordinates. The 4th one is the pointer to the array of vertices coordinates. glTexCoordPointer works in the same manner.  

// Then, enable the client state
glEnableClientState(GL_VERTEX_ARRAY) ;
glEnableClientState(GL_TEXTURE_COORD_ARRAY) ; 

In a drawing function, glDrawArrays(GLenum mode, GLint first, GLsizei count) perform rendering the primitives defined in a vertex array. mode represents the type of primitives such as GL_TRIANGLE, GL_QUADS, etc. and first specifies the starting index in the enabled arrays. count is the number of indices to be rendered. Since we are going to render a rectangle using two triangles and have 4 vertices, the function call will be : 

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) ;

If there are two or more objects defined in different vertex arrays, we have call glEnableClientState and glDisableClientState before and after setting arrays and calling glDrawArrays. 

Some tutorials about vertex array are found in : 
  • http://www.songho.ca/opengl/gl_vertexarray.html
  • http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=45 

2 comments:

  1. hello, may i know, do you develop this code using Xcode in mac OSX? can you share your system requirement for openGL ES development?

    TQ so much..

    ReplyDelete
  2. dnasura/ Of course I'm using XCODE on OSX 10.5. You can use iPhone simulator for development.

    ReplyDelete