From 4878f0fc6a039d220dd7adecb18d19c688ae50b0 Mon Sep 17 00:00:00 2001 From: Matthew Kosarek Date: Thu, 1 Jul 2021 19:46:08 -0400 Subject: (mkosarek) Decent SAT description for now --- 2d/_collisions/polygon_polygon.html | 177 +++++++++++++++++++++++++--- 2d/_collisions/polygon_polygon.html.content | 61 +++++++--- 2d/_collisions/polygon_polygon/snippet2.cpp | 117 ++++++++++++++++++ 3 files changed, 317 insertions(+), 38 deletions(-) create mode 100644 2d/_collisions/polygon_polygon/snippet2.cpp (limited to '2d/_collisions') diff --git a/2d/_collisions/polygon_polygon.html b/2d/_collisions/polygon_polygon.html index f401385..69938ff 100644 --- a/2d/_collisions/polygon_polygon.html +++ b/2d/_collisions/polygon_polygon.html @@ -72,9 +72,21 @@

The Separating Axis Theorem (SAT) provides a way to find the intersection between any n-sided convex polygon or circle. In this tutorial, I will explain how this theorem works, and how you can use it to both detect and resolve collisions in your simulation.

+ +
-

Explanation of Separating Axis Theorem

+

Explanation of Separating Axis Theorem

SAT makes use of vector projection to figure out whether or not two concave polygons are intersecting. I believe the best way to describe it is to show you the instance where two polygons do not intersect. @@ -147,7 +159,7 @@

-

Algorithm for Finding the Intersection

+

Algorithm for Finding the Intersection

Given two polygons A and B: @@ -215,7 +227,7 @@

-

SAT Collision Resolution

+

SAT Collision Resolution

Now that we know that our objects have intersected, we want to send them tumbling away from one another in order to simulate a collision. To do this, we will need to find the following things:

- To find these values, we must first find both the shape and the edge that caused the intersection in the first place. To do this, we will think about what we know so far and try to arrive at some intutitive understanding of it. Keep in mind that I am not a proof-minded person, so you will not be finding that here. -
- -

Finding the Intersecting Edge

+

Finding the Intersecting Edge

We can already figure out that the following two triangles intersect one another:

@@ -238,7 +247,9 @@

- We know that A can only intersect B if: (1) a vertex from A is inside of B, (2) an edge of A flatly intersects an edge of B, or (3) a vertex of A overlaps exactly a vertex of B. Honestly, for our purposes, scenarios 2 and 3 are quite unlikely, but we can explore them a bit just to see how we might resolve them. We will start with the first case, since it is more likely. We will start by drawing the axis defined by the leftmost edge of B with both polygons projected onto it: + We know that A can only intersect B if: (1) a vertex from A is inside of B, (2) an edge of A flatly intersects an edge of B, or (3) a vertex of A overlaps exactly a vertex of B. For our purposes, scenario 3 is quite unlikely, so we can ignore it for now. We will start with the first case, since it is the most likely. +

+ The following drawing shows both of our objects projected onto the axis defined by object B's leftmost edge:

@@ -247,22 +258,150 @@

- This is a poorly drawn picture, but you should be able to see that the bit in green represents the intersection between the projections of the two polygons. If we were to repeat this same exercise for every edge here, we'll begin to see something very interesting. And, if we take new shapes and continue this stategy, we can begin to come to a very elegant conclusion: -
-
- - The intersecting edge will be the one where the projection of triangle A overlaps with the projection of triangle B the least! - -

- I'm sure someone more inclined to proving mathematical truities would love to describe this to you, but, for all intents and purposes, this intutitive understanding is good enough for us. We just want to make games, anyhow. -
-

Finding which point causes the intersection

+ If you were to repeat this exercise of projecting the shapes onto every axis of both shapes, you will begin to unconver an interesting truth: The intersecting edge will be the one where the projection of triangle A overlaps with the projection of triangle B the least! This should be unsurprising if you consider it. If our simulation is running quickly enough, the point of object A that is penetrating the edge of object B will just barely be inside of B. At the same time, it should be the only point that is currently inside of B. Hence, the overlap of the projection on that axis will be from that edge of B to that point on A. Knowing that this edge caused the intersection, we now have the collision normal. +
+

Finding which point causes the intersection

+ This part is made easy by the fact that we know which edge of object B caused the intersection in the first place. We know, then, that the intersecting point on object A must be the point that is currently inside of B. Simply put, this point will be the vertex of A that was projected onto that axis that is closest to the edge of B. This will be true so long as the simulation is properly fast and the object is not infinitesmley small (in which case, we're dealing with particle physics, and you shouldn't be using this tutorial).

-

+

Algorithm for Collision Resolution

+ +

+ + Given two polygons A and B: +

    +
  1. Find the intersecton as before
  2. +
  3. While finding the intersection, keep track of the axis that the projection on object A overlapped with the corresponding projection on object B the least. Remember the edge that this that held this axis.
  4. +
  5. Using this axis, find out which point on the other object inside of the edge by comparing the distances from the two points on the edge to the two points projected onto the axis created by that edge.
  6. +
  7. Use the calcualted edge to find the normal and the overlap point to find the point of application.
  8. +
+ + And that is it! Here is the code for this algorithm: + +
struct IntersectionResult {
+    bool intersect = false;
+    Vector2 collisionNormal;
+    Vector2 relativeVelocity;
+    Vector2 firstPointOfApplication;
+    Vector2 secondPointOfApplication;
+};
+
+struct Edge {
+	Vector2 normal;
+	Vector2 start;
+	Vector2 end;
+};
+
+struct SATResult {
+    Edge* minOverlapEdge = NULL;        // Edge that caused the intersection (on the 'first' shape)
+    Vector2 overlapPoint;               // Point that caused the intersection (on the 'second' shape)
+    float32 minOverlap = FLT_MAX;       // Smallest projection overlap
+};
+
+struct ProjectionResult {
+    Vector2 minVertex;
+    Vector2 maxVertex;
+    Vector2 projection;
+};
+
+// Given the vertices in the shape, we find the min and max vertices that project
+// onto the axis. We also save which vertices were which so that we can resolve
+// the collision later.
+ProjectionResult getProjection(Vector2* vertices, int numVertices, Vector2 axis) {
+    ProjectionResult pr;
+    float32 min = axis.dot(vertices[0]);
+    float32 max = min;
+
+    for (int v = 1; v < numVertices; v++) {
+        float32 d = axis.dot(vertices[v]);
+
+        if (d < min) {
+            pr.minVertex = vertices[v];
+            min = d;
+        } else if (d > max) {
+            pr.maxVertex = vertices[v];
+            max = d;
+        }
+    }
+    
+    pr.projection = Vector2 { min, max };
+    return pr;
+}
+
+bool projectionsOverlap(Vector2 first, Vector2 second) {
+    return first.x <= second.y && second.x <= first.y;
+}
+
+float32 getProjectionOverlap(Vector2 first, Vector2 second) {
+    float32 e = MIN(first.y, second.y);
+    float32 f = MAX(first.x, second.x);
+    return e - f;
+}
+
+bool runSatForShapesEdges(SATResult* result, ConvexPolygon* first, ConvexPolygon* second) {
+    for (int i = 0; i < first->numVertices; i++) {
+        Vector2 normal = first->edges[i].normal;
+
+        ProjectionResult firstProj = getProjection(first->transformedVertices, first->numVertices, normal);
+        ProjectionResult secondProj = getProjection(second->transformedVertices, second->numVertices, normal);
+
+        if (!projectionsOverlap(firstProj.projection, secondProj.projection)) {
+            return false;
+        }
+
+        float32 overlap = getProjectionOverlap(firstProj.projection, secondProj.projection);
+        if (overlap < result->minOverlap) {
+            result->minOverlap = overlap;
+            result->minOverlapEdge = &first->edges[i];
+            
+            // The overlapPoint will be the point on the other shape that penetrated the edge.
+            // If we caught the intersection reasonably early, it should be the point on 'second'
+            // that is nearest to the points on 'first'.
+            float32 min1min2 = (firstProj.minVertex - secondProj.minVertex).length();
+            float32 min1max2 = (firstProj.minVertex - secondProj.maxVertex).length();
+            float32 max1max2 = (firstProj.maxVertex - secondProj.maxVertex).length();
+            float32 max1min2 = (firstProj.maxVertex - secondProj.minVertex).length();
+            
+            float32 closest = MIN(min1min2, MIN(min1max2, MIN(max1max2, max1min2)));
+            if (closest == min1min2 || closest == max1min2) {
+                result->overlapPoint = secondProj.minVertex;
+            } else {
+                result->overlapPoint = secondProj.maxVertex;
+            }
+        }
+    }
+
+    return true;
+}
+
+const float32 EPSILON = 1.f;
+IntersectionResult getIntersection(ConvexPolygon* first, ConvexPolygon* second) {
+    IntersectionResult ir;
+    SATResult sat;
+    
+    if (!runSatForShapesEdges(&sat, first, second)) {
+        return ir;
+    }
+
+    if (!runSatForShapesEdges(&sat, second, first)) {
+        return ir;
+    }
+
+	ir.intersect = true;
+	ir.relativeVelocity = first->body.velocity - second->body.velocity;
+	ir.collisionNormal = sat.minOverlapEdge->normal;
+    ir.firstPointOfApplication = sat.overlapPoint - first->body.position;
+    ir.secondPointOfApplication = sat.overlapPoint - second->body.position;;
+
+	return ir;
+}
+

+
+
+

Live Example of Intersection Detection

diff --git a/2d/_collisions/polygon_polygon.html.content b/2d/_collisions/polygon_polygon.html.content index 4f99d71..f2a9253 100644 --- a/2d/_collisions/polygon_polygon.html.content +++ b/2d/_collisions/polygon_polygon.html.content @@ -20,9 +20,21 @@

The Separating Axis Theorem (SAT) provides a way to find the intersection between any n-sided convex polygon or circle. In this tutorial, I will explain how this theorem works, and how you can use it to both detect and resolve collisions in your simulation.

+ +
-

Explanation of Separating Axis Theorem

+

Explanation of Separating Axis Theorem

SAT makes use of vector projection to figure out whether or not two concave polygons are intersecting. I believe the best way to describe it is to show you the instance where two polygons do not intersect. @@ -95,7 +107,7 @@

-

Algorithm for Finding the Intersection

+

Algorithm for Finding the Intersection

Given two polygons A and B: @@ -113,7 +125,7 @@

-

SAT Collision Resolution

+

SAT Collision Resolution

Now that we know that our objects have intersected, we want to send them tumbling away from one another in order to simulate a collision. To do this, we will need to find the following things:

- To find these values, we must first find both the shape and the edge that caused the intersection in the first place. To do this, we will think about what we know so far and try to arrive at some intutitive understanding of it. Keep in mind that I am not a proof-minded person, so you will not be finding that here. -
- -

Finding the Intersecting Edge

+

Finding the Intersecting Edge

We can already figure out that the following two triangles intersect one another:

@@ -136,7 +145,9 @@

- We know that A can only intersect B if: (1) a vertex from A is inside of B, (2) an edge of A flatly intersects an edge of B, or (3) a vertex of A overlaps exactly a vertex of B. Honestly, for our purposes, scenarios 2 and 3 are quite unlikely, but we can explore them a bit just to see how we might resolve them. We will start with the first case, since it is more likely. We will start by drawing the axis defined by the leftmost edge of B with both polygons projected onto it: + We know that A can only intersect B if: (1) a vertex from A is inside of B, (2) an edge of A flatly intersects an edge of B, or (3) a vertex of A overlaps exactly a vertex of B. For our purposes, scenario 3 is quite unlikely, so we can ignore it for now. We will start with the first case, since it is the most likely. +

+ The following drawing shows both of our objects projected onto the axis defined by object B's leftmost edge:

@@ -145,22 +156,34 @@

- This is a poorly drawn picture, but you should be able to see that the bit in green represents the intersection between the projections of the two polygons. If we were to repeat this same exercise for every edge here, we'll begin to see something very interesting. And, if we take new shapes and continue this stategy, we can begin to come to a very elegant conclusion: -
-
- - The intersecting edge will be the one where the projection of triangle A overlaps with the projection of triangle B the least! - -

- I'm sure someone more inclined to proving mathematical truities would love to describe this to you, but, for all intents and purposes, this intutitive understanding is good enough for us. We just want to make games, anyhow. -
-

Finding which point causes the intersection

+ If you were to repeat this exercise of projecting the shapes onto every axis of both shapes, you will begin to unconver an interesting truth: The intersecting edge will be the one where the projection of triangle A overlaps with the projection of triangle B the least! This should be unsurprising if you consider it. If our simulation is running quickly enough, the point of object A that is penetrating the edge of object B will just barely be inside of B. At the same time, it should be the only point that is currently inside of B. Hence, the overlap of the projection on that axis will be from that edge of B to that point on A. Knowing that this edge caused the intersection, we now have the collision normal. +
+

Finding which point causes the intersection

+ This part is made easy by the fact that we know which edge of object B caused the intersection in the first place. We know, then, that the intersecting point on object A must be the point that is currently inside of B. Simply put, this point will be the vertex of A that was projected onto that axis that is closest to the edge of B. This will be true so long as the simulation is properly fast and the object is not infinitesmley small (in which case, we're dealing with particle physics, and you shouldn't be using this tutorial). +

+
+
+

Algorithm for Collision Resolution

+ +

+ + Given two polygons A and B: +

    +
  1. Find the intersecton as before
  2. +
  3. While finding the intersection, keep track of the axis that the projection on object A overlapped with the corresponding projection on object B the least. Remember the edge that this that held this axis.
  4. +
  5. Using this axis, find out which point on the other object inside of the edge by comparing the distances from the two points on the edge to the two points projected onto the axis created by that edge.
  6. +
  7. Use the calcualted edge to find the normal and the overlap point to find the point of application.
  8. +
+ + And that is it! Here is the code for this algorithm: + + #SNIPPET polygon_polygon/snippet2.cpp

-

+

Live Example of Intersection Detection

diff --git a/2d/_collisions/polygon_polygon/snippet2.cpp b/2d/_collisions/polygon_polygon/snippet2.cpp new file mode 100644 index 0000000..8cbdcbe --- /dev/null +++ b/2d/_collisions/polygon_polygon/snippet2.cpp @@ -0,0 +1,117 @@ +struct IntersectionResult { + bool intersect = false; + Vector2 collisionNormal; + Vector2 relativeVelocity; + Vector2 firstPointOfApplication; + Vector2 secondPointOfApplication; +}; + +struct Edge { + Vector2 normal; + Vector2 start; + Vector2 end; +}; + +struct SATResult { + Edge* minOverlapEdge = NULL; // Edge that caused the intersection (on the 'first' shape) + Vector2 overlapPoint; // Point that caused the intersection (on the 'second' shape) + float32 minOverlap = FLT_MAX; // Smallest projection overlap +}; + +struct ProjectionResult { + Vector2 minVertex; + Vector2 maxVertex; + Vector2 projection; +}; + +// Given the vertices in the shape, we find the min and max vertices that project +// onto the axis. We also save which vertices were which so that we can resolve +// the collision later. +ProjectionResult getProjection(Vector2* vertices, int numVertices, Vector2 axis) { + ProjectionResult pr; + float32 min = axis.dot(vertices[0]); + float32 max = min; + + for (int v = 1; v < numVertices; v++) { + float32 d = axis.dot(vertices[v]); + + if (d < min) { + pr.minVertex = vertices[v]; + min = d; + } else if (d > max) { + pr.maxVertex = vertices[v]; + max = d; + } + } + + pr.projection = Vector2 { min, max }; + return pr; +} + +bool projectionsOverlap(Vector2 first, Vector2 second) { + return first.x <= second.y && second.x <= first.y; +} + +float32 getProjectionOverlap(Vector2 first, Vector2 second) { + float32 e = MIN(first.y, second.y); + float32 f = MAX(first.x, second.x); + return e - f; +} + +bool runSatForShapesEdges(SATResult* result, ConvexPolygon* first, ConvexPolygon* second) { + for (int i = 0; i < first->numVertices; i++) { + Vector2 normal = first->edges[i].normal; + + ProjectionResult firstProj = getProjection(first->transformedVertices, first->numVertices, normal); + ProjectionResult secondProj = getProjection(second->transformedVertices, second->numVertices, normal); + + if (!projectionsOverlap(firstProj.projection, secondProj.projection)) { + return false; + } + + float32 overlap = getProjectionOverlap(firstProj.projection, secondProj.projection); + if (overlap < result->minOverlap) { + result->minOverlap = overlap; + result->minOverlapEdge = &first->edges[i]; + + // The overlapPoint will be the point on the other shape that penetrated the edge. + // If we caught the intersection reasonably early, it should be the point on 'second' + // that is nearest to the points on 'first'. + float32 min1min2 = (firstProj.minVertex - secondProj.minVertex).length(); + float32 min1max2 = (firstProj.minVertex - secondProj.maxVertex).length(); + float32 max1max2 = (firstProj.maxVertex - secondProj.maxVertex).length(); + float32 max1min2 = (firstProj.maxVertex - secondProj.minVertex).length(); + + float32 closest = MIN(min1min2, MIN(min1max2, MIN(max1max2, max1min2))); + if (closest == min1min2 || closest == max1min2) { + result->overlapPoint = secondProj.minVertex; + } else { + result->overlapPoint = secondProj.maxVertex; + } + } + } + + return true; +} + +const float32 EPSILON = 1.f; +IntersectionResult getIntersection(ConvexPolygon* first, ConvexPolygon* second) { + IntersectionResult ir; + SATResult sat; + + if (!runSatForShapesEdges(&sat, first, second)) { + return ir; + } + + if (!runSatForShapesEdges(&sat, second, first)) { + return ir; + } + + ir.intersect = true; + ir.relativeVelocity = first->body.velocity - second->body.velocity; + ir.collisionNormal = sat.minOverlapEdge->normal; + ir.firstPointOfApplication = sat.overlapPoint - first->body.position; + ir.secondPointOfApplication = sat.overlapPoint - second->body.position;; + + return ir; +} -- cgit v1.2.1