FloatBuffer.put导致崩溃?

时间:2012-03-26 18:31:20

标签: android opengl-es

我有一个非常简单的几何图形,可以制作一些矩形。由于某种原因浮动缓冲区的put方法崩溃了手机。代码如下

private FloatBuffer mFloatVertexBuffer;
public Bars(int numberOf,float widthIn,float heightIn, GL10 gl)
{
    width=widthIn;height=heightIn;

    mCoordinateType= GL10.GL_FLOAT;
    mCoordinateSize = 4;//FLOAT_SIZE =4 ;
    mFloatVertexBuffer = ByteBuffer.allocateDirect(mCoordinateSize * numberOf * 3).order(ByteOrder.nativeOrder()).asFloatBuffer();
    mVertexBuffer = mFloatVertexBuffer;

    mIndexCount = 6 * numberOf;
    final int CHAR_SIZE = 2;
    mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * mIndexCount).order(ByteOrder.nativeOrder()).asCharBuffer();

    for (int i = 0, j = 0; i < numberOf; i++)
    {
        char a = (char) (j++); char b = (char) (j++);
        char c = (char) (j++);char d = (char) (j++);

        mIndexBuffer.put(a);mIndexBuffer.put(b); mIndexBuffer.put(c);
        mIndexBuffer.put(b); mIndexBuffer.put(c);mIndexBuffer.put(d);
    }
    float stride = widthIn/numberOf;
    for (int i = 0, j = 0; i < numberOf; i++)
    {
        float z = 0;
        float height=  heightIn*((float) Math.random());
        float ax = stride*(i+0);
        float ay = 0;
        float dx = stride*(i+1);
        float dy = 0;
        float bx = stride*(i+0);
        float by = height;
        float cx= stride*(i+1);
        float cy = height;

        mFloatVertexBuffer.put(j++,ax);
        mFloatVertexBuffer.put(j++,ay);
        mFloatVertexBuffer.put(j++,z);

        mFloatVertexBuffer.put(j++,bx);
        mFloatVertexBuffer.put(j++,by);
        mFloatVertexBuffer.put(j++,z);//Still Working

        mFloatVertexBuffer.put(j++,cx);//Throws error at this line (via debugger)
        mFloatVertexBuffer.put(j++,cy);
        mFloatVertexBuffer.put(j++,z);

        mFloatVertexBuffer.put(j++,dx);
        mFloatVertexBuffer.put(j++,dy);
        mFloatVertexBuffer.put(j++,z);
    }

1 个答案:

答案 0 :(得分:3)

mFloatVertexBuffer = ByteBuffer.allocateDirect(mCoordinateSize * numberOf * 3).order(ByteOrder.nativeOrder()).asFloatBuffer();

分配(4 * numberOf * 3)个字节,但是你需要(4 * numberOf * 4 * 3)个字节,因为你想为每个numberOf项存储12个4号浮点数。