SegIntersect

PURPOSE ^

SEGINTERSECT - test of segments intersection

SYNOPSIS ^

function bool=SegIntersect(seg1,seg2)

DESCRIPTION ^

SEGINTERSECT - test of segments intersection

   return 1 if the two segments intersect
   seg1=[x1 y1; x2 y2]

   Usage:
      bool=SegIntersect(seg1,seg2)

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function bool=SegIntersect(seg1,seg2)
0002 %SEGINTERSECT - test of segments intersection
0003 %
0004 %   return 1 if the two segments intersect
0005 %   seg1=[x1 y1; x2 y2]
0006 %
0007 %   Usage:
0008 %      bool=SegIntersect(seg1,seg2)
0009 
0010 bool=1;
0011 
0012 xA=seg1(1,1); yA=seg1(1,2);
0013 xB=seg1(2,1); yB=seg1(2,2);
0014 xC=seg2(1,1); yC=seg2(1,2);
0015 xD=seg2(2,1); yD=seg2(2,2);
0016 
0017 O2A=[xA;yA]-[xD/2+xC/2;yD/2+yC/2];
0018 O2B=[xB;yB]-[xD/2+xC/2;yD/2+yC/2];
0019 O1C=[xC;yC]-[xA/2+xB/2;yB/2+yA/2];
0020 O1D=[xD;yD]-[xA/2+xB/2;yB/2+yA/2];
0021 
0022 n1=[yA-yB;xB-xA]; %normal vector to segA
0023 n2=[yC-yD;xD-xC]; %normal vectot to segB
0024 
0025 test1=n2'*O2A;
0026 test2=n2'*O2B;
0027 
0028 if test1*test2>0
0029     bool=0;
0030     return;
0031 end
0032 
0033 test3=n1'*O1C;
0034 test4=n1'*O1D;
0035 
0036 if test3*test4>0
0037     bool=0;
0038     return;
0039 end
0040 
0041 %if colinear
0042 if test1*test2==0 & test3*test4==0 & det([n1 n2])==0
0043 
0044     %projection on the axis O1O2
0045     O2O1=[xA/2+xB/2;yB/2+yA/2]-[xD/2+xC/2;yD/2+yC/2];
0046     O1A=O2O1'*(O2A-O2O1);
0047     O1B=O2O1'*(O2B-O2O1);
0048     O1C=O2O1'*O1C;
0049     O1D=O2O1'*O1D;
0050     
0051     %test if one point is included in the other segment (->bool=1)
0052     if (O1C-O1A)*(O1D-O1A)<0
0053         bool=1;
0054         return;
0055     end
0056     if (O1C-O1B)*(O1D-O1B)<0
0057         bool=1;
0058         return;
0059     end
0060     if (O1A-O1C)*(O1B-O1C)<0
0061         bool=1;
0062         return;
0063     end
0064     if (O1A-O1D)*(O1B-O1D)<0
0065         bool=1;
0066         return;
0067     end
0068 
0069      %test if the 2 segments have the same middle (->bool=1)
0070     if O2O1==0
0071         bool=1;
0072         return;
0073     end
0074 
0075     %else
0076     bool=0;
0077     return;
0078 
0079 end
0080

Generated on Sun 29-Mar-2009 20:22:55 by m2html © 2003