In this post I will give you a glimpse of what computer graphics algorithms may look like. I will explain the ray tracing algorithm and show a simple implementation in Python.
By the end of this article you’ll be able to make a program that will generate the above image, without making use of any fancy graphic library! Only NumPy. Isn’t it crazy?! Let’s dive in!
P.S. This article is by no mean a complete guide / explanation of ray tracing, since this is such a vast subject, but rather an introduction for curious people :)
Prerequisites
We only need very basic vector geometry.
- If you have 2 points A and B — whatever the dimensionality: 1, 2, 3, …, n — then a vector that goes from
AtoBcan be found by computingB — A(element-wise); - The length of a vector — whatever the dimensionality — can be found by computing the square root of the sum of the squared components. The length of a vector
vis denoted||v||; - A unit-vector is a vector of length 1:
||v|| = 1; - Given a vector, another vector that points to the same direction but with a length of 1 can be found by dividing each component of the first vector by its length — this is called normalization:
u = v / ||v||; - Dot product for vectors. Specifically:
<v, v> = ||v||²; - Solving a quadratic equation;
- A bit of patience and imagination;