Search This Blog

Showing posts with label Computer Graphics. Show all posts
Showing posts with label Computer Graphics. Show all posts

Friday, March 10, 2017

Draw Some Basic Shapes Using OpenGL

Here, we are required to draw some basic shapes (squares, triangles, etc.) using OpenGL.

We use the so-called "old-fashioned" OpenGL.

Below is the code.

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <GL/gl.h>
#include <GL/glut.h>

using namespace std;


void renderScene(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Draw a green triangle.
    glBegin(GL_TRIANGLES);
    glColor3f(0.0f, 1.0f, 0.0f);
    glVertex3f(0.3, 0.3, 0.0);
    glVertex3f(0.4, 0.4, 0.0);
    glVertex3f(0.4, 0.6, 0.0);
    glEnd();

    // Different colors for each vertex.
    glBegin(GL_TRIANGLES);
    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3f(0.0, 0.1, 0.0);
    glColor3f(0.0f, 1.0f, 0.0f);
    glVertex3f(0.1, -0.1, 0.0);
    glColor3f(0.0f, 0.0f, 1.0f);
    glVertex3f(-0.1, -0.1, 0.0);
    glEnd();
    
    // Draw a line.
    glBegin(GL_LINE_STRIP);
    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex2f(0.5, 0.5);
    glVertex2f(0.7, 0.7);
    glEnd();

    // Draw a polygon.
    glBegin(GL_POLYGON);
    glVertex2f(0.75, 0.75);
    glVertex2f(0.75, 0.95);
    glVertex2f(0.95, 0.95);
    glVertex2f(0.95, 0.75);
    glEnd();

    // Draw a triangle strip.
    glBegin(GL_TRIANGLE_STRIP);
    glVertex2f(-0.3, -0.3);
    glVertex2f(-0.3, -0.5);
    glVertex2f(-0.6, -0.7);
    glVertex2f(-0.6, -0.4);
    glVertex2f(-0.9, -0.9);
    glEnd();
    
    glFlush();
}

int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutCreateWindow("Hello OpenGL");
    glutDisplayFunc(renderScene);
    glutMainLoop();
    return 0;

}

This is by far the simplest implementation of drawing a triangle using OpenGL I have seen on the Internet. I'm sure you are going to appreciate this, because it's really simple.