Example 02

Example 02

This is a simple OpenGL program that draws a house and quits when the user presses q.

ex_02/house.png

Source Code

house.cc:

// Peter Bui
// CSE 40166 Computer Graphics (Fall 2010)
// Example 2: house and text
 
#include <cmath>
#include <cstdlib>

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

// Display callback ------------------------------------------------------------

void 
display()
{
    glClearColor(1.0, 1.0, 1.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    // Draw roof
    glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_TRIANGLES); { 
        glVertex2f( 0.00, 0.75);
        glVertex2f( 0.50, 0.50);
        glVertex2f(-0.50, 0.50);
    } glEnd();
    
    glBegin(GL_QUADS); { 
        // Draw house
        glColor3f(0.0, 0.0, 1.0);
        glVertex2f( 0.50, 0.50);
        glVertex2f(-0.50, 0.50);
        glVertex2f(-0.50, -0.50);
        glVertex2f( 0.50, -0.50);

        // Draw door 
        glColor3f(0.0, 1.0, 0.0);
        glVertex2f( 0.20, 0.00);
        glVertex2f(-0.20, 0.00);
        glVertex2f(-0.20, -0.50);
        glVertex2f( 0.20, -0.50);
    } glEnd();

    // Draw door knob
    glBegin(GL_TRIANGLE_FAN); {
        double ox = 0.125, oy = -0.25, radius = 0.05;
        int triangles = 32;

        glColor3f(1.0, 0.0, 0.0);
        glVertex2f(ox, oy);
        for (int i = 0; i <= triangles; i++) {
            double angle = i * 2.0 * M_PI / triangles;
            glVertex2f(ox + radius * cos(angle), oy + radius * sin(angle));
        }
    } glEnd();

    // Draw message
    glColor3f(0.0, 0.0, 0.0);
    glRasterPos2f(-0.30, -0.75);
    for (const char *c = "hello, world!"; *c; c++)
        glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *c);

    glFlush();
}

// Keyboard callback -----------------------------------------------------------

void
keyboard(unsigned char key, int x, int y)
{
    if (key == 'q' || key == 'Q')
        exit(EXIT_SUCCESS);
}

// Main execution --------------------------------------------------------------

int 
main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutCreateWindow("house");
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMainLoop();     

    return (EXIT_SUCCESS);
}

// vim: sts=4 sw=4 ts=8 ft=cpp

Files