Using WebGL, draw a 3D solved rubix cube
- User
Using WebGL, draw a 3D solved rubix cube
- Assistant
Using WebGL, draw a 3D solved rubix cube
Certainly! Let's create a 3D solved Rubik's Cube using WebGL. We'll render 27 smaller cubes (called "cubies") arranged in a 3x3x3 grid to form the Rubik's Cube. We'll assign colors to each face to represent the solved state.
Create an HTML file named rubiks_cube.html with the following content:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebGL Rubik's Cube</title>
<style>
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
</style>
</head>
<body>
<!-- Canvas for WebGL -->
<canvas id="glcanvas"></canvas>
<!-- Include glMatrix library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"></script>
<!-- Your JavaScript code -->
<script src="rubiks_cube.js"></script>
</body>
</html>
Create a JavaScript file named rubiks_cube.js:
// Get the canvas element
const canvas = document.getElementById('glcanvas');
// Initialize the GL context
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
// Only continue if WebGL is available and working
if (!gl) {
alert('Unable to initialize WebGL. Your browser or machine may not support it.');
}
Vertex Shader Source Code (vsSource):
const vsSource = `
attribute vec4 aPosition;
attribute vec4 aColor;
uniform mat4 uMatrix;
varying lowp vec4 vColor;
void main(void) {
gl_Position = uMatrix * aPosition;
vColor = aColor;
}
`;
Fragment Shader Source Code (fsSource):
const fsSource = `
varying lowp vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
`;
Shader Setup Functions:
// Compile shader from source code
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
// Check for errors
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
// Initialize shader program
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// Check for errors
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
// Initialize shaders
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
Program Info:
const programInfo = {
program: shaderProgram,
attribLocations: {
position: gl.getAttribLocation(shaderProgram, 'aPosition'),
color: gl.getAttribLocation(shaderProgram, 'aColor'),
},
uniformLocations: {
matrix: gl.getUniformLocation(shaderProgram, 'uMatrix'),
},
};
Create a Function to Generate Cubie Buffers:
function createCubieBuffers(gl, colors) {
// Cube vertices
const positions = [
// Front face
-0.5, -0.5, 0.5, // 0
0.5, -0.5, 0.5, // 1
0.5, 0.5, 0.5, // 2
-0.5, 0.5, 0.5, // 3
// Back face
-0.5, -0.5, -0.5, // 4
0.5, -0.5, -0.5, // 5
0.5, 0.5, -0.5, // 6
-0.5, 0.5, -0.5, // 7
];
// Element indices
const indices = [
0, 1, 2, 0, 2, 3, // Front
1, 5, 6, 1, 6, 2, // Right
5, 4, 7, 5, 7, 6, // Back
4, 0, 3, 4, 3, 7, // Left
3, 2, 6, 3, 6, 7, // Top
4, 5, 1, 4, 1, 0, // Bottom
];
// Color data per face (6 faces)
let faceColors = colors;
let colorsArray = [];
for (const color of faceColors) {
// Repeat each color 4 times (4 vertices per face)
for (let i = 0; i < 6; i++) {
colorsArray = colorsArray.concat(color);
}
}
// Create and bind position buffer
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// Create and bind color buffer
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colorsArray), gl.STATIC_DRAW);
// Create and bind index buffer
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
return {
position: positionBuffer,
color: colorBuffer,
indices: indexBuffer,
};
}
Function to Get Face Colors Based on Position:
function getCubieFaceColors(x, y, z) {
// Define colors
const white = [1.0, 1.0, 1.0, 1.0]; // Up
const yellow = [1.0, 1.0, 0.0, 1.0]; // Down
const red = [1.0, 0.0, 0.0, 1.0]; // Front
const orange = [1.0, 0.5, 0.0, 1.0]; // Back
const blue = [0.0, 0.0, 1.0, 1.0]; // Left
const green = [0.0, 1.0, 0.0, 1.0]; // Right
const black = [0.0, 0.0, 0.0, 1.0]; // Internal faces
const colors = [];
// Front face (Z+)
colors.push(z === 1 ? red : black);
// Back face (Z-)
colors.push(z === -1 ? orange : black);
// Right face (X+)
colors.push(x === 1 ? green : black);
// Left face (X-)
colors.push(x === -1 ? blue : black);
// Top face (Y+)
colors.push(y === 1 ? white : black);
// Bottom face (Y-)
colors.push(y === -1 ? yellow : black);
return colors;
}
const cubies = [];
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
// Skip the center cubie
if (x === 0 && y === 0 && z === 0) continue;
// Get face colors for this cubie
const faceColors = getCubieFaceColors(x, y, z);
// Create buffers for cubie
const buffers = createCubieBuffers(gl, faceColors);
// Store position and buffers
cubies.push({
position: [x, y, z],
buffers: buffers,
});
}
}
}
Include the glMatrix library in your HTML (already done in Step 1).
Set up projection and view matrices:
const fieldOfView = 45 * Math.PI / 180; // Radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
const viewMatrix = mat4.create();
mat4.translate(viewMatrix, viewMatrix, [0.0, 0.0, -10.0]); // Move camera back
const pvMatrix = mat4.create();
mat4.multiply(pvMatrix, projectionMatrix, viewMatrix);
Set up the render loop:
let rotation = 0;
function drawScene() {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST); // Enable depth test
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Rotate the whole cube
const rotationMatrix = mat4.create();
mat4.rotate(rotationMatrix, rotationMatrix, rotation, [1, 1, 0]);
for (const cubie of cubies) {
// Model matrix for the cubie
const modelMatrix = mat4.create();
mat4.translate(modelMatrix, modelMatrix, cubie.position);
mat4.multiply(modelMatrix, rotationMatrix, modelMatrix);
// Final transformation matrix
const mvpMatrix = mat4.create();
mat4.multiply(mvpMatrix, pvMatrix, modelMatrix);
// Set up attributes and uniforms
{
const numComponents = 3;
gl.bindBuffer(gl.ARRAY_BUFFER, cubie.buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.position,
numComponents,
gl.FLOAT,
false,
0,
0
);
gl.enableVertexAttribArray(programInfo.attribLocations.position);
}
{
const numComponents = 4;
gl.bindBuffer(gl.ARRAY_BUFFER, cubie.buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.color,
numComponents,
gl.FLOAT,
false,
0,
0
);
gl.enableVertexAttribArray(programInfo.attribLocations.color);
}
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubie.buffers.indices);
gl.useProgram(programInfo.program);
gl.uniformMatrix4fv(programInfo.uniformLocations.matrix, false, mvpMatrix);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
gl.drawElements(gl.TRIANGLES, vertexCount, type, 0);
}
}
rotation += 0.01;
requestAnimationFrame(drawScene);
}
requestAnimationFrame(drawScene);
rubiks_cube.js)Put all the code together in your rubiks_cube.js file.
Note: Due to space constraints, the full code isn't repeated here, but ensure all the functions and code snippets from previous steps are included in rubiks_cube.js.
When you open rubiks_cube.html in a web browser that supports WebGL, you should see a 3D Rubik's Cube rotating. Each face of the cube should have the correct color corresponding to a solved Rubik's Cube:
You've successfully drawn a 3D solved Rubik's Cube using WebGL! This exercise demonstrates setting up a WebGL scene, creating geometry, applying transformations, and rendering colored objects.
Feel free to ask if you have any questions or need further assistance!
Not yet included in a published release.