Game Development Reference
In-Depth Information
A Small NIO Buffer Digression
To be totally exact, we need to use direct NIO buffers. This means that the memory is not
allocated in the virtual machine's heap memory, but in native heap memory. To construct such a
direct NIO buffer, we can use the following code snippet:
ByteBuffer buffer = ByteBuffer.allocateDirect(NUMBER_OF_BYTES);
buffer.order(ByteOrder.nativeOrder());
This will allocate a ByteBuffer that can hold NUMBER_OF_BYTES bytes in total, and it will make sure
that the byte order is equal to the byte order used by the underlying CPU. An NIO buffer has
three attributes.
ï?®
Capacity: The number of elements the buffer can hold in total.
ï?®
Position: The current position to which the next element would be written or
read from.
ï?®
Limit: The index of the last element that has been defined, plus one.
The capacity of a buffer is its actual size. In the case of a ByteBuffer , it is given in bytes. The
position and limit attributes can be thought of as defining a segment within the buffer starting at
position and ending at limit (exclusive).
Since we want to specify our vertices as floats, it would be nice not to have to cope with bytes.
Luckily, we can convert the ByteBuffer instance to a FloatBuffer instance, which allows us to
do just that: work with floats.
FloatBuffer floatBuffer = buffer.asFloatBuffer();
Capacity, position, and limit are given in floats in the case of a FloatBuffer . Our usage pattern of
these buffers will be pretty limited—it goes like this:
float[] vertices = { ... definitions of vertex positions etc. ... };
floatBuffer.clear();
floatBuffer.put(vertices);
floatBuffer.flip();
We first define our data in a standard Java float array. Before we put that float array into the
buffer, we tell the buffer to clear itself via the clear() method. This doesn't actually erase any
data, but it sets the position to 0 and the limit to the capacity. Next, we use the FloatBuffer.
put(float[] array) method to copy the content of the complete array to the buffer, beginning
at the buffer's current position. After the copying, the position of the buffer will be increased by
the length of the array. Next, the call to the put() method appends the additional data to the
data of the last array we copied to the buffer. The final call to FloatBuffer.flip() just swaps the
position and limit.
For this example, let's assume that our vertices array is five floats in size and that our
FloatBuffer has enough capacity to store those five floats. After the call to FloatBuffer.put() ,
the position of the buffer will be 5 (indices 0 to 4 are taken up by the five floats from our array).
The limit will still be equal to the capacity of the buffer. After the call to FloatBuffer.flip() , the
position will be set to 0 and the limit will be set to 5. Any party interested in reading the data
 
Search WWH ::




Custom Search