view src/Mandelbrot.cpp @ 2:0684158d38a8

Before cleanup. Still has experimental code in it.
author Eris Caffee <discordia@eldalin.com>
date Fri, 22 Oct 2010 02:21:52 -0500
parents 455406f5f021
children 0f4ad525f49a
line source
1 ////////////////////////////////////////////////////////////////////////////////
2 //
3 // (C) 2010 Sarah Eris Horsley Caffee
4 //
5 // mandelbrot - A simple Mandelbrot Set viewer.
6 //
7 // Mandelbrot.cpp
8 // Mandelbrot set calculator class implementation
9 //
10 ////////////////////////////////////////////////////////////////////////////////
12 #include <iostream>
13 #include <string>
15 #include "Mandelbrot.h"
16 #include "Options.h"
18 ////////////////////////////////////////////////////////////////////////////////
20 Mandelbrot::Mandelbrot()
21 {
22 name.assign("Mandelbrot set");
23 re_min = -2.5;
24 im_max = 2.5;
25 size = 5.0;
26 max_iter = 50;
27 }
30 ////////////////////////////////////////////////////////////////////////////////
31 bool Mandelbrot::init(SDL_Surface * surf)
32 {
33 if (!surf)
34 {
35 return false;
36 }
37 else
38 {
39 surface = surf;
40 }
41 calc_needed = true;
42 return true;
43 }
46 ////////////////////////////////////////////////////////////////////////////////
48 bool Mandelbrot::calc_set()
49 {
50 if (!surface) return false;
52 // Code from http://warp.povusers.org/Mandelbrot/
54 if (calc_needed)
55 {
56 double re_scale = (size)/(Options::width-1);
57 double im_scale = (size)/(Options::height-1);
59 int r, g, b;
61 Uint32 black = SDL_MapRGB(surface->format, 0, 0, 0);
62 Uint32 color;
63 int halfway = max_iter/2 - 1;
64 float step = (float) 255 / halfway;
66 unsigned x, y, n;
68 for(y = 0; y < Options::height; ++y)
69 {
70 double c_im = im_max - y * im_scale;
71 for(x = 0; x < Options::width; ++x)
72 {
73 double c_re = re_min + x * re_scale;
75 double z_re = c_re, z_im = c_im;
76 bool in_set = true;
77 for(n=0; n < max_iter; ++n)
78 {
79 double z_re2 = z_re * z_re, z_im2 = z_im * z_im;
80 if(z_re2 + z_im2 > 4)
81 {
82 in_set = false;
83 break;
84 }
85 z_im = 2 * z_re * z_im + c_im;
86 z_re = z_re2 - z_im2 + c_re;
87 }
88 if(in_set)
89 {
90 draw_pixel(x, y, &black);
91 }
92 else
93 {
94 if (n <= halfway)
95 {
96 b = n * step;
97 r = g = 0;
98 }
99 else
100 {
101 b = 255;
102 r = g = (n - halfway) * step;
103 }
104 color = SDL_MapRGB(surface->format, r, g, b);
105 draw_pixel(x, y, &color);
106 }
107 }
108 }
109 }
111 calc_needed = false;
112 return true;
113 }
116 ////////////////////////////////////////////////////////////////////////////////
118 void Mandelbrot::draw_pixel(int x, int y, Uint32 * color)
119 {
120 Fractal::draw_pixel(x, y, color);
121 }