UNPKG

1.81 kBPlain TextView Raw
1import assert from 'assert';
2
3import type {StructArray} from '../util/struct_array';
4import type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type';
5import type Context from '../gl/context';
6
7class IndexBuffer {
8 context: Context;
9 buffer: WebGLBuffer;
10 dynamicDraw: boolean;
11
12 constructor(context: Context, array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean) {
13 this.context = context;
14 const gl = context.gl;
15 this.buffer = gl.createBuffer();
16 this.dynamicDraw = Boolean(dynamicDraw);
17
18 // The bound index buffer is part of vertex array object state. We don't want to
19 // modify whatever VAO happens to be currently bound, so make sure the default
20 // vertex array provided by the context is bound instead.
21 this.context.unbindVAO();
22
23 context.bindElementBuffer.set(this.buffer);
24 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);
25
26 if (!this.dynamicDraw) {
27 delete array.arrayBuffer;
28 }
29 }
30
31 bind() {
32 this.context.bindElementBuffer.set(this.buffer);
33 }
34
35 updateData(array: StructArray) {
36 const gl = this.context.gl;
37 assert(this.dynamicDraw);
38 // The right VAO will get this buffer re-bound later in VertexArrayObject#bind
39 // See https://github.com/mapbox/mapbox-gl-js/issues/5620
40 this.context.unbindVAO();
41 this.bind();
42 gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer);
43 }
44
45 destroy() {
46 const gl = this.context.gl;
47 if (this.buffer) {
48 gl.deleteBuffer(this.buffer);
49 delete this.buffer;
50 }
51 }
52}
53
54export default IndexBuffer;