I am working on a 3D/physics engine using C++ and OpenGL.
Currently I’m in the process of implementing the “Sweep and Prune”-method for collisions checks using AABB (axis aligned bounding boxes). I’m roughly following the method outlined here (part 1 & 2): https://leanrada.com/notes/sweep-and-prune/
The algorithm works by sorting the min & max coordinates of each axis for each AABB box:
- vectors (sorted by coordinate) for the X-, Y- and Z-axises
- The algorithm also requires to know if each edge is the minimum coordinate or the maximum.
- Also the ID of the entity it belongs to.
For this data I’m using this struct called Edge:
struct Edge {
int id;
bool isLeft;
float coord;
Edge(int id, bool isLeft, float coord)
: id(id), isLeft(isLeft), coord(coord) {}
}
};
Example of Entity class with relevant functions for Edge:
class Entity
{
public:
int id;
std::vector<Edge> edgesList;
std::vector<glm::vec3> vertices;
std::vector<unsigned int> indices;
glm::vec3 position;
// create Edges
void setupEdges(const std::vector<float>& minMax)
{
// Create Edge objects and add them to edgesList
edgesList.emplace_back(id, true, minMax[0]); // min_X
edgesList.emplace_back(id, false, minMax[1]); // max_X
edgesList.emplace_back(id, true, minMax[2]); // min_Y
edgesList.emplace_back(id, false, minMax[3]); // max_Y
edgesList.emplace_back(id, true, minMax[4]); // min_Z
edgesList.emplace_back(id, false, minMax[5]); // max_Z
}
// update Edges. The new coordinates are calculated separately in another function
void updateEdges(const std::vector<float>& minMax)
{
edgesList[0].coord = minMax[0]; // new min_X
edgesList[1].coord = minMax[1]; // new max_X
edgesList[2].coord = minMax[2]; // new min_Y
edgesList[3].coord = minMax[3]; // new max_Y
edgesList[4].coord = minMax[4]; // new min_Z
edgesList[5].coord = minMax[5]; // new max_Z
}
To save on performance I want to use insertion sort for the axis-vectors (since generally Entities will not switch places every frame).
Also I would like to update the Edge-structs from inside the Entity-objects and have it automatically update the axis-vectors.
Question: How do I put all Edge-structs from all Entities inside a single vector, while still being able to update the values from inside each Entity (which the structs belong to)? Especially after sorting said vector
4