Tuesday, 10 June 2014

Cyrus Beck Clipping Algorithm



/* This routine performs 2D clipping. It is assumed that user  
/* will supply window and line co-ordinates.                
/* For the window only two co-ordinates are needed: left-bottom
/* and the right-top corner co-ordinates respectively.        

/******************************************************************/

#include<stdio.h>

#define k 4

struct point {float x; float y;};
struct point EndPt[2], WinPt[2], NewPt[2];
struct point n[k], D, w[k];

float dn, wn;

main()
{
 int i;
 float t, tmin = 0.0, tmax = 1.0;

 for(i=0;i<2;i++)
   {
    printf("\nGive input line end point[%d]:",i);
    scanf("%f %f", &EndPt[i].x, &EndPt[i].y);
   }
 for(i=0;i<2;i++)
   {
    printf("\nGive Window corner point[%d]:",i);
    scanf("%f %f", &WinPt[i].x, &WinPt[i].y);
   }

 D.x = EndPt[1].x - EndPt[0].x;
 D.y = EndPt[1].y - EndPt[0].y;

 n[0].x = 1; n[0].y = 0;  // normal to left boundary
 n[1].x = -1; n[1].y = 0; // normal to right boundary
 n[2].x = 0; n[2].y = 1;  // normal to bottom boundary
 n[3].x = 0; n[3].y = -1; // normal to top boundary

 w[0].x = EndPt[0].x - WinPt[0].x;
 w[0].y = EndPt[0].y - WinPt[0].y;

 w[2].x = EndPt[0].x - WinPt[0].x;
 w[2].y = EndPt[0].y - WinPt[0].y;

 w[1].x = EndPt[0].x - WinPt[1].x;
 w[1].y = EndPt[0].y - WinPt[1].y;

 w[3].x = EndPt[0].x - WinPt[1].x;
 w[3].y = EndPt[0].y - WinPt[1].y;

 for(i=0;i<k;i++)
 {
  dn = D.x * n[i].x + D.y * n[i].y; // dot product D dot n
  wn = w[i].x * n[i].x + w[i].y * n[i].y; // dot product w dot n

  if(dn != 0.0)
   {
    t=-wn/dn;
    if (dn > 0.0)
       {
        if(t <= 1.0)
          if (t>tmin) tmin=t;
       }
    else if (dn < 0.0)
       {  
        if(t >= 0.0)
          if(t<tmax) tmax=t;
       }
   }
  printf("%d) %4.2f %4.2f   %4.2f   %4.2f %4.2f\n", i, wn, dn, t, tmin, tmax);
 }
 if(tmax>tmin)
    { 
     NewPt[1].x = EndPt[0].x + tmax * D.x;
     NewPt[1].y = EndPt[0].y + tmax * D.y;
     NewPt[0].x = EndPt[0].x + tmin * D.x;
     NewPt[0].y = EndPt[0].y + tmin * D.y;
    }
   //line(round(NewPt[0].x),round(NewPt[0].y),round(NewPt[1].x),round(NewPt[1].y));
   printf("\n%4.2f %4.2f, %4.2f %4.2f\n", NewPt[0].x, NewPt[0].y, NewPt[1].x, NewPt[1].y);
}

/* Instructions are used for text mode outputs only. Students may convert it into a graphics mode program.                    
/* Here, a regular-rectangular window is used only. Students are advised to write a general program.                      
/*******************************************************************/

No comments:

Post a Comment