# require "complex"
require 'phi'; include Phi
require "mandel"

DefaultMaxDepth = 50
DefaultSX = -2.25
DefaultSY = 1.75
DefaultEX = 1.25
DefaultEY = -1.75
Width = 100 # form.width
Height = 100 # form.height

def reset
  $max_depth = DefaultMaxDepth
  $s_re = DefaultSX
  $s_im = DefaultSY
  $e_re = DefaultEX
  $e_im = DefaultEY
  $dx = ($e_re - $s_re).abs / Width # ”{—¦
  $dy = ($e_im - $s_im).abs / Height # ”{—¦
end


def zoom(a, b, c, d)
p :zoom
  center_x = (a + c) / 2
  center_y = (b + d) / 2
  size = (c - a).abs
  size = (d - b).abs if (size < (d - b).abs)
  size = 1 if (size < 1)
  zoom_rate = ((Width + Height) / 2).to_f / size
  $max_depth = ($max_depth.to_f * Math.sqrt(Math.sqrt(Math.sqrt(zoom_rate)))).to_i

  move_x_rate = (center_x - (Width / 2)).to_f / (Width / 2)
  move_y_rate = (center_y - (Height / 2)).to_f / (Height / 2)

  center_re = ($s_re + $e_re) / 2
  center_im = ($s_im + $e_im) / 2
  c_size_re = ($e_re - $s_re).abs
  c_size_im = ($e_im - $s_im).abs

  center_re = center_re + (move_x_rate * (c_size_re / 2))
  center_im = center_im - (move_y_rate * (c_size_im / 2))

  $s_re = center_re - ((c_size_re / 2) / zoom_rate)
  $s_im = center_im + ((c_size_im / 2) / zoom_rate)
  $e_re = center_re + ((c_size_re / 2) / zoom_rate)
  $e_im = center_im - ((c_size_im / 2) / zoom_rate)

  $dx = ($e_re - $s_re).abs / Width
  $dy = ($e_im - $s_im).abs / Height
end

require 'drb'
DRb.start_service

if ARGV.empty? then ARGV.push '3000' end

$mc = ARGV.map{|host_port|
  DRbObject.new(nil, "druby://#{host_port}")
}
$mc_width = Width/$mc.size

def mandel
  th_list = []
  $mc.each_with_index do |mc,n|
    th_list.push(Thread.new {
#     (n*$mc_width).upto((n+1)*$mc_width-1) do |x|
      n.step(Width,$mc.size) do |x|
        mc.mandel(x,Height,$s_re,$s_im,$dx,$dy,$max_depth).
          each_with_index {|depth,y| canvas[x,y] = depth }
      end
    })
  end
  th_list.each{|th| th.join }
end

reset()
$calc_y = StartCalcY = 0
$calc_on = true

def clear
  $calc_y = StartCalcY
end

$start_x = $start_y = 0
$current_rect = nil



form = Component._load open('amandel.afm', 'rb').read

pbox = PaintBox.new form
pbox.align = AL_CLIENT

def pbox.on_paint
  canvas.pen.color = 0x00ffffff
  canvas.ellipse(50,50,100,100)
  canvas.poly_bezier(0,100,80,60,100,200,320,100)
  mandel
end
def pbox.on_mouse_down(btn,sft,x,y)
  $x=x
  $y=y
end
def pbox.on_mouse_up(btn,sft,x,y)
  hide
  zoom($x,$y,x,y)
  show
end
form.show
Phi.mainloop
