# WebGL Experiment Demonstrates Barnes-Hut N-Body Simulation of a Growing Watermelon in a Box

### BY MARKUS SPRUNCK

Japan produces watermelons which have a cubic shape. USA Today reported in 2013 that these melons have been sold for up to 850\$ in Moscow  - quite expensive for a simple melon. To produce this unusual shape the young melon fruits are put into a box. The growing melons are then forced into the cubic shape.

In the following WebGL experiment this growth into a cubic shape is simulated with an N-Body-Simulation. This WebGL experiment demonstrates how to simulate a growing watermelon in a web browser. You may start the web application with a WebGL enabled browser here http://webgl-examples.appspot.com/square-melon/melon.html. The complete source code is available on GitHub.

## Expected Result

The WebGL simulation is not a simple geometrical transformation from a sphere to a cube. It uses an N-Body-Simulation which calculates the forces between the nodes of a sphere. Figure 1: Start of Simulation Figure 2: End of Simulation

The underlying model for the melon has 400 nodes and 420 links between the nodes. All nodes repulse each other and the links work as springs to keep them together. Figure 3: Model of N-Body Simulation with 400 vertices/nodes

## Why Barnes-Hut-Algorithm is needed?

A simple three.js sphere with 400 nodes is used to render the melon. To calculate all repulsive forces between the nodes would need 400*(400-1)/2 or 79800 single calculations - a quite CPU intensive task.

One solution to improve performance is to reduce the number of calculations with an approximation of the repulsive forces. Groups of nodes which are far away can be handled as a single node. This can be done with an optimal data structure. One approach to do this, is the so called Barnes-Hut-Algorithm designed for astronomical problems.

You find an excellent description of two dimensional Barnes-Hut-Algorithm in the article http://arborjs.org/docs/barnes-hut. For the growing watermelon the Barnes-Hut-Algorithm is implemented for three dimensions in JavaScript.