2
我花了几乎整整一天的时间尝试使用opengl 1.1和顶点缓冲区渲染简单的多边形,但没有运气。我搜索和搜索,但我没有找到太多。如何在android和opengl中使用顶点缓冲区1.1
这是我到目前为止有:
public class Polygon {
int bufferId = 0;
private FloatBuffer vertexBuffer; // Buffer for vertex-array
private float[] vertices = { // Vertices for the square
-1.0f, -1.0f, 0.0f, // 0. left-bottom
1.0f, -1.0f, 0.0f, // 1. right-bottom
-1.0f, 1.0f, 0.0f, // 2. left-top
1.0f, 1.0f, 0.0f // 3. right-top
};
private ByteBuffer indexBuffer;
private byte[] indices = {0, 1, 2, 3}; // Indices to above vertices (in CCW)
// Constructor - Setup the vertex buffer
public Polygon() {
// Setup vertex array buffer. Vertices in float. A float has 4 bytes
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder()); // Use native byte order
vertexBuffer = vbb.asFloatBuffer(); // Convert from byte to float
vertexBuffer.put(vertices); // Copy data into buffer
vertexBuffer.position(0); // Rewind
indexBuffer = ByteBuffer.allocateDirect(indices.length);
indexBuffer.put(indices);
indexBuffer.position(0);
int[] buffers = new int[1];
GLES11.glGenBuffers(1, buffers, 0);
bufferId = buffers[0];
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, bufferId);
GLES11.glBufferData(GLES11.GL_ARRAY_BUFFER, vertices.length, vertexBuffer, GLES11.GL_STATIC_DRAW);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
}
// Render the shape
public void draw(GL10 gl) {
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, bufferId);
GLES11.glEnableClientState(GL10.GL_VERTEX_ARRAY);
GLES11.glVertexPointer(3, GLES11.GL_FLOAT, 0, 0);
GLES11.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length);
GLES11.glDisableClientState(GL10.GL_VERTEX_ARRAY);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
}
}
它不会呈现任何东西,还有的是Android logcat中没有相关的错误。 我忘了其余的代码。问题显然在这个班,因为它工作正常,当我改变绘制方法,这:
public void draw(GL10 gl) {
GLES11.glEnableClientState(GL10.GL_VERTEX_ARRAY);
GLES11.glVertexPointer(3, GLES11.GL_FLOAT, 0, vertexBuffer);
GLES11.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length);
GLES11.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
所以,我做错了什么?
蒂姆,谢谢你的回答。我不确定什么是正确的价值,但我试图把vertices.length/3之前,现在再次肯定,不幸的是,它使用顶点缓冲区时不起作用。 – beegor 2012-07-23 15:15:04
我找到了。问题出在glBufferData调用中。缓冲区大小参数错误。我将顶点数乘以4(因为float具有4个字节),现在它起作用了!接受蒂姆的回答,因为它让我找到了解决方案。 – beegor 2012-07-23 15:50:19