Drawing with OpenGL
2002-03-22 19:59:57
Category: cpp:opengl
Description: Draw some basic shapes with opengl.
Author: detour
Viewed: 5124
Rating: (16 votes)


/* drawing.cpp written by detour@metalshell.com
 *
 * Shows how to draw a triangle, square and a line, using
 * OpenGL.
 *
 * Some other GLBegin() options that you can play with.
 * ------------------
 * GL_POINTS
 * GL_LINES
 * GL_LINE_LOOP
 * GL_LINE_STRIP
 * GL_TRIANGLES
 * GL_TRIANGLE_STRIP
 * GL_TRIANGLE_FAN
 * GL_QUADS
 * GL_QUAD_STRIP
 * GL_POLYGON
 * ------------------
 *
 * In order to get this to compile you must have the opengl
 * libraries, and header files.  Be sure to include opengl32.lib
 * glut32.lib and glu32.lib when compiling. 
 *
 * http://www.metalshell.com/
 *
 */
 
#include <windows.h>
#include <gl/Gl.h>
#include <gl/Glu.h>
#include <gl/glut.h>
 
void doInit() {
    /* Background and foreground color */
    glClearColor(0.0,0.0,0.0,0.0);
    glColor3f(1.0,1.0,1.0);
 
    /* Select the projection matrix and reset it */
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
 
    /* Our screen coordinates */
    gluOrtho2D(-4,4,-4,4);
}
 
void doDisplay() {
 
    /* Clear the screen with the clearcolor */
    glClear(GL_COLOR_BUFFER_BIT);
 
    /* To start drawing you must use GL_BEGIN with the type of
       drawing you are going to do.  Depending on what type of
       drawing you choose will determine how many points you 
       need to use. For a line you need 2 points, etc. If you
       change the color between each point OpenGL will fade each
       color automatically. */
    
    glBegin(GL_LINES);
        glVertex3f(2.0,1.0f,0.0f);
        glVertex3f(3.5,1.0f,0.0f);
    glEnd();
    
    glBegin(GL_TRIANGLES);
        glColor3f(1.0f,1.0f,0.0f);
        glVertex3f( 0.0f, 1.0f, 0.0f);
        glColor3f(0.0f,1.0f,1.0f);
        glVertex3f(-1.0f,-1.0f, 1.0f);
        glColor3f(1.0f,0.0f,1.0f);
        glVertex3f( 1.0f,-1.0f, 1.0f);
    glEnd();
 
    glBegin(GL_QUADS);
        glColor3f(1.0f,1.0f,0.0f);
        glVertex3f(-3.0f,1.0f,0.0f);
        glColor3f(0.0f,1.0f,0.0f);
        glVertex3f(-3.0f,3.0f,0.0f);
        glColor3f(1.0f,0.0f,0.5f);
        glVertex3f(-1.0f,3.0f,0.0f);
        glColor3f(0.0f,0.0f,1.0f);
        glVertex3f(-1.0f,1.0f,0.0f);
    glEnd();
    
    /* Dump the output to the screen */
    glFlush();
}
 
 
int main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
    glutInitWindowSize(640,480);
    glutInitWindowPosition(0,0);
    glutCreateWindow("Drawing");
 
    glutDisplayFunc(doDisplay);
 
    doInit();
    glutMainLoop();
 
    return 0;
}