martes, 7 de enero de 2014

Blender Cycles OSL: Mandelbrot Fractal

Hi. Today I'm going to show you an OSL code to get a Mandelbrot Fractal, like this:



This fractal uses the following complex numbers formula:

Z(n+1) = Z(n) ^ 2  + C

I have parameterized the exponent of the formula and the bailout value, that is, the value to stop the iterations. So the code is this:

shader mandelbrot_fractal_zn_zoom(
    float Scale = 1.0,
    float Zoom = 3.5,
    vector Vector = (vector)P,    
    float CenterX = 0.0,
    float CenterY = 0.0,
    int MaxIterations = 64,
    int Exponent = 2,
    float Bailout = 2.0,
    output float Fac = 0.0)
{
    point p = (point)Vector*Scale/(2*Zoom);
    int i = 0;
    int j = 0;
    int prevIteration = MaxIterations;
    float factor = 0.0;
    float foo = 0.0;
  
    // Starting point
    p[0] += CenterX;
    p[1] += CenterY;
 
    // Initialize 
    point pa = point(0.0);
    point pb = point(0.0);
    point pc = point(0.0);
    
    // Mandelbrot algorithm
    do
    {
        // z^j
        for(j = 1; j < Exponent; j++) {
            pc[0] = pa[0] * pb[0] - pa[1] * pb[1];
            pc[1] = pa[0] * pb[1] + pa[1] * pb[0];

            // for next product
            pb[0] = pc[0];
            pb[1] = pc[1];
        }

        // z^exponent + c
        pa = pc + p;
        pb[0] = pa[0];
        pb[1] = pa[1];
       
        i++;

        if ((prevIteration == MaxIterations) && (sqrt((pa[0]*pa[0]) + (pa[1]*pa[1])) > Bailout)) {
            prevIteration = i + 1;
        }        
    } while (i < prevIteration);
 
    // Factor to colorize
    factor = float(i);
    foo = sqrt((pa[0]*pa[0]) + (pa[1]*pa[1]));
    factor = factor - (log(log(foo))/log(Bailout));
    factor = factor / float(MaxIterations); 
  
    Fac = factor;
}

And this is the node setup to get the image before:


As it is using a exponential formula, if you change the exponent you can get another fractals (the power node and the color ramp could be slightly different):
  • Exponent 3

  • Exponent 4
  • Exponent 6
  • Exponent 7
  • Exponent 8
  • Exponent 9
  • Exponent 11


You can see other fractal renders using this code here.


Bye

1 comentario:

Spirou4D dijo...

Hi Friend,

You are interested about Fractal and me too: a crop-circle draw a radio telescope in a field near a terrian radio-telescope, do you know what I mean?
Your fractal "Exponent 3" is his plan. Do you know how calculate the perimetre of this line, may be please?

Bye
Spirou4D

Este sitio emplea cookies de Google para prestar sus servicios, para personalizar anuncios y para analizar el tráfico. Google recibe información sobre tu uso de este sitio web. Si utilizas este sitio web, se sobreentiende que aceptas el uso de cookies. Más información Entendido