Spirograph wreath, done with simple n-body vortex method
in
Share your Work
•
1 month ago
Here is a simple program that I use to teach computational physics to non-programmers. It's an n-body code which uses a vortex kernel in 2D to draw lines. The initial positions and strength are set to generate a fuzzy, growing spirograph-like wreath in the middle of the screen.
- // vortex - advanced version
// Mark J Stock
// me@markjstock.com
// use this many particles
int num = 400;
// this variable scales how fast everything moves
float dt = 2.0;
// these arrays store the parameters for each particle
float[] x = new float[num];
float[] y = new float[num];
float[] s = new float[num];
// this gets run only once, before any iteration begins
void setup() {
size(1280, 960);
for (int i=0; i<num; i=i+1) {
// create the particles randomly in the middle of the screen
//x[i] = random(100, 540);
//y[i] = random(100, 380);
// or, create them along a circle
float rad = height/3.5;
float theta = i*2.0*3.1415927/num;
x[i] = width/2.0 + rad*sin(theta);
y[i] = height/2.0 + rad*cos(theta);
// here we set the strength, centered on zero
s[i] = random(-1, 1);
}
frameRate(60);
background(50);
}
// this gets called once for each frame
void draw() {
// turn off outlines
noStroke();
// set the color for all particles
// four numbers are: red, green, blue, alpha/transparency
// each covers a range from 0 to 255
fill(255, 255, 255, 12);
// loop over the vortex particles
for (int i=0; i<num; i=i+1) {
// compute the new velocity of each particle
float velx = 0.0;
float vely = 0.0;
for (int j=0; j<num; j=j+1) {
// particle j affects particle i's speed based on
// a function of the distance and the direction
// between the two particles
float dx = x[j] - x[i];
float dy = y[j] - y[i];
// the 1.0 here is a smoothing parameter
float distsq = dx*dx + dy*dy + 1.0;
// this kernel looks like attraction/repulsion
//velx = velx + s[j]*dx/distsq;
//vely = vely + s[j]*dy/distsq;
// this kernel looks like fluid dynamics
velx = velx - s[j]*dy/distsq;
vely = vely + s[j]*dx/distsq;
}
// move each particle according to its new velocity
x[i] = x[i] + dt*velx;
y[i] = y[i] + dt*vely;
// and draw each particle as a 2x2 pixel circle
ellipse(x[i], y[i], 2.0, 2.0);
}
}
void keyPressed() {
if (key == 'p') {
saveFrame("img_vortex_#####.png");
}
}