1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
instanceVBOProvider.nextFrame(); //Ensures buffers aren't reused until 6 frames have passed

renderShader.bind();
renderShader.uploadMatrices(camera);
for(int i = 0; i < numMeshes; i++){

	Mesh mesh = meshes[i];

	renderShader.uploadMaterial(mesh.getMaterial());

	glBindVertexArray(mesh.getVAO()); //All vertex attributes bound and enabled

	MappedVBO vbo = instanceVBOProvider.nextBuffer(); //Gets/allocates a buffer
	vbo.bind();

	InstancePositionData instanceData = mesh.getInstanceData();
	vbo.ensureCapacity(instanceData); //Reallocates the buffer if it's too small
	ByteBuffer buffer = vbo.map();
	buffer.put(instanceData);
	vbo.unmap();

        //We use a different VBO for each draw call so we need to change the pointer every time
	glVertexAttribPointer(instancePositionLocation, 3, GL_UNSIGNED_SHORT, false, 8, 0);
		
	glDrawElementsInstanced(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, 0, numInstances);

        glBindVertexArray(0);
}