File size: 1,658 Bytes
c0dce6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
export default class Mesh {

    /**
     * The parent MiniGL controller.
     *
     * @type {MiniGL}
     * @private
     */
    gl;

    wireframe = false;
    attributeInstances = [];

    /**
     * @param {MiniGL} minigl
     * @param geometry
     * @param material
     * @param {object} properties
     */
    constructor(minigl, geometry, material, properties = {}) {

        // Add additional properties.
        Object.assign(this, properties);

        // Set required properties.
        this.geometry = geometry;
        this.material = material;
        this.gl = minigl;

        // Build `attributeInstances` array.
        Object.entries(this.geometry.attributes).forEach(([e, attribute]) => {
            this.attributeInstances.push({
                attribute: attribute,
                location: attribute.attach(e, this.material.program)
            });
        });

        // Add mesh to MiniGL controller.
        this.gl.meshes.push(this);
    }


    draw() {
        const context = this.gl.getContext();

        context.useProgram(this.material.program);

        this.material.uniformInstances.forEach(({uniform: uniform, location: location}) => {
            uniform.update(location);
        });

        this.attributeInstances.forEach(({attribute: attribute, location: location}) => {
            attribute.use(location);
        });

        const mode = this.wireframe ? context.LINES : context.TRIANGLES;

        context.drawElements(mode, this.geometry.attributes.index.values.length, context.UNSIGNED_SHORT, 0);
    }

    remove() {
        this.gl.meshes = this.gl.meshes.filter(mesh => mesh != this);
    }

}