Computer Graphics Lab Manual 2
Computer Graphics Lab Manual 2
OpenGL provides several primitive types that you can use to draw basic shapes and objects.
These primitives are the fundamental building blocks for creating graphics in OpenGL. Here are
the most common OpenGL primitives:
Points (GL_POINTS):
Often used for rendering particle systems, stars, or other small point-based objects.
Lines (GL_LINES):
Lines can be used to create basic shapes, such as triangles and rectangles, by connecting the
endpoints.
Similar to GL_LINE_STRIP, but it forms a closed loop by connecting the last vertex to the first
vertex.
Triangles (GL_TRIANGLES):
Used to draw a sequence of triangles.
Triangles are the most common primitive for rendering complex 3D models.
Similar to GL_TRIANGLES, but all triangles share a common vertex, forming a fan-like shape.
Useful for drawing objects with a central point, like a fan or circular objects.
Quads (GL_QUADS):
Polygon (GL_POLYGON):
#include <GL/glut.h>
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(5.0); // Set point size
glColor3f(0.0, 0.0, 0.0); // Black color (R, G, B)
glBegin(GL_LINES);
glVertex2f(-0.5, 0.5); // v1 (top-left)
glVertex2f(0.5, 0.5); // v2 (top-right)
glVertex2f(-0.5, -0.5); // v3 (bottom-left)
glVertex2f(0.5, -0.5); // v4 (bottom-right)
glEnd();
glFlush();
}
void init() {
glClearColor(1.0, 1.0, 1.0, 1.0); // Set clear color to white
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400, 400);
glutCreateWindow("2D Coordinate System");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
Sample OpenGL code to display Line strip
In order to draw 𝑛 lines at least we must have 𝑛 + 1 points
GL_LINE_STRIP primitive draw line starting from the ending point of the previous line.
#include <GL/glut.h>
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(5.0); // Set point size
glColor3f(0.0, 0.0, 0.0); // Black color (R, G, B)
glBegin(GL_LINE_STRIP);
glVertex2f(-0.5, 0.5); // v1 (top-left)
glVertex2f(0.5, 0.5); // v2 (top-right)
glVertex2f(-0.5, -0.5); // v3 (bottom-left)
glVertex2f(0.5, -0.5); // v4 (bottom-right)
glEnd();
glFlush();
}
void init() {
glClearColor(1.0, 1.0, 1.0, 1.0); // Set clear color to white
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400, 400);
glutCreateWindow("OpenGL line Drawing");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
OpenGL Code to display two lines crossing each other at 𝟎, 𝟎 and they for 2D cartesian plane.
#include <GL/glut.h>
void display(){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
glPointSize(5);
glBegin(GL_LINES);
glVertex2f(-1,0.0);
glVertex2f(1,0.0);
glVertex2f(0.0,-1);
glVertex2f(0.0,1);
glEnd();
glFlush();
}