# 3D Model Orbit

[Live demo](https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/3d-model-orbit/)

## What it is
A 3D model orbit shows a solid-looking object turning in the browser. The shape is stored as triangles, and WebGL lights every point of it with a soft base light, a direct light and a shiny highlight, so each side reads as solid as it comes into view. It is the basic pattern behind 3D product viewers, drawn here without a 3D library.

## When to use it
- Product configurators where a 3D object must rotate on hover or on scroll
- Hero sections that display an animated 3D logo or abstract shape
- Mouse-follow effects where an object tilts to track the cursor
- Educational contexts for showing the structure of 3D coordinate systems

## How it works
A WebGL program needs three components: geometry (vertex data), shaders (GPU programs), and a transformation matrix.

**Vertex shader** receives each vertex position and normal, and outputs the clipped position plus interpolated data for the fragment shader:

```glsl
attribute vec3 aPos, aNorm;
uniform mat4 uMVP, uM;        /* model-view-projection, model-view */
varying vec3 vN, vP;

void main() {
  gl_Position = uMVP * vec4(aPos, 1.0);
  vP = (uM * vec4(aPos, 1.0)).xyz;
  vN = normalize(mat3(uM) * aNorm);
}
```

**Fragment shader** applies Phong lighting — ambient + diffuse + specular:

```glsl
precision mediump float;
varying vec3 vN, vP;
uniform vec3 uCol, uLight;

void main() {
  vec3 L = normalize(uLight - vP);
  vec3 V = normalize(-vP);
  float d = max(dot(vN, L), 0.0);
  float s = pow(max(dot(reflect(-L, vN), V), 0.0), 48.0);
  gl_FragColor = vec4(0.15 * uCol + d * uCol + 0.7 * s, 1.0);
}
```

**Transformation pipeline** — the MVP matrix chain:

```js
const P   = perspective(Math.PI/4, width/height, 0.1, 20);
const T   = translate(0, 0, -dist);
const M   = multiply(multiply(T, rotateY(ry)), rotateX(rx));
const MVP = multiply(P, M);
```

**Turning** — the angles grow by the time that has passed, not by a fixed amount per frame, so the shape turns at the same speed on a 30, 60 or 144 Hz screen:

```js
const FRAME = 1000 / 60;                     // one frame on a 60 Hz screen, in milliseconds
const step = Math.min(elapsed, 50) / FRAME;  // 1 at 60 Hz; a long gap counts for at most 50 ms
ry += SPEED_Y * 0.01 * step;                 // the spin
rx += SPEED_X * 0.01 * step * (Math.sin(clock * 0.0003) * 0.5 + 0.5);  // the forward roll, at a speed that rises and falls
```

## Key parameters
| Parameter | Default | Effect |
|-----------|---------|--------|
| Shape | Cube | The object that is drawn: a cube, a sphere, a ring or a pyramid of four triangles |
| Movement | Spins | Spins turns it by itself; Follows the pointer turns it to face your pointer or finger, up to 86° to either side and 69° up or down with the pointer at the stage's edges |
| Speed | Normal | How fast it spins: slow is about 17°, normal 27° and fast 45° a second, on any screen; while it tumbles, the forward roll swings between still and a quarter of that over about 21 seconds |
| Tumbles as it spins | on | Also rolls it forward, at a speed that rises and falls, so the top and bottom come into view |
| Distance | Medium | How far away the camera is, from the shape's center: close is about 2.3 times the shape's width, medium 2.7 times and far 3.8 times, so close looks bigger; the lens stays the same, a 45° view from top to bottom |
| Color | Blue | The object's color; the lighting adds the shading and the highlight |
| Edges only | off | Draws the edges of the triangles the shape is made of, instead of its lit surface |

## Production notes
- **Three.js in production**: Three.js's `PerspectiveCamera`, `MeshPhongMaterial`, and `OrbitControls` replace everything in this demo in ~20 lines. Use Three.js for anything more complex than a single object — raw WebGL becomes unmanageable fast.
- **Time, not frames**: a fixed turn per frame would spin the shape twice as fast on a 120 Hz screen and half as fast on a 30 Hz phone. Scale each turn by the time since the last frame, cap that time (this demo uses 50 ms) so a tab that comes back does not lurch, and let a returning tab start from its next frame.
- **Normal matrix**: strictly, normals should be transformed by the inverse-transpose of the model matrix, not the model matrix itself. For uniform scaling (no non-uniform squash/stretch), the model matrix works fine. For non-uniform scale, use `mat3(transpose(inverse(uM)))`.
- **`prefers-reduced-motion`**: stop the animation loop and show the object in its default orientation. The object should remain visible and interactive for camera control.
- **Touch/pointer interaction**: use `pointerdown` / `pointermove` / `pointerup` for drag-to-rotate, not `mousedown` — this covers touch without separate event listeners.
- **Fail loudly**: a shader that does not compile produces a black canvas and no exception, because `COMPILE_STATUS` is only readable if you ask for it. Check it (and `LINK_STATUS`) and show a message; a silent black box is the hardest WebGL bug to diagnose.
- **Context loss**: the browser can drop a WebGL context on a GPU reset, driver update, or tab restore, and the canvas then stays blank forever. In production, listen for `webglcontextlost` (call `preventDefault()` on it) and rebuild buffers, textures, and programs in `webglcontextrestored`. This demo does not, to keep the render path readable.

## See also
- [Scroll-Driven 3D Rotation](../scroll-driven-3d-rotation/) — scrolling turns the object instead of time
- [Parallax 3D Tilt](../parallax-3d-tilt/) — a flat card leans in 3D toward the pointer
- [WebGL Shader Animation](../webgl-shader-animation/) — the same WebGL setup, painting a pattern instead of a shape
