Advertisement
Guest User

ANSI C to VEX: 2D Line Segments Intersection

a guest
Nov 5th, 2015
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. // Source: http://www.realtimerendering.com/resources/GraphicsGems/gemsii/xlines.c
  2. // Translated to VEX language with some minor changes.
  3. int x_line_line(float x1, y1, x2, y2, x3, y3, x4, y4; export float x, y)
  4. {
  5.     #define DONT_INTERSECT    0
  6.     #define DO_INTERSECT      1
  7.     #define COLLINEAR         2
  8.     #define SAME_SIGNS(a, b) (sign(a) == sign(b))
  9.  
  10.     float a1, a2, b1, b2, c1, c2; // Coefficients of line eqns.
  11.     float r1, r2, r3, r4;         // "Sign" values.
  12.     float denom;                  // Intermediate values.
  13.  
  14.     // Compute a1, b1, c1, where line joining points 1 and 2
  15.     // is "a1x + b1y + c1 = 0".
  16.     a1 = y2 - y1;
  17.     b1 = x1 - x2;
  18.     c1 = x2 * y1 - x1 * y2;
  19.  
  20.     // Compute r3 and r4.
  21.     r3 = a1 * x3 + b1 * y3 + c1;
  22.     r4 = a1 * x4 + b1 * y4 + c1;
  23.  
  24.     // Check signs of r3 and r4. If both point 3 and point 4 lie on same side
  25.     // of line 1, the line segments do not intersect.
  26.     if (r3 != 0 && r4 != 0 && SAME_SIGNS(r3, r4))
  27.     {
  28.         return (DONT_INTERSECT);
  29.     }
  30.  
  31.     // Compute a2, b2, c2.
  32.     a2 = y4 - y3;
  33.     b2 = x3 - x4;
  34.     c2 = x4 * y3 - x3 * y4;
  35.  
  36.     // Compute r1 and r2.
  37.     r1 = a2 * x1 + b2 * y1 + c2;
  38.     r2 = a2 * x2 + b2 * y2 + c2;
  39.  
  40.     // Check signs of r1 and r2. If both point 1 and point 2 lie on same side
  41.     // of second line segment, the line segments do not intersect.
  42.     if (r1 != 0 && r2 != 0 && SAME_SIGNS(r1, r2))
  43.     {
  44.         return (DONT_INTERSECT);
  45.     }
  46.  
  47.     // Line segments intersect: compute intersection point.
  48.     denom = a1 * b2 - a2 * b1;
  49.  
  50.     if (denom == 0)
  51.     {
  52.         return (COLLINEAR);
  53.     }
  54.  
  55.     x = (b1 * c2 - b2 * c1) / denom;
  56.     y = (a2 * c1 - a1 * c2) / denom;
  57.     return (DO_INTERSECT);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement