Optimizing gravitation calculation for particles in a zero gravity 2d space

前端 未结 5 1067
北荒
北荒 2021-01-13 07:28

I\'ve have created a small visualisation of particles in python. I\'m caclulation the movement of particels in a 2D space with zero gravity. As each particle attracts all o

5条回答
  •  梦谈多话
    2021-01-13 07:56

    I've worked on this previously, and one of the things I've seen in the past to accelerate collision calculations is to actually store a list of nearby particles.

    Basically, the idea is inside of your gravity calculation you do something like:

    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            DoGravity(Particle[i], Particle[j]);
            if (IsClose(Particle[i], Particle[j]))
            {
                Particle[i].AddNeighbor(Particle[j]);
                Particle[j].AddNeighbor(Particle[i]);
            }
        }
    }
    

    Then, you simply pass over all particles and you do collision detection on each on in turn. This is usually something like O(n) in best case, but it can easily degrade to O(n^2) in the worst case.

    Another alternative is to try placing your particles inside of a Octree. Building one up is something like O(n), then you can query it to see if anything is near each other. At that point you'd just do collision detection on the pairs. Doing this is O(n log n) I believe.

    Not only that, but you can use the Octree to accelerate the gravity calculation as well. Instead of O(n^2) behavior, it drops down to O(n log n) as well. Most Octree implementations include an "opening parameter" that controls the speed vs accuracy trade off you'll be making. So Octrees tend to be less accurate than a direct pairwise calculation and complicated to code up, but they also make large scale simulations possible.

    If you use the Octree in this manner, you'll do what's known as a Barnes-Hut Simulation.

    Note: Since you're working in 2D, the 2D analogue to an Octree is known as a Quadtree. See the following Wikipedia article for more information: http://en.wikipedia.org/wiki/Quadtree

提交回复
热议问题