|
For the second lesson, we will finally begin with drawing a couple shapes: a box (quad) and a triangle. Only the DrawGLScene function will be presented here, because that is all that has changed from lesson 1.
Lesson 2 Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 |
int DrawGLScene() {
glLoadIdentity(); glTranslatef(-1.5f,0.0f,-6.0f); glBegin(GL_TRIANGLES); glVertex3f( 0.0f, 1.0f, 0.0f); glVertex3f(-1.0f,-1.0f, 0.0f); glVertex3f( 1.0f,-1.0f, 0.0f); glEnd(); glTranslatef(3.0f,0.0f,0.0f); glBegin(GL_QUADS); glVertex3f(-1.0f, 1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 0.0f); glVertex3f( 1.0f,-1.0f, 0.0f); glVertex3f(-1.0f,-1.0f, 0.0f); glEnd(); return TRUE; }
|
Analyze:
Line 4:
glLoadIdentity();
For our current mode, GL_MODELVIEW, this resets the current matrix to an identity
Line 5: glTranslatef(-1.5f, 0.0f, -6.0f);
This shifts the entire scene (anything rendered after this call) over 1.5 units left and 6.0 units into the screen (assuming there is no view change). Objects can be drawn locally, around the origin, then their positions are multiplied by the current matrix modified by translations and rotations. If you are unfamiliar with the axis for OpenGL, take a look at the Basic 3D lesson in the Tutorials section.
Lines 6 / 14: glBegin( int primitive_type );
There are 6 primitive types that could be used with glBegin():
GL_TRIANGLE - Sets up to be able to draw just one triangle
GL_QUAD - Sets up to draw just one quad
GL_TRIANGLES - Will draw (number of vertices / 3) triangles (numVertices in Begin/End block).
GL_QUADS - Draws (numVerts / 4) quads inside of Begin/End block
GL_TRIANGLE_STRIP - After the first triangle is drawn, for each extra vertex in the block, it will use the previous 2 vertices. Ex: you have 4 vertices, triangle 1 uses verts {1,2,3} and triangle 2 would be {2,3,4}.
GL_QUAD_STRIP - As with triangle_strip, uses previous vertices, but should use the previous 3 vertices, instead.
Line 7: glVertex3f( 0.0f, 1.0f, 0.0f );
Positions the first vertex at the (x,y,z) coords of (0,1,0)
. Because we are using the primitive type of GL_TRIANGLES, we need at least 3 vertices to draw a triangle. If you have extra vertices where numVerts % 3 != 0, it won't render the last triangle, all you're doing is wasting memory with adding the extra vertices.
Line 11: glEnd();
Without this function, you will not see anything drawn on the screen, this finishes off the vertex list and sends to the FIFO for rendering.
Line 12: glTranslatef( 3.0f, 0.0f, 0.0f );
all transformations are relative, they are not reset until glLoadIdentity() is called. Alternatively, this could have been glLoadIdentity(); followed by glTranslatef( 1.5f, 0.0f, -6.0f );
You should now be able to draw some basic shapes! Next lesson: adding color to the vertices.
|