 Welcome back CAD from scratch episode 15. The topic today is triangle intersections in three dimensions And so this is an extremely important fundamental topic. It's the basis of almost everything of value in computational geometry. It's in CAD obviously Rendering it's used for collision detection and even where it's not used the geometric Predicates or concepts that these algorithms are based on They apply and just having watched this video. I think you'll not only have a Better understanding of what's happening under the hood when you play certain games or make something in CAD But you'll also have greater appreciation of how much goes into it. You know, it's not just simple You know dot products was quite a bit involved in the computations here And it's surprising to me how few comprehensive resources there actually are on this topic because honestly, there aren't any and It's not any textbooks that I've seen. It's not in any MIT open courseware syllabus Most of the papers, especially on quantification here. They're paywalled Most of the open source code is, you know, obfuscated or very hard to understand There are a few really good papers that are sort of free to access about classification Especially paper by Tomas Moller. I don't have it written down here and then paper here by Olivier and Philippe It's an awesome paper. They have a great and they have a really good very Efficient algorithm to classify intersections very very good But even their paper has a really bad typo that took me like honestly hours to figure out that it even was there And it has a huge impact on how this works. So What I'm trying to say is This video is a synthesis of like four or five hard to find hard to understand resources Plus some geometry and matrix algebra stuff of varying difficulties. So this video in the code to go along with it is Definitely like a one-of-a-kind resource that I I genuinely hope is useful to at least one other person besides me So without further ado, I'm gonna first talk about the math the geometry the algorithms Then I'm I'm not gonna do any live coding today. Like I usually do. There's just too much and I would make a hundred mistakes I have the code already written, which I'll just go through and show how we're implementing each of the algorithms So let's begin so when it comes to these intersections, you have to first classify it So you have to see if for any two different triangles if they a Don't intersect if they're far apart, right? That's the most common case Then B if they do intersect for example like shown here the yellow and red triangles intersect in a single line segment in pink Or C to absolutely the worst case if they intersect in our coplanar That's you know, you can imagine like a triangle is intersecting like this in this boundary here That would be a coplanar intersection. That's the terrible case. Unfortunately, though It's a very common case, especially when you're working with you know primitives with flat faces like prisms cubes Stuff like that, you know and extrusions and stuff you have this all the time And it's just a an absolute mess if you can't do it properly So that's the classification after that once you kind of determine what's going on in the triangles Get people to figure out where it's going on. So where where does the injection occur? Where is this line segment? That's not as easy as it would sound. It's actually a lot harder than classification. So we'll get into all this So what is the fastest classification algorithm? Now this is gonna be the fastest overall. It's the fastest one that I'm aware of It has three different steps. So step a Is to check if the triangle bounding box is overlap This is how you can filter out, you know, the vast majority of Faces that just don't intersect So what it's a triangle bounding box a bounding box is basically the box that surrounds The triangle and goes from the minimum to the maximum coordinate in the x, y and z direction And so basically if you have two triangles with bunny boxes that don't even touch Then you can say for certain that they don't intersect If the boxes do overlap, however, you may possibly have intersections for the triangles Phase step B What are these signed distances from triangle ones vertices to triangle twos plane and vice versa? So basically we're trying to figure out if the distances from triangle ones plane triangle two vertices and vice versa if they're all Positive or all negative and I'll get into details later about what goes on for each of these is just me talking sort of a top-level discussion right now If they're all positive or all negative, there's no intersection if they're all zero Obviously you have coplanar intersection And now if some are positive and somewhere negative That would mean that Triangle one vertices are split across the plane of triangle T2 In that case you may have intersection in that case the third step step C applies so That's basically if the triangle planes intersect along a line called line L Does the interval of intersection of triangle one in L? overlap the interval of intersection of triangle two in L if So you definitely have intersection if not you do not have intersection and these three steps are sort of Set up in a way that you can fill throughout most of the cases with the least amount of Operations so you do a first and then B and then C because C is the most involved B is the next most involved and a is the easiest so that that's why you do a B and C in that order and the the benefit of what Olivia and Philippe came up with in their paper is using a determinant either a four by four determinant or a three by three reduction of that determinant to evaluate something so basically You take this kind of weird triple product of some coordinates here and It has a couple different Interpretation so basically This determinant here will evaluate to positive if the a2 vertex is Above plane a1 b1 c1 it will like negative if it's net if it's below the plane And I wait to zero if it's in plane so you can imagine how that would be useful for example to figure out this step B Right because that's exactly how you would compute these quantities is with that determinant so the other interpretation that which is harder to understand but Equally relevant is basically this determinant would be positive if the screw around ray a1 to b1 turns toward Ray c1 to a to a2 Negative if it turns the other way and zero again if your coplanar and there's nothing to talk about So if that doesn't make sense, don't worry the first one should make sense That's one that's that matters more this one is sort of the extra extra credit if that would make sense That's great as well So for phase a this is about the triangle bounding boxes overlapping So basically it's pretty simple. We will have to encode basically these Minimum maximum coordinates in x y and z for each triangle We can save that in the same structure that we use to encode the faces and their their own nodes and things like that That'll be part of you know our data structure and basically you can compute these six Expressions basically if any minimum value for a triangle exceeds the maximum value of the other triangles bounding box Then you cannot have intersections Only if all these tests fail Then you can possibly have intersections And that's why you always want to do this test first because you can throw away 99% of all You know triangle intersection possible cases with this very simple test if any one of these fails You can immediately say no intersection So it could be a single operation. It could be two. It could be three whatever. You'll be very quickly Go very quickly be able to figure out if they intersect or not so phase B this one is the Computation of the sine distances from triangle one to triangle two. So imagine you're looking down the edge of Triangle one from its side. So it's just a single line like this basically normal points out of that face now if you have Triangle twos where it sees like this where you may have two on the top one on the bottom Or one on the top and two on the bottom if that is the case where you have some Vertices above and some vertices below the plane of triangle t1 Then you can possibly have intersection, but you can imagine if this vertex here was actually up here You're trying to look like this Then you you obviously could not have intersection because all the vertices are you know above triangle t1 So basically you can use those determinants Here y1 y2 and y3 to compute whether or not triangle T twos where to see is here a2 b2 and c2 if they are above the plane defined by a1 b1 and c1 so if If y1 y2 and y3 have the same sign, there's no intersection And if y1 y2 and y3 are all zero that would mean that triangle t2 is sort of Coincidence at least in the plane of triangle t1 So they would be coplanar So after that if neither of those two is is it is been evaluated as true Then look at why 4 by 5 and 6 so why 4 5 and 6 are basically the opposite So this is triangle t1's vertices a1 b1 and c1 relative to the plane a2 b2 c2 Which is triangle twos plane so you can evaluate that again So if y4 5 and 6 have the same sign then you have no intersection and If y4 5 and 6 are zero again your coplanar, but this would already be true You would have already evaluated this so this is not even important to keep as a as a possible test You can keep it if you'd like, but it will always evaluate here not here And of course you can't use your you have to use a tolerance because you can't use like you know exactly zero in Computing like this, but some small tolerance would be fine Now finally is phase C. This is like the the real last chance for Intersection to occur between triangles At least in the general sense not in a coplanar sense. So basically is it's asking and do the intersection intervals Overlap. So what does that mean? So triangle one here is in is in teal and triangle two here is in green and The plane of triangle t1 and t2 intersects in this line L in pink Now we're triangle t1 Intersects L which is guaranteed to do because it's defined by the plane of triangle t1 and t2 So we're t1 crosses line L. You have some interval here shown in this pink color same in color and We're triangle t2 crosses L. You have this interval in this same in color And if those two intervals overlap, then you have intersection guaranteed. That's the final test However, if you can imagine triangle t2 was over here and the interval for intersection was you know over here Then you can say that this interval on t2 does not overlap this long interval on t1 And therefore the triangles do not intersect That makes sense it should so basically if you kind of can Set it up like this it will make computational sense so if you can call the loan Vertex from triangle t1 on its own side of the plane of triangle t2 a1 So basically what I'm saying is if you have this view here from the side of triangle t1 This here would be point a2 and then in the opposite case where this is green and this one is blue This point would be triangle a1 The loan vertex is called a If you call it a a1 and a2 respectively then you can evaluate intersections of these sort of line segments with line L So for example where a1 b1 Crosses line L that is point i and where a1 c1 crosses L that is point j a2 b2 that's point k a2 c2 That's point L And remember L is oriented obviously to n1 cross n2 and one being normal of triangle t1 and To be normal of triangle t2 So basically the way this works is you do a simple min max evaluation and if that min max evaluation Evaluates a certain way you can say that Interaction occurs or not because the intervals overlap or do not so in this case You're looking if the minimum value from sort of you know in this sense looking from this point In pink here outwards along line L is the minimum of ij less than the maximum of lk And is the minimum of lk less than the maximum of ij if those both are true. You're guaranteeing That the intervals overlap If they're not then you can possibly have the intervals not overlapping or I mean you do have it not overlapping So you must have this min max evaluated in this way For there to be guaranteed intersection And lucky for us this equates to evaluating these two determinants So Computing these ones in the way I said before if these are both less than or equal to zero you have intersection So basically with a very little number of operations we can determine If triangles intersect Especially on average when you consider the fact that we're throwing away almost all of the Possible intersection cases in the first phase of the algorithm and then even more in the second phase of the algorithm You know it's a very efficient on average for us to evaluate whether or not Faces intersect because if you can imagine we have you may have a model with thousands and thousands and thousands or even millions of triangular faces You want to have this be very efficient in terms of number of operations Now here's one more thing If you evaluate these two more determinants you can classify the intersection interval even further So basically the point is You want people to evaluate what is the sequence of i j l and k? Because you can imagine you know if if l k is located over here It's a different intersection than where if it was over here Or where it is originally or what if l k was this big and i j was smaller You know there's plenty of options for intersection intervals here So basically if you evaluate y 9 and y 10 which are Uh Similar Oh crap. I made a mistake. Hold on. I'll fix that No, I didn't am I crazy? No, I didn't I'm just dyslexic. Nevermind. It's fine. So Basically if uh, you have these combinations of y 10 and y 9 you can get the actual sequence of the Points of intersection along line l now. Why does that matter that matters because On both triangles the actual intersection slice Sort of if I go back to the very top this This slice here Will always occur on both triangles between the center of those two vertices Uh, so these two vertices here in the middle. So in this case, it would be i j in this case It would be k j in this case. It would be k l in this case. It would be i l So basically if you can figure out what i and j are You can figure out exactly where the intersection occurs If y 10 and 9 are both, you know, in this in this condition here That's the plan of attack for the actual Quantification of where these lines of intersection between triangles occur We'll leave that for a second now. We'll go on to the actual calculations now So if you want to calculate the points of intersections Of you know on line l the first step is obviously defines line l Of player intersection. So if you have you know triangle t2 and t1 with their own normals And then you have plane p2 and p1 there They intersect along line l so line l has this form It is uh p0, which is you know at some point on this line Plus n1 cross n2 that's the direction times parameter t So what is p0? That's actually not very easy to find And in fact, this you'll see this is very complicated But basically you obviously have equations for plane one and plane two Because you have the normals and you have plenty of vertices on each face, right? You have Three vertices for each triangle so you can take your pick for p1 and p2 And this just gives you the equation for the plane Obviously n1 x and one y and one z are the Normalized that's very important. You have to have normalized values for this These are the Coordinates for the normal in uh for plane one and for n2 that's for plane two Now the third plane equation is basically arbitrary We're defining a plane passing through Any vertex that we know about it can be on triangle one it can be on triangle two It doesn't really matter, but just some point that we know And then uh it has the The l direction as it's normal So basically, uh, it's this plane equation here. So you have the x y and z components again, it should be normalized And you're taking any point anywhere on any of the triangles as to the point you're passing through With those you can make a very simple system of equations and honestly you can just solve this with an inversion But remember we're doing things efficiently because we want to be able to evaluate things that these things Very quickly for many many thousands of of canada intersections Um Once we have no down selected them to our to which ones are intersections We have to evaluate all of them as quickly as possible. So you don't want to be able you don't have to invert matrices If you don't have to that's a very intensive operation So there's actually a clever way to solve this But basically if you solve this system of equations You will solve x y and z for p zero and remember p zero is a point that we need in order to quantify line l So we this is the trick you can recall that row one And row three are perpendicular because remember n three is is the cross product of n one and n two So you know for a fact that m three is perpendicular to both n one and n two And so basically if we can just make rows one and two orthogonal Like rows one and three and two and three are The equation is already solved because once you have an orthogonal matrix or I guess in our case in An orthonormal matrix or whatever you call it The the solution just falls out remember because when you have an orthonormal matrix The transpose is the inverse and then you can evaluate this entire expression as simply A matrix multiplication right three by three matrix by three more matrix that will give you x y and z So if we can basically pull out the n two component from Uh this first row We've basically solved the problem. So that row operation is basically shown here. So you're taking row one subtracting out the n one dot n two so the n two component in the direction of n one Of row two and storing that in row one. So basically you're just subtracting out the Like I said the n two component of n one And then you're renormalizing it. It's very important to renormalize because you have to have an orthonormal matrix For the transpose to be the inverse. I believe And so you have something like this when two deals operations, you'll have a same row two and row three as before But your row one will be very different E has this form just the magnitude For normalization, but here is very interesting that you don't have to actually evaluate the square root because When we solve the equation later on you'll have e times e So the square root will cancel out But that's sort of not either here or there You'll also have this revised right-hand side vector d So you have the same row two and three, but you have a different row one And so your original matrix looks like this So but but now with your orthonormal matrix a you can take the transpose and pre multiply Uh both sides and then you can evaluate p zero very simply like this So at transpose times d that will exactly give you p zero and once you have p zero you can fully define line l So basically now you have a closed form expression For a point on line l and with that you have line l and that's one of the hardest parts of solving the intersection problem And you did it with a single matrix inversion, which is very very nice Now step two once you have line l quantified like we do You want to find the intersection Of t one and t two online l. That's the intervals here i j and and k l. So you're basically evaluating four things But really only two like I said before because you only care about the center two of these uh Evaluation so here you care about k and l So you want you want of these four two of them So i is the intersection of a one b one with l And so on So to solve for i again, it's very simple. So we have a couple things so You have to have the equation of a one b one so you can parametrize this vector equation like this. So This is the a one Uh sort of coordinates and x y and z and this is the vector from a one to b one times parameter t And this is the the equation we have for line l. So we have p zero we have n three and u is the parameter So at the intersection obviously l Equals a one b one those two equal each other And so you can solve this equation You have three equations because you have three components x y and z and you have two unknowns t and u So it's an over defined or whatever they call it Uh system And so there's different ways you can solve it you have you know three different combinations of Um substitutions to solve this this system, right? And so you can go about that At the end of the day here is one possible case if you took the x and y equations and and solve the two of them you'd have this expression for t From the x and y coordinates. It looks like this. However Whenever you see a denominator In any sort of mathematical expression that you're using on a computer you should always question When will this be zero because this will be zero? You know quite frequently if you have um you know Uh primitives that are oriented along, you know x y and z axes because if a one b one is parallel with c This evaluates to zero, right? And also in some combinations of n three and a one b one You'll also have this to be zero, but you can't account for those before hand those are going to be flukes, right? So basically what you do is You can calculate not only t from x and y Equations but you can also calculate t from the x and z equations And the z and y equations and then what you do is you don't you don't solve the t values You you calculate the not dominant d You calculate the denominator values first. Sorry. So basically You pick whichever val whichever t so t x y t x or t z y you pick whichever t has the greatest value of the denominator If you do that or sorry, I should say denominator magnitude If you pick the t equation with the greatest denominator magnitude You will guarantee yourself that you're not going to have a zero in the denominator because zero is not a very high magnitude And also you'll have a very good computational Accuracy because you want to have a large denominator when you do when you do divisions because that just gives you more accurate results You know in in general So you'll you'll pick you'll force it like with the denominators here. So Uh denominator x y denominator x z denominator z y and c which is largest And then whichever is largest you'll evaluate the numerator and evaluate the total expression for t And once you have t you're basically done because once you have t you can solve for point i at x y and z from the original equation that we had here, right? And once you have i You know, you can calculate l k and j in the same way and then you can precisely describe where the intersection occurs So you repeat that process for j k and l as you need Remember, you only need in the middle two of those uh those points And at that point you can precisely quantify the region of intersection for any Non-coplanar triangles end of story Now, how do you detect overlapping? Coplanar triangles and 3d this is what I hate and you will hate this too and I know I identify with with hating coplanar triangles. I really hate it So basically the first thing you do as before is you check if the bounding boxes overlaps very simple if they do you go on Now here's the process the first thing you do is you test if any of triangle one's edges Cross any of triangle two's edges And there might be better ways to do this, but this is a very simple one to understand And I think it's it's pretty quick. I'm not sure if a fashion one exists I think possibly Olivier and fleet have a better one, but it's just too hard for me to explain in a video like this So but this this is comparable, you know very very closely comparable So you test if any edges cross then if no edges cross You test if a single point in t2 lies in t1. Why do you do that? Well, here's the reason why So let's say t1 is like this And t2 is like this Well, then no edges intersected, but still They overlap why because one of these vertices is inside this triangle So you test both if any of vertices in t1 are in t2 and vice versa If any of those things evaluate to true You have some kind of intersection Between the triangles In the plane So here's a here's a very simple way to calculate whether or not line segments intersect and this is very very clever So basically the way you do this is let me change my color really quick Take you have to set if I these two sort of dot products of cross products So let me explain how they work. So let's look at a1 b1 cross b1 b2 So a1 b1 b1 b2 is basically saying this This sort of curl If so basically the if you were to have the right hand rule So you put your right hand on the screen if a1 b1 b2 that points out of the page, right? And then it checks a1 b1 a2 So this Right hand rule that points into the page. So basically if Out of the page times in the page That will give you less than zero right because it would be you know If you dot them you'll have a negative number right because they're in opposite directions So if that's the case for both this this direction and this direction You are guaranteed to have intersection You basically want to you basically asking yourself does a2 b2 cross over a1 b1 in the sense that Sort of right hand rule would indicate that for both a1 b1 and a2 b2 But here's an example of that not being the case. So as before This And this are opposite directions of right hand rule curl however This hold them change colors this and this Are the same direction of right hand curl. So this lower expression Evaluates to false and then you do not have intersections of these line segments So basically this is a very efficient way to evaluate whether or not line segment intersect and you will repeat this for three times three Possibilities for any of t1 edges crossing triangle t2 right And then if if any of them do you can immediately stop Calculating you can say yes, we have intersection. The classification is done. We do have intersection Now the last two things there was checking if triangle t1's nodes are in triangle t2 boundaries and vice versa And like before we can evaluate this type of expression here you have a normal for triangle t1 you can take That cross it with the sides to evaluate the side normals and one and two and three as shown here And then you can calculate the dot product of the sides with these normals Sorry, I should say not the sides, but the The the vectors from the vertices to the point of interest like this this and this If those dotted with the normals are all the same sign Then the point is inside triangle t1 If any of them are different signs, it's not And I should say if if you have some zeros in there It may be fine depending on how you want to count intersections or not Because if you have two of the same sign and one zero that means that triangle a2 would be on an edge Like like here for example, and if you had two zeros That would mean that you're on a vertex like c1 there Now you may look at this and see difference from previous videos So in previous videos, I actually had six equations to evaluate That was just so I could make things very simple for you to understand when we have to do things efficiently I don't want to do any extreme calculations. So I'm only going to take three Three dot products here to evaluate whether or not we're inside the triangle or not Now how can you now once we have classified intersections of of co-planet triangles the question is how can you calculate the vertices Of that overlap zone. So here are two planar triangles And you have an overlap zone here between i j and a2 So these overlap zones are defined by A series of points right here the points are i j and a2, but these points are basically generated by any time A line segment on triangle t2 crosses a line segment on triangle t1 and any time you have a point inside Anytime you have a node from one triangle inside the other If you take all those points that entire point set that defines this boundary zone here So it's very simple It's it's actually very simple to understand but it's kind of hard to implement You're just going to basically be computing making a huge list of All the points on this sort of Overlap polygon and you'll get like I said before points from Intersections of line segments and then points from contained nodes like a2 here So again, um i and j are computed as the intersection of line segments. So here is an example for i and This should be deja vu because we did this just a few minutes ago. You have an equation for a line I guess p2 here and the equation for line p1 here So you it starts at a2 and it goes in this direction times parameter t and times parameter u And where p2 equals p1 you have intersection at point i uh, so basically, um We have a similar sort of the um t value as before We're going to be have three candidate t's so we have t x y t x z and t y x and again You want to write the denominator first and see whichever denominator has the maximum magnitude And use that denominator and that numerator for calculation of t And once you have t you can compute the point of intersection very easily And I should say by the way when you have an expression like this For you know anything If the t value is less than zero or greater than one The point of intersection of this line is not on the boundary that you said Because this is normalized so that zero basically means a2 and one means b2 So if you have any point that's less than zero or more than one You will not be on sort of the line segment part of this line And so at this point you're pretty much an expert in intersections of triangles And that's the that's the entire master class on intersections, but there's one last thing That we have to talk about because If you recall we have this point set here i j and a2 and when you have only three it's not a problem But when you have four five six, how do you know that these Points are in the correct order because the order Matters when you're talking about the polygon, right? And so basically I want to compute the vertex order for convex polygons So once you find the vertices of the polygonal overlap zone for these coplanar triangles You have to put them in a sequence. So here you have, you know, four points of interest They would be in like a rhombus shape here. You have, you know, two triangles making a Triangle shape here. You have two more in a triangle shape here. You have, you know, uh A hexagon shape And so there's different options and how do you know that these six vertices go in a certain order? You have to compute that right you can't just guess Now there are there are ways to Apply the previous sort of um intersection tests that you get these in this order Automatically, but they're honestly way too hard and then we can do this sort of ourselves in a very simple way So basically if that overlap zone has more than three vertices You have to define a sequence for them because like I said before there's a difference between here. You can see this Rhombus shape a b c d This rhombus shape a c d b has the same vertices just in a different order These three are sort of rotated around It gives you a you know to generate Part of lateral. It's not even a real shape, you know, it's it's self-intersecting. So it doesn't work It's it's also inaccurate because your region intersection was like this, right? So having these intersections is just just blatantly inaccurate. So when it comes down to quads, it's actually not that hard There's a sort of um method you can use so basically you have to ask Did the diagonals intersect so does the first and third vertex or sorry? There's the first and third Vertex combined into a diagonal cross over the second and fourth if it does You're fine. Your ordering is fine if the first and the third so a to d and b to c second to fourth if they Don't cross the signs don't don't cross Then what you have to do is you have to swap the first and the The fourth vertices here you'll swap a one and b one and then you can you can imagine swapping these two Would basically reduce you to this, right? So that's the process for quadrilaterals unfortunately for pentagons and hexagons you have to sort their points by the 3d angle about a normal vector at the center of that polygon That's the simplest way to understand how this works. So let's say you had a Pentagon like this You have a center point you could compute as the average of these sort of five points And then you compute the angle from This this line here a to center of everything else So a sort of a center b a center c a center d a center e compute all those angles And you compute those in a very simple way We did this in one of the first videos And this is very very actually it's actually it's simple But almost no one knows this Because when people talk about angles, they don't care about negatives, but in when it comes to this computational geometry stuff We really care about negatives a lot because you know this angle and this angle You know if you do it with stupid arc cosine like most people do Like the dot product rule the both be positive angles What we want though is what we want this angle to be You know This a b to be this and you want a e to be this or This this would be negative, right? So you want people to evaluate all those things And so the process here is taking the arc tangent to that's a special kind of arc tangent Of this determinant and a dot product so It defined vectors v1 and v2 as sort of this vector and this vector And n as the unit normal very important has to be a unit normal Out of the plane here. So that's defined like n The dot product is simply v1 dot v2 and the determinant is n dot v1 cross v2 If you have these two you can evaluate this angle For these you know all of the possible angles so you can compute the angle here You get the angle here put the angle here put the angle here every single angle you can compute Of course obviously the angle from a center to a will be zero But all the rest are going to be in general, you know not known And then all you have to do is sort them in an ascending order If you sort these angles in ascending order and the points that go along with it in ascending order Then you're guaranteed to have a right-handed. I guess counterclockwise sequence of your polygon vertices This is this is big stuff. I mean, this is not easily understood not easily graspable You you have to be able to do this to be able to to orient your vertex set in a way that gives you Convex polygon that you can use for Other things that you may want to use for your your algorithm going forward. So we're going to use this stuff for Computational solid geometry We're going to triangulate this this polygon in other ways It's very important for us to know exactly what this polygon looks like for the next one or two videos in this series So that's very very important and that wraps up all the theory that goes into 3d triangle intersections So that's been 41 minutes. I'm gonna take a break and then I go through the code. I'll see you in a second Okay, welcome back so the First thing we have to do for our algorithm is add a couple things to our structures here So for um in order to basically encode this bounding box So I won't be able to encode the minimum and maximum x y and c values for everything. So I put here. Let me zoom in a little bit This is our structures for our you know geometry stuff For the edges for the faces and for the bodies I put these floats here These quantify the minimum maximum values for the bounding box around the the objects And of course we had to change the constructors for these things Which I did in order to put these things in place, but it's very simple. I'm not going to go into that The next thing here is these uh, let me go to the um actual geometry That c file and so I'll explain every algorithm that I implemented here in in order because it's kind of a Easiest to do that way so Let's talk about this first So these are two very short functions. One is one says rotate face nodes. One says swap face nodes These basically rotate nodes on a face or swap nodes on a face And so why would you do that? Well? This is why if you recall when we tried to determine if the Interaction intervals overlapped We basically said that we had to have a one be the lone vertex on its side of t2 And a vice versa a two being on its own side of t1 To do that you have to be able to to circularly rotate a b c on both triangles So this simply does that and then swapping Swapping basically guarantees that you are keeping your vertex on the same What's it called? Like a the positive subspace? Of the others of of the other plane So basically whenever you have rotation and you change the the Whenever you want to swap the face nodes to preserve your orientation of your face you can use this function here So next we have this function here edge edge intersection this basically determines if Two line segments a 1 b 1 and a 2 b 2 cross and we use this a couple times if you remember Where where where Where where where here? Yeah And also we used it down down here So basically this this determines if they intersect and also it gives you where they intersect So it will tell you this intersection point i here in terms of an output coordinate And it just implements what I just told you about here this tij. So basically it computes these cross products here Uh and dot drop part of them together that that's what I said before that's um this If those are satisfied it basically goes on and it computes the denominators It picks the largest denominator Evaluates the corresponding t value and with that corresponding t value. Um, we can compute the i value here I'm going to return it very simple the next the next function we have is edge line intersection This is a very similar it just evaluates where a 1 b 1 crosses a line a given line Through p zero interaction and three we use that um to compute this Basically where where a 1 b 1 crosses l And it's the same exact thing pretty much just a slightly different expression for t And again we divide with the denominators pick the largest denominator magnitude evaluate t make sure it's between zero and one If it's not it doesn't intersect if it does we evaluate where it does and we return one Very simple now Next is a function called coplanar node within triangle. This evaluates Are you know tried and true method of determining if triangle Node is another triangle In this way we've done a thousand times before I'm going to go over it again. Um Then This is the talk the part I talked about at the very end It's function called reorder points. This basically implements what I mentioned down here So what it does is it uh For the special case of a quadrilateral it does what I said it evaluates if the diagonals are crossing In in this way you can take a look in the code and if you'd like I would cross products takes the dot products of them and evaluates if they're uh If they're both less than zero if yes They cross and it's a good order. If not, we change them around Now for pentagons and hexagons, it's much more difficult and much more operations involved So we're doing this first thing we do is we evaluate the center point of all the points in our point set abc dne You calculate that like this, of course, we have a division divisions are not very good But you have to do what you have to do sometimes Um Now we're taking the normal We use that normal and the uh points a And center here took it with the angles as I mentioned down here And the function for that is in our trigonometry dot c file here So I these are we had we had this one before get node angle I added get point angle because it doesn't involve nodes it involves just generic points in space Uh, but it's pretty much the same operation here This is how we calculate the angle in 3d space This is the best way to do so keep you know keep this in the back of your mind for everything in your life This is extremely important equation Now once we calculate, um Uh that that angle we basically do an insertion insertion sort By that angle and we use the insertion sort algorithm to rearrange not just the angle list But also the point list In ascending order as I mentioned you can look up at insertion short. I'm not going to talk about that It's not in the scope of this discussion now Here are sort of the the the big um the big function. So I have one function that basically does This and one function that does this based off of this So this is called, uh, classified triangle intersect This takes in simply two faces Triangular faces and it will return these values return negative one if some kind of error return zero if they don't don't cross That's this it will return one if they intersect in a line Um in this form so this sequence of k i j and l returns two in this form three in this form four in this form And it returns five if they're coplanar very simple And the way it does that Well, uh, first things first I set a tolerance. Remember we have to use a tolerance not in zero because you know Things may not be exactly zero when you do floating point arithmetic So you have to use some small number. It could be smaller than this. That's probably too large of a tolerance, but whatever If we have more than three nodes per triangle we say that's bogus Now the first thing For our algorithm is we check if the bounding boxes overlap. So evaluating if the minimum values exceed the maximum values If they do Then there's no overlap No intersection if any of them do and I think I'm not sure what the compiler does I'm pretty sure if you wanted to you could break this up into like six different operations and You know, maybe save some operations here, but I'm pretty sure if you do an optimizing Um step for your compiler. I I I think it will just automatically do that. It will automatically break out if one of these is uh satisfied The next step is we're evaluating Let me scroll down a little bit. So we did we did phase phase a phase b. We're evaluating y one two and three That computes whether or not triangle t diversities are all above below or in the same plane or crossing the plane of triangle t one Um, if they're all the same sign No intersection is possible if they're all within the tolerance Uh, then you have a coplanar Case I'll come back to this in a second Um, and then if it's four five and six You can check those as well. If they're all positive you have an intersection If they're all zero, which I commented out because you don't need Um, you have a coplanar solution Uh, then what we do is we We rotate like I said before we rotate around these vertices a one b one c one and a two b two c two to make sure that Only the zero's node is on that side of the other triangle's plane Very simple. Then we evaluate some determinants here. Um To do that finally we Talk about um y seven y eight Nine and ten these are used so y seven eight are used to compute If we have an intersection at all So if we have an overlap of our interval intersection if the both less than zero We do and then we can check nine and ten And if they're different sort of combinations, we have different return values one two three and four again They correspond with different sequences of Um those points k i j and l On the interval of line, uh l here So i'm going back up now if it was coplanar Here if it's coplanar We Do some of the announcements we talked about down here Where is it? Here so we we first um We loop over all edges of face one to see if any of them cross face two edges If they if any of them cross we have intersections. So we return five, which means coplanar Then we check if any if a single node in this case node zero on face one is inside face two If it is we return five for coplanar Then we check vice the opposite if a single node of face two is inside inside triangle face one If yes return five if not they're coplanar, but they don't intersect Which is the best case for coplanar triangles um So that's that wraps up the classification step. So now we've basically evaluated how the triangles cross if they do They either don't cross they cross in One of four ways of a line segment or they cross in some kind of polygon Yeah At this point I have a final function here, which is triangle intersection points This computes the points of intersection. So for this it would compute this point and this point For this case it would compute this point this point and this point right It would compute all the points required for intersection of of the two triangles So the first thing is is it it calculates the mode remember it calculates the classification. So it runs this first between face one and face two if the mode is Not zero because if it's zero there's no intersection if it's between zero and five And you have a line segment like this. Oops like this I should say like this Oops, I hope it did break anyone. I hate that. Okay so uh Basically if we have a line segment intersection we can compute how it intersects. So in that case we're basically doing um This so the first thing we do is we compute um Everything we do is to basically compute these plane these planes because you want to be able to evaluate this expression here A transpose times d. So we basically do that. It's not really that hard Um after that we have we have basically solved for p zero That's I call it p three in the code. Um And then we'd look at the four different modes. So the modes being um Where is it? Yeah, these these four modes here one two one two three four whatever order it happens to be Based on whatever mode we have so intersection sort of sequence. We compute the two middle Uh points. So here k j here k l here i l here i j we compute those two and we print them out very simple Then um that that that wraps up the Line segment intersection. So modes one through four if mode is five Um here it says I should say equal equal five not So basically if they're co-planers And they intersect We have to do what we talked about down here Where here so we have to compute all these vertices. So the first thing we do is we Check we loop through all the edges in uh in I guess triangle one here We check if the we first check if the p th node of t one is inside t two and the p th node of t two is inside t one typo Let me fix that before I forget And then we check if the p th edge Crosses the q th edge of t two. So we loop through both t one and t two edges and see if any of them cross If they do we add them to a list of intersection points here And we increment the number of points in our list And then lastly if number of points exceeds three that is if we have You know something like this Like like this case or this case Then we must make sure that this sequence is a You know a convex not self intersecting polygon And for that we have the function reorder points talked about before That does the you know whole insertion short thing with the with the angles Um, and then it prints it out So if I uh if I compile that and I run it. Oh, sorry. Let me show you the the main thing first. Oops, maybe So what I did was I um defined four triangles here Don't worry what they are. I'll I'll show you that in a second, but there's four triangles With different coordinates and I made them so they intersect in different ways Just to test out different parts of this code So what I do is I first I classify them just to see what the classification returns And then if it returns a number that's not zero. So if it returns intersection Then it computes the points of intersection and it will print them to the screen So very simple. So if I can recompile it rerun it We have these results. So Don't worry about them. Um, basically this just shows you that the the functions Work as intended. I will show you a graphic about how this looks right now. So Um, it's not going to be in the code, but it's in octave. So I made another function here. Um In uh, just in terms of octave or matlab code here with all those points So these are the four triangles one two three and four. These are where our code calculates. They intersect And then just plot some figures and it waits for us to hit enter between the two So let me show you how this looks so octave Let me send this to the other screen first So here is the first two triangles. So these two are not coplanar. These are just in just general intersection So the blue triangle is t1 red triangle is t2 and the yellow line there is the intersection interval You can see that it crosses exactly between the two So this test case works Hit enter. Second test case is right here. These are two coplanar triangles crossing in this way And you can see the red triangle blue triangle and the yellow triangle yellow triangle is the intersection of red triangle and the blue triangle Right that seems to work next Here's that star david thing. So there's two triangles here crossing in a hexagon plate a hexagon sort of uh sequence And again this test two thing a test can be compute the intersection points But it also tests If we can, you know, reorder them in a way that puts them in a uh, you know, clockwise right hand rule Sequence and it does so the red triangle, you know Crossing over the blue triangle gives us this yellow hexagon and everything seems to work just fine So That's it. I hope you really enjoyed this video. I hope that one or two people learned something It was a very long video. It's almost an hour now so If you did that's awesome. If you didn't that's awesome too. Either way. Have a great day