Lens effect

There is a cool new 256b intro at pouet.net, called ind. It shows a rotating sphere divided into several fields, which flicker in funky colours.

This intro is basically based on the lens effect. The lens effect is a distortion that projects all pixels from a square onto a circle surrounding it. How is this done?

If we try to imagine how it works, we will perhaps start with the y coordinates of the projection of the topmost line of the square: We notice that the points in the horizontal center are the topmost ones and the elevation declines to the edges, where it becomes zero, i.e. the edges are printed at the same position as in the square. With what mathematical formula can this be achieved? Simple subtraction wouldn't make it a circle. We need a trigonometric function. Which one? Let's figure it out: We use the distance from the horizontal center point as its parameter. If it is 0, the height must have the highest value, and if it is maximal, the height must be 0. A trigonometric function that has this property is... cosine! So we'll use cosine.

Now we must just consider that the level of elevation also depends on the y coordinate of the original point in the square. The closer we get to the vertical center of the square, the "flatter" the curve becomes. So we also have to multiply with a factor dependent on the y coordinate.

The computation of the x coordinate works in an analogous way.

The code to precalculate the transformations needed for applying the lens effect could basically look like this:

int pos = 0;
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
{
coords [pos].x = cos (((double) y / center - 1) * 3.1415 / 2) * (((double) x / center) - 1) * factor;
coords [pos].y = cos (((double) x / center - 1) * 3.1415 / 2) * (((double) y / center) - 1) * factor;
pos ++;
}

Now what's this variable called "factor"? Well, it determines the smoothness of your projection, how much it looks like a real circle. Try inserting various values for it.

Can you find out the optimal value for "factor" - either by trying it out or, even better, by computing it mathematically?

Kommentare

Beliebte Posts aus diesem Blog

The Demoscene

Digital Art Natives

Autobiographical Sketch