1 | import assert from 'assert';
|
2 |
|
3 | import type {StructArray} from '../util/struct_array';
|
4 | import type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type';
|
5 | import type Context from '../gl/context';
|
6 |
|
7 | class 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 |
|
19 |
|
20 |
|
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 |
|
39 |
|
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 |
|
54 | export default IndexBuffer;
|