{
let shaderv = gl.createShader(gl.VERTEX_SHADER);
let shaderf = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(shaderv, vertex_shader);
gl.compileShader(shaderv);
if (!gl.getShaderParameter(shaderv, gl.COMPILE_STATUS)) {
throw gl.getShaderInfoLog(shaderv);
}
gl.shaderSource(shaderf, fragment_shader);
gl.compileShader(shaderf);
if (!gl.getShaderParameter(shaderf, gl.COMPILE_STATUS)) {
throw gl.getShaderInfoLog(shaderf);
}
let shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, shaderv);
gl.attachShader(shaderProgram, shaderf);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
throw "Could not initialise shaders";
}
gl.useProgram(shaderProgram);
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
// Init buffers
let squareVertexBuffer;
let vertices = [];
squareVertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexBuffer);
// below is how you interleave positions and colors into a single array and then VBO
vertices.push(-.5); vertices.push(-.5); vertices.push(0.0); // v1 positions
vertices.push(1.0); vertices.push(0.0); vertices.push(0.0); // v1 colors
vertices.push(.5); vertices.push(.5); vertices.push(0.0); // v2 positions
vertices.push(0.0); vertices.push(0.0); vertices.push(1.0); // v2 colors
vertices.push(-.5); vertices.push(.5); vertices.push(0.0); // v3 positions
vertices.push(0.0); vertices.push(0.0); vertices.push(0.0); // v3 colors
vertices.push(-.5); vertices.push(-.5); vertices.push(0.0); // v4 positions
vertices.push(1.0); vertices.push(0.0); vertices.push(0.0); // v4 colors
vertices.push(.5); vertices.push(-.5); vertices.push(0.0); // v5 positions
vertices.push(0.0); vertices.push(1.0); vertices.push(0.0); // v5 colors
vertices.push(.5); vertices.push(.5); vertices.push(0.0); // v6 positions
vertices.push(0.0); vertices.push(0.0); vertices.push(1.0); // v6 colors
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); // use 4 bytes float
squareVertexBuffer.numFloats = 3; // three floats per vertex
squareVertexBuffer.numVertices = 6; // number of vertices in the buffer
gl.viewport(0, 0, width, height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
let offset = 0, stride = 2 * 3 * 4 // 4 is the size of a float in bytes
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, squareVertexBuffer.numFloats, gl.FLOAT, false, stride, offset);
offset = 3 * 4 // 4 is the size of a float in bytes
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, squareVertexBuffer.numFloats, gl.FLOAT, false, stride, offset);
offset = 0;
gl.drawArrays(gl.TRIANGLES, offset, squareVertexBuffer.numVertices);
return "OK"
}