Michael Bradford Williams

Home / Programming / Random Circle Packing

There are several related definitions, but let us say that a circle packing is a collection of circles in the plane whose interiors do not overlap. This page demonstrates an algorithm to create a random circle packing with the added property that no circle in the packing can be enlarged without creating an overlap. The basic idea is to build the packing one circle at a time, in a greedy fashion, meaning each circle is made to be as large as possible given the previously existing circles. There is a built-in overall maximum radius size, and a maximum number of circles allowed in the circle packing.

In a bit more detail, once a center point for a new circle is randomly selected, its circle is given a small radius, in this case 1 pixel. Then the radius is iteratively increased according to the following logic.

In the case where the circle is tangent to 1 other circle, as the radius increases, the center point moves along the straight line joining the two centers. In the case where the circle is tangent to 2 other circles, as the radius increases, the center point moves in a more complicated way. Namely, if the center is \((x,y)\) and the proposed radius is \(r\), and the tangent circles have centers \((x_1,y_1), (x_2,y_2)\) and radii \(r_1, r_2\), then \((x,y)\) is determined by this data by solving two equations that describe tangency: \[ \begin{align*} (x-x_1)^2 + (y-y_1)^2 &= (r+r_1)^2 \\ (x-x_2)^2 + (y-y_2)^2 &= (r+r_2)^2 \end{align*} \] The resulting expressions for \(x\) and \(y\) are messy and highly non-linear, but closed-form. This non-linearity introduces the possibility that the center moves "too quickly" as the circle's radius increases, and that the circle will end up overlapping another circle, even if the change in radius is very small. Care was needed to avoid this, but the solution isn't perfect. (Look closely and you might find a few cases where some circles have a small overlap.)

There are three visualization modes for the circle packing: (1) simple, meaning just the circles are drawn; (2) simple, but with connections between tangent circles drawn (e.g., this is the tangency graph of the circle packing), and (3) circles represented by randomly colored disks.

Here is a larger version of the program more suited to desktop browsers.

Your browser is currently unsupported.