{
const height = 500;
const vsSource = `
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec4 a_color;
uniform mat4 u_matrix;
varying vec4 v_color;
varying vec4 v_normal;
void main() {
gl_Position = u_matrix * vec4(a_position, 1);
v_color = a_color;
v_normal = u_matrix * vec4(a_normal, 0.5);
}
`
const fsSource = `
precision mediump float;
varying vec4 v_color;
varying vec4 v_normal;
void main() {
gl_FragColor = vec4(
v_color.x + ((v_normal.x - v_color.x) * 0.1),
v_color.y + ((v_normal.y - v_color.y) * 0.1),
v_color.z + ((v_normal.z - v_color.z) * 0.1),
1
);
}
`
const {canvas, gl, shaderProgram, passDataToShader } = webGlCanvasBoilerplate(width, 500, vsSource, fsSource);
const matrixLocation = gl.getUniformLocation(shaderProgram, "u_matrix");
//baseRgb.map((channel, i) => Math.round(channel + (tintRgb[i] - channel) * tintAmount));
// ATTRIBUTES
// triangle positions and normals
const cubePositions = [];
const cubeVertexNormals = [];
// go through all 12 faces of the cube (6 sides à 2 triangles)
cubeFaces.forEach(face => {
// each face (triangle) has three numbers (positions in the cubeVertex array)
const [v1, v2, v3] = face.map(i => cubeVertices[i]);
const faceNormal = normalize(cross(subtractVectors(v1, v2), subtractVectors(v3, v2)));
// get the vertices of the face
face.forEach(vertexNumber => {
// unspread the coordinates of the vertex and push into cubePositions array
cubePositions.push(...cubeVertices[vertexNumber]);
// unspread the coordinates of the normal and push into cubeVertexNormals array (same for each
// vertex of a face)
cubeVertexNormals.push(...faceNormal);
});
});
console.log(cubePositions, cubeVertexNormals);
passDataToShader("a_position", cubePositions, 3)
passDataToShader("a_normal", cubeVertexNormals, 3)
// colors
const colors = _.flatten(
_.times(cubePositions.length / 3, num => [0.3, 0.7, 0.5, 1])
);
passDataToShader("a_color", colors, 4)
// variable initialization
let translation = [];
let matrix = [];
// animation
const drawScene = () => {
const time = Date.now() / 2500;
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//gl.enable(gl.CULL_FACE);
gl.enable(gl.DEPTH_TEST);
let matrix = m4.projection(width, height, height);
matrix = m4Helpers.translate(matrix, width / 2, height / 2, 100);
matrix = m4Helpers.xRotate(matrix, degreesToRadians(time * 90));
matrix = m4Helpers.yRotate(matrix, degreesToRadians(time * 45));
matrix = m4Helpers.scale(matrix, width / 4, width / 4, width / 4);
//console.log(matrix);
gl.uniformMatrix4fv(matrixLocation, false, matrix);
// draw
gl.drawArrays(
gl.TRIANGLES,
0, // offset
cubePositions.length / 3 // total count of vertices
);
}
while (true) {
drawScene();
yield canvas;
}
}