Monday, December 22, 2014

2D Translation Without Using OpenGL Function For Translation

Program to draw a rectangle and translate it without using OpenGL function for translation

#include<stdio.h>
#include<GL/glut.h>

int x, y, p, q, a[10], b[10], da, db, i;
float dx, dy;

void line(int x, int y, int a, int b)
{
  glBegin(GL_LINES);
  glVertex2d(x, y);
  glVertex2d(a, b);
  glEnd();
}

void display_rectangle()
{
  for(i = 0; i < 4; i++)
  {
    if(i != 3)
      line(a[i], b[i], a[i+1], b[i+1]);
    else
      line(a[i], b[i], a[0], b[0]);
  }
}

void Init()
{
  /* Set clear color to white */
  glClearColor(1.0, 1.0, 1.0, 0);
  /* Set fill color to black */
  glColor3f(0.0, 0.0, 0.0);
  gluOrtho2D(0 , 640 , 0 , 480);
}

void translate()
{
  // Find the translated rectangle vertices
  for(i = 0; i < 4; i++)
  {
    a[i] = a[i] + dx; b[i] = b[i] + dy;
  }
}

void transform()
{
 glClear(GL_COLOR_BUFFER_BIT);

  // Find the original rectangle vertices
  da = p-x; db = q-y;
  a[0] = x; b[0] = y;
  a[1] = x + da; b[1] = y;
  a[2] = x + da; b[2] = y + db;
  a[3] = x; b[3] = y + db;
  // Draw original rectangle
  display_rectangle();

  // Perform translation
  translate();
  // Draw translated rectangle using dotted lines
  glEnable(GL_LINE_STIPPLE);
  glLineStipple(1, 0xF0F0);
  display_rectangle();
  glDisable(GL_LINE_STIPPLE);

  glFlush();
}

void main(int argc, char **argv)
{
  printf("\n************************************************\n");
  printf("Enter the upper left corner of the rectangle:\n");
  scanf("%d%d", &x, &y);
  printf("\n************************************************\n");
  printf("Enter the lower right corner of the rectangle:\n");
  scanf("%d%d", &p, &q);

  printf("\n******************Translation******************\n");
  printf("Enter the value of shift vector:\n");
  scanf("%f%f", &dx, &dy);

  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
  glutInitWindowPosition(0, 0);
  glutInitWindowSize(640, 480);
  glutCreateWindow("Translation");
  Init();
  glutDisplayFunc(transform);
  glutMainLoop();
}
Written by

No comments:

Post a Comment