Java – The offset of each vertex data interleaved in OpenGL ES on Android

The offset of each vertex data interleaved in OpenGL ES on Android… here is a solution to the problem.

The offset of each vertex data interleaved in OpenGL ES on Android

Is it possible to use interleaved vertex data in OpenGL ES on Android?

I can’t get the correct offset pointer for normal the and color member.

In C++ I would do something like this:

struct ColoredVertexData3D{
    Vertex3D    vertex;
    Vector3D    normal;
    ColorRGBA   color;
};

const ColoredVertexData3D vertexData[] =
{
    {
        {0.0f, 0.5f, 0.8f},       // Vertex |
        {0.0f, 0.4f, 0.6f},       // Normal | Vertex 0
        {1.0f, 0.0f, 0.0f, 1.0f}  // Color  |
    },
    {
        {0.8f, 0.0f, 0.5f},       // Vertex |
        {0.6f, 0.0f, 0.4f},       // Normal | Vertex 1
        {1.0f, 0.5f, 0.0f, 1.0f}  // Color  |
    },
    // ... more vertexes.
};

const int stride = sizeof(ColoredVertexData3D);
glVertexPointer(3, GL_FLOAT, stride, &vertexData[0].vertex);
glColorPointer(4, GL_FLOAT, stride, &vertexData[0].color);
glNormalPointer(GL_FLOAT, stride, &vertexData[0].normal);

Can Java do the same thing on Android? Here’s what I’m getting so far:

ByteBuffer vertexData = ...;
int stride = 40;

gl.glVertexPointer(3, GL10.GL_FLOAT, stride, vertexData);

// This obviously doesn't work. ------------v
gl.glColorPointer(4, GL10.GL_FLOAT, stride, &vertexData[0].color);
gl.glNormalPointer(GL10.GL_FLOAT, stride, &vertexData[0].normal);

Best Solution

The basic idea is to call duplicate() on ByteBuffer, which will create a new ByteBuffer that shares the underlying storage but allows you to start from a different location.

This worked for me:

FloatBuffer verticesNormals;
// ... code to initialize verticesNormals ...
// verticesNormals contains 6 floats for each vertex. The first three
// define the position and the next three define the normal.

gl.glVertexPointer(3, gl.GL_FLOAT, 24, verticesNormals);

// Create a buffer that points 3 floats past the beginning.
FloatBuffer normalData = mVerticesNormals.duplicate();
normalData.position(3);

gl.glNormalPointer(gl.GL_FLOAT, 24, normalData);

Related Problems and Solutions