NestedBoxesGeometry

Hi community!

This picture is the result of gradiental rotation of a bunch of nested boxes

And that’s how the boxes look like, non-rotated:

Demo: https://codepen.io/prisoner849/full/jOwVJEW

Rotation of boxes is based on Matrix4(), pretty similar to how it’s done for instances of InstancedMesh

Code:

function NestedBoxesGeometry(minSize, maxSize, layers = 2, innerColor = 0xffffff, outerColor = 0x7f7f7f){
  
  let cI = new THREE.Color(innerColor);
  let cO = new THREE.Color(outerColor);
  let cM = new THREE.Color();
  
  let basePts = [
    [0, 0, 0],[1, 0, 0],[1, 0, 1],[0, 0, 1],
    [0, 1, 0],[1, 1, 0],[1, 1, 1],[0, 1, 1]
  ].map(p => {return new THREE.Vector3(p[0], p[1], p[2]).subScalar(0.5)});
  let baseIndex = [
    0, 1, 1, 2, 2, 3, 3, 0,
    4, 5, 5, 6, 6, 7, 7, 4,
    0, 4, 1, 5, 2, 6, 3, 7
  ];
  let connect = [
    0, 8, 1, 9, 2, 10, 3, 11,
    4, 12, 5, 13, 6, 14, 7, 15
  ];
  
  let sizeStep = (maxSize - minSize) / (layers);
  let pts = [];
  let idx = [];
  let col = [];
  let layer = [];
  for(let i = 0; i < layers; i++){
    basePts.forEach(p => {
      pts.push(p.clone().multiplyScalar(i * sizeStep + minSize));
      layer.push(i);
      cM.lerpColors(cI, cO, i / (layers - 1));
      col.push(cM.r, cM.g, cM.b);
    });
    baseIndex.forEach(id => {
      idx.push(id + i * 8)
    })
    
    if (i < (layers - 1)){
      connect.forEach(c => {
        idx.push(c + i * 8);
      })
    }
  }
  
  let g = new THREE.BufferGeometry().setFromPoints(pts);
  g.setAttribute("color", new THREE.Float32BufferAttribute(col, 3));
  g.setAttribute("layer", new THREE.Float32BufferAttribute(layer, 1));
  g.setIndex(idx);

  return g;
}
4 Likes