# How to create a fractal torus Fractals are a wonderful part of computer graphics – with just some lines of code, you can create awesome effects.
Here’s how to create a fractal torus (i.e. a ring made up of smaller rings, recursively). Click on the image to see a live demo with WebGL.

In pseudocode:

```createTorus
if (recursionFinished)
drawBasicShape();
else
for each segment
rotate by 90 degrees
move to torus center
rotate by one segment part
createTorus with smaller size
```

and here’s the core part of the torus generation with WebGL/three.js:

 Source code   ```function createTorus(radius, hoseRadius, segments, recursionDepth, matrix)
{
if (recursionDepth < 1)
{
var torus = new THREE.Mesh(geometry, materials[objects.length % SEGMENT_COUNT]);
geometry.applyMatrix(matrix);
objects.push(torus);
}
else
{
for (var i = 0; i < segments; i++)
{
var localMatrix = new THREE.Matrix4();
localMatrix.copy(matrix);
//rotate by 1 nth of the torus
var angle = i / segments * 2 * Math.PI;
var rotationMatrix = new THREE.Matrix4();
rotationMatrix.setRotationZ(angle);
//move to torus center
var translationMatrix = new THREE.Matrix4();
//twist be 90 degrees - the next smaller torus generation
var recursionRotation = new THREE.Matrix4();
recursionRotation.setRotationY(Math.PI / 2)
localMatrix.multiplySelf(rotationMatrix);
localMatrix.multiplySelf(translationMatrix);
localMatrix.multiplySelf(recursionRotation);
}
}
}```

and in OpenGL (a lot shorter, because the matrix operations are single function calls)

 Source code   ```void torus(double mainRadius, double hoseRadius, int segments, int rDepth) {
int i;
GLfloat m;/*temporary matrix*/
if (--recDepth < 1) {