Barnes-Hut: Gravity in n log n
Hundreds of bodies pull on each other, but a quadtree lets distant clumps act as one mass, turning an n squared force sum into n log n. Tune the opening angle and watch accuracy trade against speed.
Barnes-Hut: Gravity in n log n
Every body pulls on every other one. Summing all those pairs costs n squared work per frame, which stalls past a few hundred bodies. Barnes-Hut rebuilds a quadtree each frame and lets a distant clump of stars act as a single point mass, so the force on one body costs a walk of order log n, and hundreds of bodies run in real time. The control is the opening angle theta, which decides how distant is distant enough.
else : open the node and walk its four children
For each body the walk starts at the root cell. s is the cell width and d is the distance from the body to the cell's center of mass. A small s over d means the cell sits far away and tight on the sky, so the bodies inside it are well approximated by their combined mass at one point. A large ratio means the cell looms large, and lumping it would be inaccurate, so the walk descends into the four children and asks again. Because each descent quarters the area, a body reaches the approximation after about log n steps instead of touching all n bodies.
theta = 0 never accepts an approximation, so the walk opens every cell down to single bodies and you get exact brute-force gravity at n squared cost: watch the force-eval count climb to match the brute figure. Raising theta accepts coarser groupings, cutting the eval count and lifting the frame rate while adding a small force error. Galaxy simulations usually sit near theta = 0.5 to 1.0, which is the trade this slider lets you feel directly.
The force law is Newtonian with a softening length epsilon added inside the denominator. Without it, two bodies that pass close share a near-zero separation, the 1 over r squared term explodes, and the integrator flings them to infinity in a single step. Softening caps the closest-approach force so the run stays well behaved. Larger epsilon makes the gravity gentler and the disk puffier.
Integration is velocity-Verlet, a symplectic scheme that half-kicks the velocity, drifts the position, recomputes the force, then half-kicks again. Symplectic integrators keep the total energy bounded over long runs rather than letting it bleed away the way plain Euler does, which is why the orbits hold their shape instead of spiraling in or flying apart. The energy-drift readout tracks how far the total energy has wandered from its starting value. Shrink the timestep to tighten it.