Game Development Reference
In-Depth Information
this
.hasTexCoords = hasTexCoords;
this
.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
ByteBuffer buffer = ByteBuffer.
allocateDirect
(maxVertices * vertexSize);
buffer.order(ByteOrder.
nativeOrder
());
vertices = buffer.asFloatBuffer();
if
if(maxIndices > 0) {
buffer = ByteBuffer.
allocateDirect
(maxIndices * Short.
SIZE
/ 8);
buffer.order(ByteOrder.
nativeOrder
());
indices = buffer.asShortBuffer();
}
else
{
indices =
null
;
}
}
In the constructor, we specify how many vertices and indices our
Vertices
instance can
hold maximally, as well as whether the vertices have colors or texture coordinates. Inside the
constructor, we then set the members accordingly and instantiate the buffers. Note that the
ShortBuffer
will be set to
null
if
maxIndices
is 0. Our rendering will be performed nonindexed in
that case.
public void
setVertices(
float
[] vertices,
int
offset,
int
length) {
this
.vertices.clear();
this
.vertices.put(vertices, offset, length);
this
.vertices.flip();
}
public void
setIndices(
short
[] indices,
int
offset,
int
length) {
this
.indices.clear();
this
.indices.put(indices, offset, length);
this
.indices.flip();
}
Next up are the
setVertices()
and
setIndices()
methods. The latter will throw a
NullPointerException
in case the
Vertices
instance does not store indices. All we do is clear
the buffers and copy the contents of the arrays.
public void
draw(
int
primitiveType,
int
offset,
int
numVertices) {
GL10 gl = glGraphics.getGL();
gl.glEnableClientState(GL10.
GL_VERTEX_ARRAY
);
vertices.position(0);
gl.glVertexPointer(2, GL10.
GL_FLOAT
, vertexSize, vertices);
if
if(hasColor) {
gl.glEnableClientState(GL10.
GL_COLOR_ARRAY
);
vertices.position(2);
gl.glColorPointer(4, GL10.
GL_FLOAT
, vertexSize, vertices);
}