Last active
April 29, 2024 16:55
-
-
Save vishal-wadhwa/b746e917b9e362a273257bac21d9530b to your computer and use it in GitHub Desktop.
OpenGL code to rotate, translate and scale a rectangle using basic matrix transforms, written in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by vishal on 11/1/17. | |
// | |
#include <GL/glut.h> | |
#define SCREEN_WIDTH 640 | |
#define SCREEN_HEIGHT 480 | |
typedef struct { | |
GLfloat x, y; | |
} Point; | |
const Point sqr[] = { | |
{20, 30}, | |
{20, 80}, | |
{100, 80}, | |
{100, 30} | |
}; | |
GLfloat tr_matrix[][3] = { | |
{1, 0, 200}, | |
{0, 1, 10}, | |
{0, 0, 1} | |
}; | |
GLfloat sc_matrix[][3] = { | |
{2, 0, 0}, | |
{0, 3, 0}, | |
{0, 0, 1} | |
}; | |
//sin45 = 0.707 | |
GLfloat rt_matrix[][3] = { | |
{0.707, -0.707f, 0}, | |
{0.707, 0.707, 0}, | |
{0, 0, 1} | |
}; | |
Point multiply(GLfloat m[][3], Point v) { | |
GLfloat arr[] = {v.x, v.y, 1}, ans[] = {0, 0, 1}; | |
int i, j; | |
for (i = 0; i < 3; i++) { | |
for (j = 0; j < 3; j++) { | |
ans[i] += m[i][j] * arr[j]; | |
} | |
} | |
Point p = {ans[0], ans[1]}; | |
return p; | |
} | |
void init_graph(int argc, char **argv) { | |
glutInit(&argc, argv); | |
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); | |
glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT); | |
glutCreateWindow(argv[0]); | |
glClearColor(1.0, 1.0, 1.0, 0.0); | |
glPointSize(1.0f); | |
glMatrixMode(GL_PROJECTION); | |
glLoadIdentity(); | |
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); | |
} | |
void close_graph() { | |
glutMainLoop(); | |
} | |
void init() { | |
glClear(GL_COLOR_BUFFER_BIT); | |
const int xshift = 300; | |
const int yshift = 300; | |
//original | |
glColor3f(0.5, 0.5, 0.5); | |
glBegin(GL_LINE_LOOP); | |
for (int i = 0; i < 4; ++i) { | |
glVertex2f(sqr[i].x, sqr[i].y); | |
} | |
glEnd(); | |
//translated | |
glColor3f(1, 0, 0); | |
glBegin(GL_LINE_LOOP); | |
for (int j = 0; j < 4; ++j) { | |
Point p = multiply(tr_matrix, sqr[j]); | |
glVertex2f(p.x, p.y); | |
} | |
glEnd(); | |
//scaled | |
glColor3f(0, 1, 0); | |
glBegin(GL_LINE_LOOP); | |
for (int k = 0; k < 4; ++k) { | |
Point p = multiply(sc_matrix, sqr[k]); | |
glVertex2f(xshift + p.x, p.y); | |
} | |
glEnd(); | |
//rotated | |
glColor3f(0, 0, 1); | |
glBegin(GL_LINE_LOOP); | |
for (int l = 0; l < 4; ++l) { | |
Point p = multiply(rt_matrix, sqr[l]); | |
glVertex2f(xshift/2 + p.x, yshift/2 + p.y); | |
} | |
glEnd(); | |
glFlush(); | |
} | |
int main(int argc, char **argv) { | |
init_graph(argc, argv); | |
glutDisplayFunc(init); | |
close_graph(); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks very much that's help me❤️❤️❤️❤️