Search code examples
setzoomingprocessingfractalsmandelbrot

I made a processing program that generates a mandelbrot set but don't know how to effectively implement a zoom method


I'm not sure if it is possible in processing but I would like to be able to zoom in on the fractal without it being extremely laggy and buggy. What I currently have is:

int maxIter = 100;
float zoom = 1;
float x0 = width/2;
float y0 = height/2;

void setup(){
  size(500,300); 
  noStroke(); 
  smooth();
}

void draw(){
   translate(x0, y0);
   scale(zoom);
   for(float Py = 0; Py < height; Py++){
      for(float Px = 0; Px < width; Px++){
//        scale pixel coordinates to Mandelbrot scale
        float w = width;
        float h = height;
        float xScaled = (Px * (3.5/w)) - 2.5;
        float yScaled = (Py * (2/h)) - 1;

        float x = 0;
        float y = 0;
        int iter = 0;
        while( x*x + y*y < 2*2 && iter < maxIter){
           float tempX = x*x - y*y + xScaled;
           y = 2*x*y + yScaled;
           x = tempX;
           iter += 1;
        }
//        color pixels
        color c;
        c = pickColor(iter);
        rect(Px, Py,1,1);
        fill(c);
     } 
  }
}

//        pick color based on time pixel took to escape (number of iterations through loop)
color pickColor(int iters){
  color b = color(0,0,0);
  if(iters == maxIter) return b;

  int l = 1;
  color[] colors = new color[maxIter];
  for(int i = 0; i < colors.length; i++){
    switch(l){
      case 1 :  colors[i] = color(255,0,0); break;
      case 2 :  colors[i] = color(0,0,255); break;
      case 3 :  colors[i] = color(0,255,0); break;
    }
    if(l == 1 || l == 2) l++;
    else if(l == 3) l = 1;
    else l--;    
  }

  return colors[iters];
}
//        allow zooming in and out
void mouseWheel(MouseEvent event){
    float direction = event.getCount();
    if(direction < 0) zoom += .02;
    if(direction > 0) zoom -= .02;
}

//        allow dragging back and forth to change view
void mouseDragged(){
   x0+= mouseX-pmouseX;
   y0+= mouseY-pmouseY; 
}

but it doesn't work very well. It works alright at the size and max iteration I have it set to now (but still not well) and is completely unusable at larger sizes or higher maximum iterations.


Solution

  • The G4P library has an example that does exactly this. Download the library and go to the G4P_MandelBrot example. The example can be found online here.

    Hope this helps!