How can I render a simple lattice in LibGDX?

| | August 6, 2015

I have searched all over, but I can’t find what I think will be a simple answer. I am using Opengl ES 2.0, and LibGDX. I simply want to use GL_LINES primitives to create a lattice structure.

I have used shapeRenderer with the following code:
in create():

shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);

in render():

shapeRenderer.setProjectionMatrix(cam.combined);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(0, 1, 0, 1);
for (float i = -10; i <=10; i++) {
    for (float j = -10; j <= 10; j++){
        shapeRenderer.line(i, j, -10, i, j, 10);
        shapeRenderer.line(-10, i, j, 10, i, j);
        shapeRenderer.line(j, -10, i, j, 10, i);
    }
}
shapeRenderer.end();

The problem is, this is not a model instance, thus doesn’t seem to use the RendererContext (GL_DEPTH_TEST, etc.). When I render the lattice this way, it either shows up entirely behind my models, or entirely in front of them (depending on the order I render them in the render method).

Is there a way to build a model which is simply a set of lines to be rendered with Opengl primitive GL_LINES? Any pointers would be greatly appreciated.

One Response to “How can I render a simple lattice in LibGDX?”

  1. snapfractalpop on November 30, -0001 @ 12:00 AM

    Ok, I found a way. I’m not sure that it’s the most performant, but it works, and the DEPTH_TEST (z-culling) is working now. Here is how I did it:

    in declarations:

    private ModelInstance mLattice;
    

    in create():

    ModelBuilder modelBuilder = new ModelBuilder();
    modelBuilder.begin();
    MeshPartBuilder meshPartBuilder = modelBuilder.part("lattice", GL20.GL_LINES,
            Usage.Position, new Material(ColorAttribute.createDiffuse(Color.GREEN)));
    
    for (float i = -10; i <=10; i++) {
        for (float j = -10; j <= 10; j++){
            meshPartBuilder.line(i, j, -10, i, j, 10);
            meshPartBuilder.line(-10, i, j, 10, i, j);
            meshPartBuilder.line(j, -10, i, j, 10, i);
        }
    }
    
    Model latticeModel = modelBuilder.end();
    mLattice = new ModelInstance(latticeModel);
    instances.add(mLattice);
    

    in render():

    modelBatch.begin(cam);
    modelBatch.render(instances, environment);
    modelBatch.end();
    

    This solved my problem. There may be better (more efficient) ways to accomplish this, but this suits my needs at the moment. If I find something better, I’ll update the answer for anyone who may stumble upon this.

Leave a Reply