Develop a program to demonstrate 2D transformation on basic objects
Program:
#include <GL/glut.h>
// Vertex coordinates for a square
GLfloat squareVertices[4][2] = {
{-0.5, -0.5},
{0.5, -0.5},
{0.5, 0.5},
{-0.5, 0.5}
};
// Vertex coordinates for a triangle
GLfloat triangleVertices[3][2] = {
{-0.5, -0.5},
{0.5, -0.5},
{0.0, 0.5}
};
// Transformation parameters
GLfloat tx = 0.0, ty = 0.0; // Translation
GLfloat sx = 1.0, sy = 1.0; // Scaling
GLfloat angle = 0.0; // Rotation angle
void drawSquare() {
glBegin(GL_QUADS);
for (int i = 0; i < 4; i++) {
glVertex2fv(squareVertices[i]);
}
glEnd();
}
void drawTriangle() {
glBegin(GL_TRIANGLES);
for (int i = 0; i < 3; i++) {
glVertex2fv(triangleVertices[i]);
}
glEnd();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
// Apply transformations and draw square
glPushMatrix();
glTranslatef(tx, ty, 0.0);
glRotatef(angle, 0.0, 0.0, 1.0);
glScalef(sx, sy, 1.0);
glColor3f(1.0, 0.0, 0.0); // Red color for square
drawSquare();
glPopMatrix();
// Apply transformations and draw triangle
glPushMatrix();
glTranslatef(tx + 1.0, ty + 1.0, 0.0);
glRotatef(angle, 0.0, 0.0, 1.0);
glScalef(sx, sy, 1.0);
glColor3f(0.0, 0.0, 1.0); // Blue color for triangle
drawTriangle();
glPopMatrix();
glFlush();
}
void init() {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
}
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 't': ty += 0.1; break; // Translate up
case 'e': angle -= 5.0; break; // Rotate clockwise
case 'i': sy += 0.1; sx += 0.1; break; // Scale up vertically
case 27: exit(0); // ESC key to exit
}
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("2D Transformations");
init();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
