Creating 3D Voronoi with Hemesh
Posted on 2011-01-31 by Jan Vantomme
Tags:
processing, tutorial
EDIT: Some things have changed in the latest version of Hemesh. These examples don't work with this version. I wrote an article that explains how to use the new WB_Render class to draw the meshes to the screen. Read it over here.
In this article, I'm going to show you the techniques I've used to create these 3D Voronoi images I posted on Flickr a while ago. The first thing you need is a mesh to use as the container for the voronoi cells. You can use any of the creators I wrote about. I'm going to use a geodesic sphere in this article.
The first thing you need to do is creating the container mesh. I created a level 3 geodesic sphere with a radius of 150 pixels.
HEC_Geodesic creator = new HEC_Geodesic(this).setRadius(150).setLevel(3);
mesh = new HE_Mesh(creator);
The next thing you need is to generate an array of 3D points. These points will be used to create the voronoi cells. I've created an array of 25 points with X, Y and Z values between -150 and 150.
float[][] points = new float[numCells][3];
for (int i = 0; i < numCells; i++) {
points[i][0] = random(-150, 150);
points[i][1] = random(-150, 150);
points[i][2] = random(-150, 150);
}
Next thing is to create the actual cells. You can do this by using HEMC_VoronoiCells
which is a multicreator. Every cell created is a HE_Mesh object. Before you create the voronoi cells, you'll need to declare an empty HE_Mesh[]
array at the beginning of your sketch.
HEMC_VoronoiCells vc = new HEMC_VoronoiCells(this).setPoints(points).setContainer(mesh).setOffset(3);
voronoiCells = vc.create();
To draw everything to the screen, you'll need a for-loop to go through the array and draw each cell to the screen.
for (int i = 0; i < numCells; i++) {
noStroke();
fill(128);
voronoiCells[i].drawFaces();
}
Another thing I did is create a lattice from a number of voronoi cells and draw them in another color. I'm using an array to keep track of which mesh to draw in which color. I did this right after creating the cells.
colorArray = new int[numCells];
for (int i = 0; i < numCells; i++) {
if ( random(100) < 30 ) {
HEM_Lattice lattice = new HEM_Lattice().setWidth(6).setDepth(6);
voronoiCells[i].modify(lattice);
colorArray[i] = 1;
} else {
colorArray[i] = 0;
}
}
And the last piece of code shows you how to draw the cells with different colors to the screen.
for (int i = 0; i < numCells; i++) {
noStroke();
if (colorArray[i] = = 1) {
fill(c2);
} else {
fill(c1);
}
voronoiCells[i].drawFaces();
}
The result should look like the image below. Download the 3D Voronoi example. Feel free to experiment with the code. Have fun!