Search code examples
androidopengl-esopengl-es-2.0bytebufferfloatbuffer

OpenGL ES Android Confusion


I am learning OpenGL ES for Android through this website: http://www.learnopengles.com/android-lesson-one-getting-started/

There are a couple of things I don't understand...

What exactly do this code do:

mTriangle1Vertices = ByteBuffer.allocateDirect(triangle1VerticesData.length * mBytesPerFloat)
    .order(ByteOrder.nativeOrder()).asFloatBuffer();
    mTriangle2Vertices = ByteBuffer.allocateDirect(triangle2VerticesData.length * mBytesPerFloat)
    .order(ByteOrder.nativeOrder()).asFloatBuffer();
    mTriangle3Vertices = ByteBuffer.allocateDirect(triangle3VerticesData.length * mBytesPerFloat)
    .order(ByteOrder.nativeOrder()).asFloatBuffer();

    mTriangle1Vertices.put(triangle1VerticesData).position(0);
    mTriangle2Vertices.put(triangle2VerticesData).position(0);
    mTriangle3Vertices.put(triangle3VerticesData).position(0);

What are these "buffer" things and are there always four bytes to a float? I'm not really sure why the code above is needed. The author explained it, but I'm not sure what he means.

Thanks!


Solution

  • Why do we even need to do this at all?

    If we were coding in C, we wouldn't need the above code -- we'd just skip the whole ByteBuffer.allocateDirect stuff and pass a pointer to our array when we call drawArrays or drawElements. However, we can't do that because Dalvik, the Java virtual machine running inside Android, has a garbage collector, and it might move the data around on us. It might even scrap the memory, erroneously thinking that we don't need it anymore. The safe way to do it is to use ByteBuffer.allocateDirect to create a block of memory in native memory, copy the data to that, and then OpenGL can use that directly without us having to worry about the virtual machine.

    Each buffer needs to be big enough to hold the data we're going to copy; when we create the buffer, it wants a size in bytes. Our Java array is made of floats, so to figure out the size in bytes, we pass the array length and multiply it by 4. A floating point value is a 32-bit, and a byte is an 8-bit value, so there are always 4 bytes to a float.

    Hope this helps out. :)