Tuesday, February 9, 2010

Metaballs


The metaball effect is a famous demoscene effect. It's a cool effect, and it's easy to optimize.
The theory is pretty simple: for each ball, you evaluate the value of a function for a given point, and add it to a variable. If it's over some threshold, then you can plot that point. The function is usually:

P: center of the metaball
S: screen point

f(S, P) = 1 / (S - P)2
For each metaball add f(S, P) to a variable (P: current ball center)


It's very easy to compute this function for each metaball. Howewer, this function is slow, due to the division. For this reason, you must find an alternate function. Another possible function is:
f(S, P) = (1 - S - P2)2

You can erase the square root, due to this:
sqrt(x)2 = x

So, the final formula is:

r = (Sx - Px)2 + (Sy - Py)2
f(S, P) = (1 - r)2


This formula is faster, but not fast enough. However, there's another trick you could do. Most of the space in the screen won't be covered by the metaballs, so you can change the code to scan for metaballs (each rectangle in the image, for example), instead of scanning each pixel of the screen.

No comments:

Post a Comment