# 01. First cube, explained line by line

**Goal:** the smallest complete three.js program: a spinning cube that stays sharp when you resize the window.

Run it: serve the repository folder (see the main README) and open `examples/01-first-cube/`.

## The three things every three.js app needs

| Object | Job | Analogy |
| --- | --- | --- |
| `Scene` | Holds objects, lights and the background | The stage |
| `Camera` | Defines the viewpoint and projection | The audience's eyes |
| `WebGLRenderer` | Draws the scene, as seen by the camera, into a `<canvas>` | The projector |

## Walkthrough

```js
import * as THREE from 'three';
```
The `importmap` in `index.html` maps the bare name `three` to a pinned CDN URL, so the browser can load it without a bundler. In a Vite or webpack project the same line works after `npm install three`.

```js
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101418);
```
Creates the container for everything. `background` accepts a `Color`, a texture or a cube texture. Colors use hex numbers (`0xRRGGBB`), CSS strings (`'tomato'`) or RGB floats.

```js
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 0, 3);
```
- `60` is the **vertical field of view** in degrees. Larger values look more "fish-eye".
- The **aspect ratio** must match the canvas, or everything looks stretched.
- `0.1` and `100` are the **near and far planes**: objects closer than 0.1 or farther than 100 units are not drawn. Keep the ratio far/near reasonable (not 0.0001 to 1e9), or depth precision suffers and surfaces flicker (z-fighting).
- The camera starts at the origin looking down **-Z**. Moving it to `z = 3` puts the cube in front of it.

```js
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
```
- `antialias: true` smooths jagged edges.
- `setPixelRatio` renders at the screen's density for crisp output on high-DPI displays. Capping at 2 avoids rendering 9x the pixels on 3x phones, which costs a lot of GPU time for little visible gain.
- `setSize` sets both the drawing buffer and the canvas CSS size.
- `renderer.domElement` is the `<canvas>` three.js created; you add it to the page yourself.

```js
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshNormalMaterial();
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
```
A `Mesh` combines **what shape** (geometry: vertices and triangles) with **how it looks** (material). `MeshNormalMaterial` colors each face by the direction it points, so it is visible without any light, which makes it ideal for a first test. Nothing appears until the mesh is added to the scene.

```js
window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});
```
After changing any camera property that affects projection (`fov`, `aspect`, `near`, `far`, `zoom`), call `updateProjectionMatrix()`. Forgetting it is the classic "my scene is squished after resizing" bug.

```js
const timer = new THREE.Timer();
renderer.setAnimationLoop((time) => {
  timer.update(time);
  const delta = timer.getDelta();
  cube.rotation.x += delta * 0.6;
  cube.rotation.y += delta * 0.9;
  renderer.render(scene, camera);
});
```
- `setAnimationLoop` is three.js's wrapper around `requestAnimationFrame`. It also works in WebXR sessions, where plain `requestAnimationFrame` does not.
- `Timer` (part of the core library; the older `Clock` logs a deprecation warning since r183) must be **updated once per frame** with the timestamp; then `getDelta()` returns seconds since the previous frame. Multiplying speeds by `delta` makes motion the same on 60 Hz and 144 Hz screens.
- Rotations are in **radians** (`Math.PI` = 180 degrees).
- `renderer.render(scene, camera)` draws one frame.

## Try this

1. Swap `MeshNormalMaterial` for `new THREE.MeshBasicMaterial({ color: 'orange', wireframe: true })`.
2. Replace the box with `new THREE.TorusKnotGeometry(0.5, 0.15, 128, 16)`.
3. Change the field of view to 20 and then 110 and watch the perspective change.
4. Stop the loop with `renderer.setAnimationLoop(null)`.

## Common mistakes

- **Black screen:** camera inside the object, object not added to the scene, or a lit material with no lights (see example 02).
- **Stretched image:** aspect ratio not updated on resize.
- **Animation speed differs between computers:** incrementing by a fixed amount per frame instead of using delta time.
