toxiclibs voronoi to GLGraphics GLModel
in
Contributed Library Questions
•
1 year ago
Hi, I am wondering what is the best way to render an arbitrary number of polygons with different vertex counts using GLGraphics?
I have a toxiclibs voronoi instance, and I'm taking its regions and feeding the vertices of each region into a separate GLModel. I have the feeling this is not the most efficient way to do it. Performance starts to suffer with less than 200 vertices.
I suspect I could put all vertices in one GLModel and somehow keep track which vertex belongs to which region, and then call GLModel.render(first, last) as many times as needed to draw each polygon.
But then I'm not sure what mode to set for the GLModel - TRIANGLE_STRIP would bind all regions into one, TRIANGLES would probably create problems when I try to texture each region with a different image. POLYGON turns all points into one single polygon...
Here's my code:
import processing.opengl.PGraphicsOpenGL;
import toxi.geom.Polygon2D;
import toxi.geom.Vec2D;
import toxi.geom.mesh2d.Voronoi;
import codeanticode.glgraphics.GLConstants;
import codeanticode.glgraphics.GLGraphics;
import codeanticode.glgraphics.GLModel;
Voronoi voronoi = new Voronoi();
ArrayList<GLModel> glModels = new ArrayList<GLModel>();
int numVertices = 150;
public void setup() {
size(600, 600, GLConstants.GLGRAPHICS);
smooth();
initVoronoi();
regionsToGLModels();
}
private void initVoronoi() {
for (int i = 0; i < numVertices; i++) {
voronoi.addPoint(new Vec2D(random(600), random(600)));
}
}
private void regionsToGLModels() {
for (Polygon2D region : voronoi.getRegions()) {
ArrayList<PVector> regionVertArray = new ArrayList<PVector>();
for (Vec2D vertex : region.vertices) {
regionVertArray.add(new PVector(vertex.x, vertex.y, 0));
}
GLModel glRegion = new GLModel(this, region.vertices.size(), GLModel.POLYGON, GLModel.STATIC);
glRegion.updateVertices(regionVertArray);
coloriseRegions(glRegion);
glModels.add(glRegion);
}
}
public void draw() {
background(0);
GLGraphics renderer = (GLGraphics) g;
renderer.beginGL();
for (GLModel model : glModels) {
updateVertexPositions(model);
model.render();
}
renderer.endGL();
}
private void coloriseRegions(GLModel model) {
model.initColors();
model.beginUpdateColors();
for (int i = 0; i < model.getSize(); i++)
model.updateColor(i, random(255) + 10 * i, random(255), random(255), 255);
model.endUpdateColors();
}
private void updateVertexPositions(GLModel model) {
model.beginUpdateVertices();
for (int i = 0; i < model.getSize(); i++) {
model.displaceVertex(i, random(-1f, 1f), random(-1f, 1f), random(-1f, 1f));
}
model.endUpdateVertices();
}
1