I'm making a fluid simulator and for this I have made a grid to store the particles in each cell so I can limit collision checks to only the neighbors of each particle. Now I have managed to implement the grid and It does indeed store the particles in the right cell but when I iterate over the particles in the grid and update their values the update doesn't show up in the main container of the particles.
Here is how I made the grid:
void clearGrid(Grid& grid)
{
for (int i = 0; i < grid.width; ++i) {
for (int j = 0; j < grid.height; ++j) {
grid.cells[i][j].clear();
}
}
}
void createGrid(Grid& grid)
{
grid.cells.resize(grid.width + 1); // Resize the outer vector to have a size equal to grid.width
for (int i = 0; i < grid.width; ++i) {
grid.cells[i].resize(grid.height + 1); // Resize each inner vector to have a size equal to grid.height
}
}
void updateGrid(Grid& grid, std::vector<Particle>& particles)
{
grid.cells.clear(); // reset the grid
createGrid(grid); // remake the grid in reference
for (Particle& particle : particles)
{
// calculate cell indices and multiply to find in which cell we are
int cell_x = static_cast<int>((particle.position.x + 4) / grid.cellSize);
int cell_y = static_cast<int>((particle.position.y + 3) / grid.cellSize);
// sometimes particle pushed past the wall gotta correct the value
if (cell_x > grid.width - 1) cell_x = grid.width - 1;
if (cell_y > grid.height - 1) cell_y = grid.height - 1;
grid.cells[cell_x][cell_y].push_back(particle);
}
// make the neighbors here
}
Here is how the particle is made and in the main.cpp it is in a std::vector<Particle> particles:
struct Particle
{
glm::vec2 position;
glm::vec2 velocity;
float density;
float density0 = 1000; //
const float mass = 1.0f;
const float radius = 0.02f;
const int segments = 6;
};