Search Tutorials

Friday, 14 June 2013

OpenGL code to make simple Triangles

This source code is for making a simple triangle and rectangle.

OpenGL program:-

#include<iostream>
#include<stdlib.h>

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

using namespace std;

void keyPress(unsigned char key,int x,int y)
{

    switch(key)
    {
        case 27:
            exit(0);
   
    }
}

void initRendering()
{
    glEnable(GL_DEPTH_TEST);
}

//Called when the window is resized
void handleResize(int w, int h) {
    //Tell OpenGL how to convert from coordinates to pixel values
    glViewport(0, 0, w, h);
    
    glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective
    
    //Set the camera perspective
    glLoadIdentity(); //Reset the camera
    gluPerspective(45.0,                  //The camera angle
                   (double)w / (double)h, //The width-to-height ratio
                   1.0,                   //The near z clipping coordinate
                   200.0);                //The far z clipping coordinate
}

void drawScene()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
   
    glMatrixMode(GL_MODELVIEW);
   
    glLoadIdentity();
   
    glBegin(GL_TRIANGLES);
   
        glVertex3f(-0.5f, 0.5f, -5.0f);
        glVertex3f(-1.0f, 1.5f, -5.0f);
        glVertex3f(-1.5f, 0.5f, -5.0f);


        glVertex3f(0.5f, 0.5f, -5.0f);
        glVertex3f(1.0f, 1.5f, -5.0f);
        glVertex3f(1.5f, 0.5f, -5.0f);
   
    glEnd();

    glBegin(GL_QUADS);
        glVertex3f(0.5f, 0.0f, -4.0f);
        glVertex3f(0.5f, -0.5f, -4.0f);
        glVertex3f(1.5f, -0.5f, -4.0f);
        glVertex3f(1.5f, 0.0f, -4.0f);

    glutSwapBuffers();
}

int main(int argc,char** argv)
{
    glutInit(&argc,argv);
   
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
   
    glutInitWindowSize(400,400);
   
    glutCreateWindow("Triangle");
   
    initRendering();
   
    glutDisplayFunc(drawScene);
   
    //glutKeyBoardFunc(keyPress);
    glutKeyboardFunc(keyPress);

    glutReshapeFunc(handleResize);
   
    glutMainLoop();
   
    return(0);
}

//Output of the above Program:-

OpenGL code to make simple Triangles

Related Programs:-

Simple Triangle and Bouncing Ball

Simple Cloud

Moving Circle

Moving Car

Simple Fountain

No comments:

Post a Comment

Back to Top