简体   繁体   中英

Pass array of Java vertex objects to OpenGL entry points

I am starting to port my games over to Android from iOS and I've run into a problem.

In my standard workflow on iOS I would store my vertex info in an array of structs:

typedef struct{
    float x, y, z;
} Vector3;

Vector3 verts[];

That sort of thing.

Then when it came time to send my vertex data to GL, I would just point to the verts array and it would treat it like an array of floats.

glVertexAttribPointer(Vertex_POSITION, 3, GL_FLOAT, 0, 0, (void *)verts);

How do I do this in Java?

I tried making a Vector3 class and putting a few of them into an array, but it throws an error when I try to stuff that array into GL.

With the direction you are going, I don't think this can work directly. When you have an array of objects in Java (like an array of your Vector3 class ), the array contains a sequence of references to those objects, and each object is allocated in a separate chunk of memory.

What you need to pass to OpenGL entry points like glVertexAttribPointer() or glBufferData() is a contiguous block of memory containing the data. An array of objects does not have that layout, so it's simply not possible to use it directly.

You have various options:

  • Don't use arrays of objects to store your data. Instead, use a data structure that stores the data in a contiguous block of memory. For float values, this can be a float[] , or a FloatBuffer . The Java entry points in Android take buffers as arguments, so using buffers is the most straightforward approach. You should be able to find plenty of examples in Android OpenGL examples.
  • Copy the data to temporary buffers before making the API calls. This is obviously not very appealing, since extra data copies cause unproductive overhead.
  • Write your OpenGL code in C++, and compile it with the NDK. This might also save you a lot of work if you're porting C++ code from another platform. If you intermixed the OpenGL code with Objective-C on iOS, it will still take work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM