Class: Fractals::Mandelbrot

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

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) ⇒ 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
# File 'lib/fractal.rb', line 31

def draw definition=255, scale=2
  scaleWidth  = scale.to_f
  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
      # TODO: Use colorType as option non-monochromatic images
      #       (allow colourful fractals), currently only greyscale
      shade = drag(snap, 0, definition, 0, 1)
      shade = drag(Math.sqrt(shade), 0, 1, 0, 255)

      colours = [shade.round.to_i] * 3
      hex = String.new
      colours.each { |component| hex << component.to_s(16) }
      @image[x, y] = ChunkyPNG::Color.from_hex hex
    end
  end
  return @image
end