Android/OpenglES2/examples: 为什么使用 ByteBuffer 作为坐标?

Android/OpenglES2/examples: Why use ByteBuffer for coords?

朋友们,你们好,

总的来说,我是 Android 和 Java 的新手,对于菜鸟问题​​,我深表歉意。 我遇到了标准的 OpenGl ES 示例并试图理解这段代码:

static float wallCoords[] = {
        // in counterclockwise order:
        -0.5f,  0.6f, 0.0f,   // top left
        -0.5f,  0.5f, 0.0f,   // bottom left
        0.5f,   0.5f, 0.0f,   // bottom right
        0.5f,   0.6f, 0.0f,   // top right
};
private final int vertexCount = wallCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex

float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 0.0f };

private final FloatBuffer vertexBuffer;
private final ShortBuffer drawListBuffer;
private final short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices

...

ByteBuffer bb = ByteBuffer.allocateDirect(
        // (number of coordinate values * 4 bytes per float)
            wallCoords.length * 4);
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
// create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer();
// add the coordinates to the FloatBuffer
vertexBuffer.put(wallCoords);
// set the buffer to read the first coordinate
vertexBuffer.position(0);

所以我的问题是为什么不使用 FloatBuffer.wrap() 方法,例如:

vertexBuffer = FloatBuffer.wrap(wallCoords);

谢谢!

这是出于性能原因。

FloatBuffer 没有分配 direct buffer:

allocateDirect 方法

Direct vs. non-direct buffers

A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations.

A direct byte buffer may be created by invoking the allocateDirect factory method of this class. The buffers returned by this method typically have somewhat higher allocation and deallocation costs than non-direct buffers.

事实上 FloatBuffer.wrap 将数组和缓冲区紧密联系起来

The new buffer will be backed by the given float array; that is, modifications to the buffer will cause the array to be modified and vice versa.

以可能复制数据为代价。