Advertisement
Shailrshah

Liang-Barsky Line Clipping Algorithm

Sep 18th, 2014
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <graphics.h>
  3. #define X1 20
  4. #define Y1 20
  5. #define X2 80
  6. #define Y2 110
  7. #define XMIN 40
  8. #define YMIN 40
  9. #define XMAX 100
  10. #define YMAX 90
  11. #define M 3
  12. int main(){
  13.     int i, gd = DETECT,gm;
  14.     initgraph(&gd, &gm, NULL);
  15.     line(M*X1, M*Y1, M*X2, M*Y2);
  16.     delay(5000);
  17.     float p[4], q[4], r, t1 = 0, t2 = 1, xx1, yy1, xx2, yy2;
  18.     p[0] = -(X2-X1);  p[1] = (X2-X1);
  19.     p[2] = -(Y2-Y1);  p[3] = (Y2-Y1);
  20.     q[0] = (X1-XMIN); q[1] = (XMAX-X1);
  21.     q[2] = (Y1-YMIN); q[3] = (YMAX-Y1);
  22.     for(i=0; i < 4; i++){  
  23.         r = q[i]/p[i];
  24.         if(p[i] == 0 && q[i] < 0){
  25.         printf("Line is completly outside.\n");
  26.         return;
  27.         }
  28.         else if(r > t1 && p[i] < 0) t1 = r;
  29.         else if(r < t2 && p[i] > 0) t2 = r;
  30.     }
  31.     cleardevice();
  32.     if(t1 > t2){
  33.         printf("Line is completly outside.\n");
  34.         return 0;
  35.     } else{
  36.         printf("t1 = %f, t2 = %f\n", t1, t2);
  37.         xx1 = X1 + t1 * (X2 - X1);
  38.         yy1 = Y1 + t1 * (Y2 - Y1);
  39.         xx2 = X1 + t2 * (X2 - X1);
  40.         yy2 = Y1 + t2 * (Y2 - Y1);
  41.         printf("(%.2f, %.2f) to (%.2f, %.2f)\n", xx1, yy1, xx2, yy2);
  42.         rectangle(M*XMIN, M*YMIN, M*XMAX, M*YMAX);
  43.         line(M*xx1, M*yy1, M*xx2, M*yy2);
  44.         delay(5000);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement