Saturday, November 12, 2011

IllegalArgumentException: Must use a native order direct Buffer

Today I was playing around a little bit with opengl and android. Using android version 1.5 it was working fine. However, I wanted to use a higher android version and set it to at least 2.1. But doing that - unfortunately - my code's execution always failed with an IllegalArgumentException: Must use a native order direct Buffer.
After tracking down the code, I found the parts that were causing this exception:

cubeVertexBfr = new FloatBuffer[6];
cubeNormalBfr = new FloatBuffer[6];
cubeTextureBfr = new FloatBuffer[6];
for(int i = 0; i < 6; i++)
{
  cubeVertexBfr[i] = FloatBuffer.wrap(cubeVertexCoords[i]);
  cubeNormalBfr[i] = FloatBuffer.wrap(cubeNormalCoords[i]);
  cubeTextureBfr[i] = FloatBuffer.wrap(cubeTextureCoords[i]);
}

After changing this part (which I found here) with an direct buffer to:

int SIZEOF_FLOAT = Float.SIZE / 8;
 
cubeVertexBfr = new FloatBuffer[6];
cubeNormalBfr = new FloatBuffer[6];
cubeTextureBfr = new FloatBuffer[6];
for (int i = 0; i < 6; i++) {
  ByteBuffer vbb = ByteBuffer.allocateDirect(4 * 3 * SIZEOF_FLOAT);
  vbb.order(ByteOrder.nativeOrder());
  cubeVertexBfr[i] = vbb.asFloatBuffer();
  cubeVertexBfr[i].put(cubeVertexCoords[i]);
  cubeVertexBfr[i].flip();
 
  ByteBuffer nbb = ByteBuffer.allocateDirect(4 * 3 * SIZEOF_FLOAT);
  nbb.order(ByteOrder.nativeOrder());
  cubeNormalBfr[i] = nbb.asFloatBuffer();
  cubeNormalBfr[i].put(cubeNormalCoords[i]);
  cubeNormalBfr[i].flip();
 
  ByteBuffer tbb = ByteBuffer.allocateDirect(4 * 2 * SIZEOF_FLOAT);
  tbb.order(ByteOrder.nativeOrder());
  cubeTextureBfr[i] = tbb.asFloatBuffer();
  cubeTextureBfr[i].put(cubeTextureCoords[i]);
  cubeTextureBfr[i].flip();
}

it worked again on android 2.1 and higher.
Give it a try!

1 comment: