#--------------------
# Mandelbrot set viewer in TrafficScript.
#
# This rule is split into two distinct parts. The first half generates the
# HTML for the page, and the second half calculates the colour of each
# individual image on the page.
$path = http.getPath();
if( $path == "/" ) {
# Generating the HTML for the page
$rows = 150.0;
$columns = 150.0;
# Get the area of the mandelbrot set to view
$minx = http.getFormParam( "minx" );
$miny = http.getFormParam( "miny" );
$maxx = http.getFormParam( "maxx" );
$maxy = http.getFormParam( "maxy" );
if( $minx == "" ) $minx = -2.5;
if( $miny == "" ) $miny = -2.0;
if( $maxx == "" ) $maxx = 1.5;
if( $maxy == "" ) $maxy = 2.0;
$minx = lang.toDouble( $minx );
$miny = lang.toDouble( $miny );
$maxx = lang.toDouble( $maxx );
$maxy = lang.toDouble( $maxy );
$width = $maxx - $minx;
$height = $maxy - $miny;
$magf = 4.0;
$stepx = $width / $columns;
$stepy = $height / $rows;
# Build up the initial web page
$page = "
Mandlebrot"
. ""
. "\n"
. "Zoom back out
";
# Scan each row
$yval = $maxy;
while( $yval > $miny ) {
# Build each row separately, and append them one at a time to the
# main $page string, as this is more efficient
$line = "";
# Zoom parameters
$nminy = $yval - $height / $magf;
$nmaxy = $yval + $height / $magf;
$aref = "" . "
";
$xval = $xval + $stepx;
}
$page = $page . $line . "
";
$yval = $yval - $stepy;
}
$page = $page . "\n";
http.sendResponse( "200 OK", "text/html", $page, "" );
} else if( $path == "/s.gif" ) {
# Calculating the colour of one particular area of the mandelbrot.
# Maximum number of iterations before we drop out
$maxiter = 256;
# real and imaginary components of c, based on the co-ordinates
$cr = lang.toDouble( http.getFormParam( "x" ));
$ci = lang.toDouble( http.getFormParam( "y" ));
$zr = 0.0;
$zc = 0.0;
# The main loop. It calculates z=z*z+c, and loops until z*z >= 2
$n = $maxiter;
while( $n > 0 ) {
$zrs = $zr * $zr;
$zis = $zi * $zi;
if(( $zrs + $zis ) >= 4.0 ) break;
$zi = 2 * $zr * $zi + $ci;
$zr = $zrs - $zis + $cr;
$n = $n - 1;
}
$p = lang.toDouble( $maxiter )/4.0;
$g = 128*(math.sin( ($maxiter-$n)*2.0*3.14/$p )+1);
$r = 128*(math.sin( ($maxiter-$n)*2.0*3.14/$p + 2.0*3.14/3.0 )+1);
$b = 128*(math.sin( ($maxiter-$n)*2.0*3.14/$p + 4.0*3.14/3.0 )+1);
$s = ($n)/lang.toDouble( $maxiter );
$s = $s*$s*$s*$s;
$r = $r * $s;
$g = $g * $s;
$b = $b * $s;
# An 8x8 GIF, completely black
$image = string.hexDecode(
"47494638376108000800800100000000ffffff2c".
"0000000008000800000207848fa9cbed5d00003b" );
$image = string.replaceBytes( $image, lang.chr( $r ), 13 );
$image = string.replaceBytes( $image, lang.chr( $g ), 14 );
$image = string.replaceBytes( $image, lang.chr( $b ), 15 );
http.sendResponse( "200 OK", "image/gif", $image, "" );
}