Search code examples
androidallocationmeshrenderscript

An Allocation variable is set before it gains any data


After flipping throw the Grass Live Wallpaper, I have come around this bit of code - it creates the grass blade mesh and sets it indices:

private void createMesh() {
    mVertexBuffer = new ScriptField_Vertex(mRS, mVerticies * 2);

    final Mesh.AllocationBuilder meshBuilder = new Mesh.AllocationBuilder(mRS);
    meshBuilder.addVertexAllocation(mVertexBuffer.getAllocation());

    mBladesIndicies = Allocation.createSized(mRS, Element.U16(mRS), mIndicies);
    meshBuilder.addIndexSetAllocation(mBladesIndicies, Primitive.TRIANGLE);

    mBladesMesh = meshBuilder.create();

    short[] idx = new short[mIndicies];
    int idxIdx = 0;
    int vtxIdx = 0;
    for (int i = 0; i < mBladeSizes.length; i++) {
        for (int ct = 0; ct < mBladeSizes[i]; ct ++) {
            idx[idxIdx + 0] = (short)(vtxIdx + 0);
            idx[idxIdx + 1] = (short)(vtxIdx + 1);
            idx[idxIdx + 2] = (short)(vtxIdx + 2);
            idx[idxIdx + 3] = (short)(vtxIdx + 1);
            idx[idxIdx + 4] = (short)(vtxIdx + 3);
            idx[idxIdx + 5] = (short)(vtxIdx + 2);
            idxIdx += 6;
            vtxIdx += 2;
        }
        vtxIdx += 2;
    }

    mBladesIndicies.copyFrom(idx);
}

I am puzzled by this 2 lines: meshBuilder.addIndexSetAllocation(mBladesIndicies, Primitive.TRIANGLE); and mBladesIndicies.copyFrom(idx); Why do they send themBladesIndicies to the mesh builder and create the mesh, before the mBladesIndicies variable actually got he's data at mBladesIndicies.copyFrom(idx);

In short - why meshBuilder.addIndexSetAllocation(mBladesIndicies, Primitive.TRIANGLE); and mBladesMesh = meshBuilder.create(); come BEFORE mBladesIndicies.copyFrom(idx); ?


Solution

  • The Allocation is connected to the Mesh by a reference and not a copy. Because of this the order in which the data is added does not matter.

    The Mesh.Builder does retain the allocation references after creation.