juliamath.c (2518B)
1 /* 2 Back-end Math for the Julia/Mandelbrot Set implementation file 3 "juliamath.c" 4 M. Yamanaka 5 email: myamanaka@live.com 6 website: csmyamanaka.com 7 license: MIT (See included "LICENSE" file for details) 8 */ 9 10 #include "juliamath.h" 11 12 int cmplxAdd(float* rz, float* op1, float* op2){ 13 /* 14 op1 ... first operand 15 op2 ... second operand 16 rz ... result 17 */ 18 rz[0] = op1[0] + op2[0]; 19 rz[1] = op1[1] + op2[1]; 20 return 0; 21 } 22 23 int cmplxMult(float* rz, float* op1, float* op2){ 24 /* 25 op1 ... first operand 26 op2 ... second operand 27 rz ... result 28 */ 29 rz[0] = op1[0]*op2[0] - op1[1]*op2[1]; 30 rz[1] = op1[0]*op2[1] + op1[1]*op2[0]; 31 return 0; 32 } 33 34 float cmplxLenSq(float* ipt){ 35 /* 36 ipt ... input complex number 37 */ 38 return ipt[0]*ipt[0] + ipt[1]*ipt[1]; 39 } 40 41 float convNtoR(int ipt, int sz, float cmin, float cmax){ 42 /* 43 ipt ... number pending conversion 44 sz ... image length in a given dimension before conversion 45 cmin ... mininum value of a given axis on the complex plane 46 cmax ... maximun " " " etc ... 47 */ 48 49 /* 50 ipt ranges from [0 to sz) and needs to be mapped to [0, 1) 51 */ 52 53 return ((1.0*ipt)/sz)*(cmax - cmin) + cmin; 54 } 55 56 int fz(float* z, float* C, int* n){ 57 /* 58 z ... z in f(z) = z^2 + C 59 C ... C in f(z) = z^2 + C 60 n ... current iteration 61 */ 62 if(cmplxLenSq(z) < 4 && *n < iter_max){ 63 float reg[2]; //temporary register 64 cmplxMult(reg, z, z); 65 cmplxAdd(z, reg, C); 66 (*n)++; 67 fz(z, C, n); 68 } 69 return 0; 70 } 71 72 int* imgIters(int w, int h){ 73 /* 74 w ... width or number of columns 75 h ... height or number of rows 76 */ 77 78 //Initialize array that contains the escape for each pixel initialized to 0 79 int* data = (int*)malloc(sizeof(int)*w*h); 80 for(int i = 0; i < w*h; i++) data[i] = 0; 81 82 //for each pixel, calculate the Re-Im plane conversion then calculate escape count 83 for(int i = 0; i < h; i++){ 84 for(int j = 0; j < w; j++){ 85 86 /* 87 C + 0 points to 0 + 0i, C + 2 points to the pixel converted to complex coordinates and C + 4 points to the 88 pre-selected constant for the Julia set. 89 */ 90 float C[6] = {0, 0, convNtoR(j, w, vx_min, vx_max), convNtoR(i, h, vy_min, vy_max), julia_C[0], julia_C[1]}; 91 92 /* 93 fractal_flag: 0 creates the mandelbrot set, otherwise julia 94 I use a nifty little maneuver with boolean arithmetics to avoid using if-else statements 95 */ 96 fz(C + 2*(fractal_flag != 0), C + 2 + 2*(fractal_flag != 0), data + i*w + j); 97 } 98 } 99 100 return data; 101 }