ByteBuffer in android opengl es

First we need to understand two concepts:

1. The JAVA code of the Android application layer does not run on the hardware, but runs on the Dalvik virtual machine. The code running on the virtual machine cannot directly access the local environment.

2.opengl as a local system library, running in the local environment.

The code running environment of the android application layer is different from that of opengl. So how do they communicate? There are two techniques. The first is to use NDK. When we call OpenGL functions on Android, we are actually using NDK to call opengl in the local system library, but these are all encapsulated. The second technique is to change the way memory is allocated. JAVA has a special set of classes that can allocate memory blocks in the local environment and copy JAVA data into the memory of the local environment.

Let's talk about the second technical solution here. A grand introduction to ByteBuffer, yes, that is it, as well as its siblings FloatBuffer, DoubleBuffer and other classes, the objects of these classes are obtained through several functions such as asFloatBuffer(), asDoubleBuffer() of ByteBuffer, and they use ByteBuffer memory allocated by allocateDirect. Here is an example.

        float[] point = {5, 5};//Define a vertex of type float

        int bytesPerFloat = 4; //Each float data occupies four bytes

        //The total number of bytes occupied by a float type vertex
        int byteSize = point.length * bytesPerFloat;
        
        //Allocate the memory of the local environment, this memory will not be recycled by the garbage collection mechanism
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(byteSize) ;
        
        //Organize content according to native byte order
        byteBuffer.order(ByteOrder.nativeOrder());
        
        //We don't want to operate on individual bytes, we want to operate on floating point numbers
        FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
        
        //put dalvik The memory in the virtual machine is copied to the local environment memory
        floatBuffer.put(point);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325442975&siteId=291194637