Game Development Reference
In-Depth Information
the
Vertices
instance used to render the batch. It also stores the indices that we'll define in a
minute. The member
numSprites
holds the number drawn so far in the current batch.
public
SpriteBatcher(GLGraphics glGraphics,
int
maxSprites) {
this
.verticesBuffer =
new float
[maxSprites*4*4];
this
.vertices =
new
Vertices(glGraphics, maxSprites*4, maxSprites*6,
false
,
true
);
this
.bufferIndex = 0;
this
.numSprites = 0;
short
[] indices =
new short
[maxSprites*6];
int
len = indices.length;
short
j = 0;
for
(
int
i = 0; i < len; i += 6, j += 4) {
indices[i + 0] = (
short
)(j + 0);
indices[i + 1] = (
short
)(j + 1);
indices[i + 2] = (
short
)(j + 2);
indices[i + 3] = (
short
)(j + 2);
indices[i + 4] = (
short
)(j + 3);
indices[i + 5] = (
short
)(j + 0);
}
vertices.setIndices(indices, 0, indices.length);
}
Moving to the constructor, we have two arguments: the
GLGraphics
instance we need for
creating the
Vertices
instance, and the maximum number of sprites the batcher should be able
to render in one batch. The first thing we do in the constructor is create the float array. We have
four vertices per sprite, and each vertex takes up four floats (two for the x and y coordinates and
another two for the texture coordinates). We can have
maxSprites
sprites maximally, so that's
4 × 4 ×
maxSprites
floats that we need for the buffer.
Next, we create the
Vertices
instance. We need it to store
maxSprites
× 4 vertices and
maxSprites
× 6 indices. We tell the
Vertices
instance that we have not only positional attributes,
but also texture coordinates for each vertex. We then initialize the
bufferIndex
and
numSprites
members to zero. We create the indices for our
Vertices
instance. We need to do this only once,
as the indices will never change. The first sprite in a batch will always have the indices 0, 1, 2,
2, 3, 0; the next sprite will have 4, 5, 6, 6, 7, 4; and so on. We can precompute these and store
them in the
Vertices
instance. This way, we only need to set them once, instead of once for
each sprite.
public void
beginBatch(Texture texture) {
texture.bind();
numSprites = 0;
bufferIndex = 0;
}
Next up is the
beginBatch()
method. It binds the texture and resets the
numSprites
and
bufferIndex
members so that the first sprite's vertices will get inserted at the front of the
verticesBuffer
float array.
public void
endBatch() {
vertices.setVertices(verticesBuffer, 0, bufferIndex);
vertices.bind();