From fcd4a27f470d58677323c4bac3c22f320c744485 Mon Sep 17 00:00:00 2001 From: CTurt Date: Sun, 1 Feb 2015 18:03:27 +0000 Subject: [PATCH] DSGM_Intersection --- include/DSGM_misc.h | 2 ++ source/DSGM_misc.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/include/DSGM_misc.h b/include/DSGM_misc.h index e08851e..6135016 100644 --- a/include/DSGM_misc.h +++ b/include/DSGM_misc.h @@ -18,3 +18,5 @@ inline int DSGM_Random(int min, int max); void DSGM_Delay(unsigned int time); size_t DSGM_GetWordLength(char *text); + +bool DSGM_Intersection(int Ax, int Ay, int Bx, int By, int Cx, int Cy, int Dx, int Dy); diff --git a/source/DSGM_misc.c b/source/DSGM_misc.c index 89ad325..35dd5f6 100644 --- a/source/DSGM_misc.c +++ b/source/DSGM_misc.c @@ -124,3 +124,45 @@ unsigned int DSGM_GetWordLength(char *text) { return i; } + +// Taken from: http://alienryderflex.com/intersect/ +bool DSGM_Intersection(int Ax, int Ay, int Bx, int By, int Cx, int Cy, int Dx, int Dy) { + int distAB, theCos, theSin, newX, ABpos; + + // Fail if either line segment is zero-length + if((Ax == Bx && Ay == By) || (Cx == Dx && Cy == Dy)) return false; + + // Fail if the segments share an end-point + if((Ax == Cx && Ay == Cy) || (Bx == Cx && By == Cy) || (Ax == Dx && Ay == Dy) || (Bx == Dx && By == Dy)) return false; + + // Translate the system so that point A is on the origin + Bx -= Ax; By -= Ay; + Cx -= Ax; Cy -= Ay; + Dx -= Ax; Dy -= Ay; + + // Discover the length of segment A-B + distAB = sqrt32(Bx * Bx + By * By); + + // Rotate the system so that point B is on the positive X axis + theCos = Bx / distAB; + theSin = By / distAB; + newX = Cx * theCos + Cy * theSin; + Cy = Cy * theCos - Cx * theSin; Cx = newX; + newX = Dx * theCos + Dy * theSin; + Dy = Dy * theCos - Dx * theSin; Dx = newX; + + // Fail if segment C-D doesn't cross line A-B + if((Cy < 0 && Dy < 0) || (Cy >= 0 && Dy >= 0)) return false; + + // Discover the position of the intersection point along line A-B + ABpos = Dx + (Cx - Dx) * Dy / (Dy - Cy); + + // Fail if segment C-D crosses line A-B outside of segment A-B + if(ABpos < 0 || ABpos > distAB) return false; + + // Apply the discovered position to line A-B in the original coordinate system + // *X = Ax + ABpos * theCos; + // *Y = Ay + ABpos * theSin; + + return true; +}