Class: Fractals::Mandelbrot

Inherits:
Object
  • Object
show all
Defined in:
lib/fractal.rb

Direct Known Subclasses

Julia

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(image) ⇒ Mandelbrot

Returns a new instance of Mandelbrot.



16
17
18
19
# File 'lib/fractal.rb', line 16

def initialize image
  @width, @height = image.width, image.height
  @image = image
end

Instance Attribute Details

#colorTypeObject

Returns the value of attribute colorType.



14
15
16
# File 'lib/fractal.rb', line 14

def colorType
  @colorType
end

Instance Method Details

#calculate(a, b, c_arr) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/fractal.rb', line 21

def calculate a, b, c_arr
  ca, cb = c_arr
  left = a * a - b * b
  right = 2 * a * b
  a = left  + ca
  b = right + cb

  return [a, b]
end

#draw(definition = 255, scale = 2.0) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/fractal.rb', line 31

def draw definition=255, scale=2.0
  scaleWidth  = scale
  scaleHeight = scale.to_f * (@height.to_f / @width.to_f)
  definition = definition.to_f
  (0..@width - 1).each do |x|
    (0..@height - 1).each do |y|
      a = ca = drag(x, 0, @width,  -scaleWidth, scaleWidth)
      b = cb = drag(y, 0, @height, -scaleHeight, scaleHeight)

      snap = 0
      while snap < definition
        a, b = calculate(a, b, [ca, cb])
        if a * a + b * b > 16
          break
        end
        snap += 1
      end

      case @colorType
      when 'multichromatic', 'multi', 'rainbow'
        brightness = 1
        brightness = 0 if snap == definition
        hue = drag(snap, 0, definition, 0, 1)
        hue = drag(Math.sqrt(hue), 0, 1, 0, 360)

        @image[x, y] = ChunkyPNG::Color.from_hsv hue, 1, brightness
      else
        shade = drag(snap, 0, definition, 0, 1)
        shade = drag(Math.sqrt(shade), 0, 1, 0, 255)
        r, g, b = [shade.round.to_i] * 3

        @image[x, y] = ChunkyPNG::Color.rgb r, g, b
      end
    end
  end
  return @image
end