// Copyright 2009 futomi  http://www.html5.jp/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Mandelbrot_set.js v1.0.0

(function () {

onmessage = function(e) {
	//var p = JSON.parse(e.data);
	var p = eval("(" + e.data + ")");
	var data = [];
	for( var x=0; x<p.w; x++ ) {
		for( var y=0; y<p.h; y++ ) {
			_add_pixel(p, data, x, y);
		}
	}
	postMessage(data.join("\t"));
};

var _add_pixel = function(p, data, x, y) {
	// calculate the complex value (a, b) from the point(x, y) in the coordinate space of the canvas.
	var a = p.a + x * p.pixel;
	var b = p.b + y * p.pixel;
	// calculate whether this complex value is bounded.
	var bp = _is_bounded(p, a, b);
	var iteration = bp[0];
	var a = bp[1];
	var b = bp[2];
	// color
	var color = _get_color(p, iteration, a, b);
	// add the pixel data into the imagedata object.
	var idx = (p.w * y + x) * 4;
	var ary = [color.r, color.g, color.b, 255];
	for( var i=0; i<4; i++ ) {
		data[idx+i] = ary[i];
	}
};

var _is_bounded = function(p, a0, b0) {
	var iteration = 0;
	var a = 0;
	var b = 0;
	while ( a*a + b*b <= 4 && iteration < p.max_iteration ) {
		var atemp = a*a - b*b + a0;
		b = 2*a*b + b0;
		a = atemp;
		iteration ++;
	}
	if( iteration == p.max_iteration ) {
		return [0, a, b];
	} else {
		return [iteration, a, b];
	}
};

var _get_color = function(p, n) {
	return p.colors[ n % 256 ];
};

})();

