A terminal-based 3D ASCII donut animation written in C.
This program renders a rotating torus (donut) directly inside the terminal using mathematical projection, trigonometry, depth buffering, and ASCII shading techniques.
The animation continuously rotates in real-time and simulates 3D lighting entirely using text characters.
This project focuses on learning:
- terminal rendering
- 3D projection math
- trigonometry in graphics
- depth buffering
- animation loops
- low-level rendering concepts in C
- Real-time rotating ASCII donut
- 3D perspective projection
- Depth buffer (Z-buffer) implementation
- ASCII lighting and shading
- Pure terminal rendering
- Written entirely in C
- Uses trigonometric functions for rotation
The program mathematically generates points on a torus surface and projects them onto a 2D terminal screen.
For every frame:
- Clears previous frame buffer
- Calculates 3D donut coordinates
- Applies rotation transformations
- Projects 3D points into 2D screen space
- Computes brightness/shading
- Uses ASCII characters as pixels
- Prints updated frame to terminal
The animation repeats continuously to create smooth rotation.
Two buffers are created:
char b[1760];
float z[1760];b[]stores ASCII charactersz[]stores depth values (Z-buffer)
This allows proper 3D overlap rendering.
Nested loops generate points across the torus surface:
for (j = 0; j < 6.28; j += 0.07)
for (i = 0; i < 6.28; i += 0.02)These loops iterate across circular angles using radians.
Rotation variables:
A += 0.04;
B += 0.02;control donut rotation over time.
Trigonometric functions:
sin()
cos()are used to rotate 3D coordinates.
Perspective projection converts 3D points into terminal coordinates:
int x = 40 + 30 * D * (...);
int y = 12 + 15 * D * (...);This creates the illusion of depth.
if (D > z[o])ensures closer points overwrite farther points.
This prevents rendering artifacts.
Brightness values are mapped to characters:
".,-~:;=!*#$@"Different characters simulate lighting intensity.
Example:
. -> dark
@ -> brightest
The frame is drawn using:
putchar()and terminal cursor reset escape sequences:
printf("\x1b[H");This redraws frames in-place to create animation.
Compile using:
gcc donut.c -o donut -lmThe -lm flag links the math library.
./donut @$@@$@@
$$$$$$$$$$$$$
$$$$############$$$
$$$####********####$$$
$$###****!!!!!****###$$
(The actual donut rotates continuously in terminal.)
- 3D coordinate systems
- Perspective projection
- Rotation matrices
- Trigonometry in graphics
- ASCII rendering
- Frame buffering
- Z-buffering
- Animation loops
- Terminal graphics
- Real-time rendering
Standard C libraries only:
stdio.hmath.hstring.hunistd.h
No graphics engine required.
Inspired by the classic ASCII donut demo created by Andy Sloane.
A legendary demonstration of how powerful math and low-level rendering can be even inside a terminal.