Finding the intersection points of a line and a circle (2D) or sphere (3D) is useful in many situations. So I just wanted to post a function that finds those intersection points.
A and B are points of the line, P is the center of the circle.
int IntersectionLineSphere(vec *Q1, vec *Q2, vec A, vec B, vec P, float r){ vec pa = A - P; vec ab = B - A; float a = dot(ab,ab); float b = dot(pa,ab); float c = dot(pa,pa) - r*r; float d = b/a; float s = d*d-c/a; if (s < 0.0f) return 0; // sphere and line do not intersect else s = sqrtf(s); float t1 = -d+s; float t2 = -d-s; *Q2 = A + ab * t1; // closer to B *Q1 = A + ab * t2; // closer to A int intersections = 0; // intersection points within line segment? if (t1 > 0.0f && t1 < 1.0f) intersections++; if (t2 > 0.0f && t2 < 1.0f) intersections++; // will be either 1 or 2 return intersections;}
The function is valid for 2D and 3D, and not optimized (const pointers to A and B). Having found the intersection points Q1 and Q2 one can find the "theta area" of the circle.
float SegmentOfCircle(vec Q1, vec Q2, vec P, float r){ vec s1 = Q1 - P; vec s2 = Q2 - P; float costheta = dot(s1,s2)/(length(s1)*length(s2)); return 0.5f*acosf(costheta)*r*r;}
float AreaOfTriangle(vec A, vec B, vec C){ vec s1 = B - A; vec s2 = C - A; vec cr = cross(s1,s2); return 0.5f * length(cr);}
Now DeathRay2K found a good approximative solution, but the functions above would be the tools to find the correct area of the portion of a circle within a triangle (2 triangles = square). Of course it shouln't be done in real time. If someone is interested in finding this area I could post some code (~150 lines).