Skip to content

Instantly share code, notes, and snippets.

@oshoham
Last active September 24, 2017 21:13
Show Gist options
  • Save oshoham/2199e0bfb3a53dba4ee6395586212791 to your computer and use it in GitHub Desktop.
Save oshoham/2199e0bfb3a53dba4ee6395586212791 to your computer and use it in GitHub Desktop.
circle packing for the laser cutter
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/QHEQuoIKgNE
class Circle {
float x;
float y;
float r;
boolean growing = true;
Circle(float x_, float y_, float r_) {
x = x_;
y = y_;
r = r_;
}
void grow() {
if (growing) {
r = r + 0.5;
}
}
boolean edges() {
return (x + r > width || x - r < 0 || y + r > height || y -r < 0);
}
void show() {
stroke(0);
strokeWeight(1);
noFill();
ellipse(x, y, r*2, r*2);
}
}
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/QHEQuoIKgNE
import processing.pdf.*;
ArrayList<Circle> circles;
void setup() {
circles = new ArrayList<Circle>();
for (int i = 0; i < 1000; i++) {
int total = 10;
int count = 0;
int attempts = 0;
while (count < total) {
Circle newC = newCircle();
if (newC != null) {
circles.add(newC);
count++;
}
attempts++;
if (attempts > 1000) {
noLoop();
println("FINISHED");
break;
}
}
for (Circle c : circles) {
if (c.growing) {
if (c.edges()) {
c.growing = false;
} else {
for (Circle other : circles) {
if (c != other) {
float d = dist(c.x, c.y, other.x, other.y);
if (d - 0.5 < c.r + other.r) {
c.growing = false;
break;
}
}
}
}
}
c.grow();
}
}
beginRecord(PDF, "/Users/barakchamo/Desktop/circle_packing.pdf");
size(100, 100);
pushMatrix();
}
void draw() {
background(255);
for (Circle c : circles) {
c.show();
}
endRecord();
}
Circle newCircle() {
float x = random(width);
float y = random(height);
float r = 1;
boolean valid = true;
for (Circle c : circles) {
float d = dist(x, y, c.x, c.y);
if (d - 0.5 < r + c.r) {
valid = false;
break;
}
}
if (valid) {
return new Circle(x, y, r);
} else {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment