2. Develop a program to demonstrate basic geometric operations on the 2D object.
#include <GL/glut.h>
#include <stdio.h>
float squareX = 0.0f;
float squareY = 0.0f;
float squareSize = 0.2f;
void init()
{
glClearColor(1.0, 1.0, 1.0, 1.0); // Set background color to white
gluOrtho2D(-1.0, 1.0, -1.0, 1.0); // Set the clipping area
}
void drawSquare()
{
glColor3f(0.0, 0.0, 0.0); // Set square color to black
glBegin(GL_QUADS);
glVertex2f(squareX, squareY);
glVertex2f(squareX + squareSize, squareY);
glVertex2f(squareX + squareSize, squareY + squareSize);
glVertex2f(squareX, squareY + squareSize);
glEnd();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
glLoadIdentity(); // Load the identity matrix
drawSquare();
glFlush(); // Flush OpenGL buffer
}
void reshape(int width, int height)
{
glViewport(0, 0, width, height); // Set the viewport to cover the new window
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'w':
squareY += 0.05f; // Move square upwards
break;
case 's':
squareY -= 0.05f; // Move square downwards
break;
case 'a':
squareX -= 0.05f; // Move square to the left
break;
case 'd':
squareX += 0.05f; // Move square to the right
break;
case 27:
exit(0); // Exit program when 'Esc' key is pressed
break;
}
glutPostRedisplay(); // Mark the current window for redisplay
}
int main(int argc, char** argv)
{
glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set display mode
glutInitWindowSize(500, 500); // Set window size
glutInitWindowPosition(100, 100); // Set window position
glutCreateWindow("vtucode| Basic Geometric Operations"); // Create the window with the given title
init(); // Initialize drawing
glutDisplayFunc(display); // Register display callback function
glutReshapeFunc(reshape); // Register reshape callback function
glutKeyboardFunc(keyboard); // Register keyboard callback function
glutMainLoop(); // Enter the main loop
return 0;
}
OUTPUT:
braham@braham:~/Desktop/program$ g++ program2.cpp -lGL -lGLU -lglut -o program2
braham@braham:~/Desktop/program$ ./program2