I'm working on visualizing the Mandelbrot set as well as a few other fractals and there's a lot of duplicated code but no code reuse.
One of the functions I am using is below:
/**
* determines whether a pixel lies in the set
* @params x, y - x and y coordinates on R/I axes
* @param c - a complex number
*/
void calculateSet(int x, int y, Complex c) {
Complex z = c.clone();
int n = 0;
for (; n < maxDepth; n++) {
if (z.dis() > 4) { break; }
z = z^2 + c;
}
// some code using n to color the set
}
This follows the Mandelbrot set:
z_(n+1) = z_n^2 + c
But look at the relevant code for the Burning Ship set:
void calculateSet(int x, int y, Complex c) {
Complex z = c.clone();
int n = 0;
for (; n < maxDepth; n++) {
if (z.dis() > 4) { break; }
z = abs(z)^2 + c; // ***
}
// follows z_(n+1) = abs(z_1)^2 + c
}
All the code save for the starred line is identical. Right now I have separate classes for Mandelbrot
, BurningShip
, and a few others with the only difference being that one line.
Is there a way to define this expression and pass to a generalized Set
class?
Some pseudocode:
class Set {
// ...
Set(Type expression) {
// ...
// x, y, c initialized
// ...
calculateSet(x, y, c, expression);
}
void calculateSet(int x, int y, Complex c, Type e) {
Complex z = c.clone();
int n = 0;
for (; n < maxDepth; n++) {
if (z.dis() > 4) { break; }
z = e;
}
}
};
And I can just use Set
to describe any kind of set I wish?
Set mandelbrot = Set(Type("z^2 + c"));
Set burningship = Set(Type("abs(z)^2 + c"));
// etc
I could use if/else
statements to have just one class, but it's not generalized.