# Generate circles in cell 2D

I want to generate circles as the distribution of random circles in a square cell. these circles have the same radius. constraints applied to these circles are: (i) these circles not overlap each other. (ii) these circles do not touch the square cell walls.

I want to create this algorithm with python, can you help me?

This script should do the trick:

import bpy
from mathutils import Vector
from random import random

def check_circle_bounbox( circC, circR, rectC, rectR ):
''' Make sure this circle does not protrude outside the rectangle's bounding box '''
maxX = rectC.x + rectR
minX = rectC.x - rectR
maxY = rectC.y + rectR
minY = rectC.y - rectR

withinX = ( circC.x + circR <= maxX ) and ( circC.x - circR >= minX )
withinY = ( circC.y + circR <= maxY ) and ( circC.y - circR >= minY )

return withinX and withinY

def check_overlap( circles, circC, circR ):
''' Make sure the distance between the current circle's center and all
other circle centers is greater than or equal to the circle's perimeter (2r)
'''
return len(
[ True for c in circles if ( c - circC ).length >= circR * 2 ]
) == len( circles )

circleCount  = 50
rectCenter   = Vector((0, 0, 0))

circles = []

maxIterations = 500 # Set max number of loop iterations to prevent infinite loop

z = 0 # All circles lie on Z = 0
i = 0 # Current loop iteration
while len( circles ) < circleCount and i < maxIterations:
circC = Vector((x, y, z ))

and check_overlap( circles, circC, circleRadius ):
circles.append( circC )

i += 1

for c in circles:
• good work, thank you TLouskyn for Full circle, how to add this type May 8, 2016 at 13:01
• the faces of circles are full (ex: ekladata.com/2xrMvGO8ZBWexfsolnVoKFhqeNg.jpg) May 8, 2016 at 13:45
• @saded, I changed the fill type to NGON (default is no fill). May 8, 2016 at 13:49
• yes, how to add this? May 8, 2016 at 13:52
• Use the updated script in the answer above. The last line (#48) was changed to set the fill type parameter with fill_type = 'NGON'. May 8, 2016 at 13:53

Particle System

Some stages of creation.

User Ortho View above

• [A] Plane with Loop Cuts
• [B] Edit Mode. Face Mode. Inset Faces. Vertex Mode. Invert selection. Delete Vertices. Faces remain with empty margin.
• [C] Edit Mode. Face Mode. Random Select from Menu. Delete Faces.
• [D] Particle System using blue torus as Render [Object]. The radius of torus < (.5 Margin) is the intention.

Image Editor Render Result

• Particles Rendered

Particle System settings shown above.

Of course your variations and improvements are welcome. Click on image to see larger version.

• I don't think this is Random May 7, 2016 at 19:19
• Good work, but I want a script python May 7, 2016 at 19:42