Three.js Crystal Lattice Viewer (SC, BCC, FCC, NaCl, Diamond)

Explore cubic crystal lattices in Three.js — simple cubic, body-centered, face-centered, rock salt, cesium chloride and diamond — with nearest-neighbour bonds, unit-cell outline and an exploded view.

Key topics: three.js crystal, crystal lattice, unit cell, fcc, bcc, nacl, diamond cubic, materials science

What this code does

- Basis + Lattice: each structure is a list of fractional basis atoms repeated over an N×N×N grid of unit cells.
- Boundary Atoms: far-face atoms are kept so the block looks closed, and duplicates are removed with a position hash.
- Bond Detection: atom pairs exactly one nearest-neighbour distance apart (lattice-specific) are joined with `LineSegments`.
- Instancing: one `InstancedMesh` per species keeps even 5×5×5 diamond blocks to a handful of draw calls.
- Exploded View: scale positions outward to see how atoms are shared between neighbouring cells.
- Controls: lattice type, cells per edge, atom size, explode, bonds, unit cell and spin.

Continue Learning

JavaScript Implementation

ES6+
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100)
camera.position.set(7, 5.5, 9)
camera.lookAt(0, 0, 0)
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(width, height)
document.querySelector('#app').appendChild(renderer.domElement)
scene.add(new THREE.HemisphereLight(0xdbeafe, 0x1e293b, 1.2))

// Face-centered cubic basis in fractional coordinates
const basis = [[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]]
const n = 3
const a = 2
const points = []
for (let i = 0; i < n; i++) {
  for (let j = 0; j < n; j++) {
    for (let k = 0; k < n; k++) {
      basis.forEach(([fx, fy, fz]) => {
        points.push(new THREE.Vector3((i + fx) * a - n, (j + fy) * a - n, (k + fz) * a - n))
      })
    }
  }
}

const atoms = new THREE.InstancedMesh(
  new THREE.SphereGeometry(0.35, 24, 16),
  new THREE.MeshStandardMaterial({ color: 0xf97316 }),
  points.length
)
const m = new THREE.Matrix4()
points.forEach((p, i) => atoms.setMatrixAt(i, m.makeTranslation(p.x, p.y, p.z)))
scene.add(atoms)

function animate () {
  requestAnimationFrame(animate)
  atoms.rotation.y += 0.004
  renderer.render(scene, camera)
}
animate()