three.js ~ example ~ Mr.doob

2012-01-05 ~

by Umair Rafiq

HTML

<script src="https://cdn.jsdelivr.net/gh/paulmasson/threejs-with-controls@r121/build/three.min.js"></script>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3D Rubik's Cube with Algorithm Input</title>
</head>
<body>
  <div id="container"></div>
  <div id="controls" style="position: absolute; top: 10px; left: 10px; background: rgba(255,255,255,0.8); padding: 10px; z-index: 10;">
    <input type="text" id="dataInput" style="width: 400px;" 
      value="alg=R' D' R D R' D' R D R' D' R D R' D' R D R' D' R D R' D' R D   |hover=1|speed=100|flags=showalg">
    <button id="runAlg">Run Algorithm</button>
    <div id="algDisplay" style="margin-top:10px;"></div>
  </div>
</body>
</html>

CSS

body {
  margin: 0;
  overflow: hidden;
}

JavaScript

var scene, camera, renderer, controls;
var rubiksGroup;
var cubes = [];
var rotating = false;
var globalOffset; // used to compare cube positions

init();
animate();

function init() {
  // Set up scene and camera
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x202020);
  
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.set(6, 6, 6);
  camera.lookAt(0, 0, 0);
  
  // Create renderer and append to container
  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.getElementById('container').appendChild(renderer.domElement);
  
  // Set up OrbitControls
  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  
  // Create Rubik's Cube group
  rubiksGroup = new THREE.Group();
  scene.add(rubiksGroup);
  
  // Build the 3x3x3 Rubik's Cube
  var cubeSize = 1;
  var gap = 0.05;
  var total = 3;
  globalOffset = (total - 1) * (cubeSize + gap) / 2;
  
  for (var x = 0; x < total; x++) {
    for (var y = 0; y < total; y++) {
      for (var z = 0; z < total; z++) {
        var geometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
        var materials = createCubeMaterials(x, y, z, total);
        var cube = new THREE.Mesh(geometry, materials);
        cube.position.set(
          x * (cubeSize + gap) - globalOffset,
          y * (cubeSize + gap) - globalOffset,
          z * (cubeSize + gap) - globalOffset
        );
        rubiksGroup.add(cube);
        cubes.push(cube);
      }
    }
  }
  
  // Basic lighting
  scene.add(new THREE.AmbientLight(0xffffff, 0.7));
  var directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
  directionalLight.position.set(5, 10, 7.5);
  scene.add(directionalLight);
  
  window.addEventListener('resize', onWindowResize, false);
  
  // Handle the "Run Algorithm" button click
 ...