gl-sprite-batch
Version:
a high level quad batcher for stackgl
79 lines (65 loc) • 2.33 kB
JavaScript
var createVAO = require('gl-aliased-vao') //TODO: improve this with gl-vao
var createBuffer = require('gl-buffer')
module.exports.floatsPerVertex = 5
function createIndices(capacity) {
var numIndices = capacity * 6
var indices = new Uint16Array(numIndices)
for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
indices[i + 0] = j + 0
indices[i + 1] = j + 1
indices[i + 2] = j + 2
indices[i + 3] = j + 0
indices[i + 4] = j + 2
indices[i + 5] = j + 3
}
return indices
}
module.exports.mixins = {
create: function create(opt) {
opt = opt||{}
this.clear()
//dispose before building...
if (this.vao)
this.dispose()
var capacity = typeof opt.capacity === 'number' ? opt.capacity : 100
// 65535 is max index, so 65535 / 6 = 10922.
if (capacity > 10922)
throw new Error("Can't have more than 10922 quads per batch: " + capacity)
this._capacity = capacity
//the total number of floats in our batch
var numVerts = capacity * 4 * module.exports.floatsPerVertex
this.vertices = new Float32Array(numVerts)
this.indices = createIndices(capacity)
var gl = this.gl
var usage = opt.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW
this.vertexBuffer = createBuffer(gl, this.vertices, gl.ARRAY_BUFFER, usage)
this.indexBuffer = createBuffer(gl, this.indices, gl.ELEMENT_ARRAY_BUFFER, gl.STATIC_DRAW)
var stride = 5 * 4
this.vao = createVAO(gl, [{ //position XY
name: 'position',
buffer: this.vertexBuffer,
size: 2,
stride: stride
}, { //texcoord UV
name: 'texcoord0',
buffer: this.vertexBuffer,
size: 2,
offset: 2 * 4,
stride: stride
}, { //color (packed) C
name: 'color',
buffer: this.vertexBuffer,
size: 4,
stride: stride,
offset: 4 * 4,
type: gl.UNSIGNED_BYTE,
normalized: true
}], this.indexBuffer)
return this
},
ensureCapacity: function(capacity) {
if (this.capacity < capacity)
this.create({ capacity: capacity })
return this
}
}