#!/usr/bin/perl
# Copyright (C) 2006 by Moritz Andreas Lenz, http://moritz.faui2k3.org/
# This is free Software. You may use, modify, redistribute... it 
# under the terms of the WTFPL: http://sam.zoy.org/wtfpl/
#
# Use it at your own Risk

use warnings;
use strict;
use GD;


my $width = 1024;
my $edges = 5;
my $height = $width;

foreach $edges (3 .. 9){
	my $im = new GD::Image($width,$height);
	my $black = $im->colorAllocate(0, 0, 0);
	my $white = $im->colorAllocate(255, 255, 255);
	$im->fill(1, 1, $white);

	my @x;
	my @y;

	for (my $i = 0; $i < $edges; $i++){
		$x[$i] = int $width/2 * (1-sin($i * (2*3.14159) / $edges));
		$y[$i] = int $height/2 * (1-cos($i * (2*3.14159) / $edges));
	}

	for (my $i = 0; $i < $edges; $i++){
		$im->line($x[$i], $y[$i], $x[($i+1)%$edges], $y[($i+1)%$edges], $black);
	}

	my $x = $width * rand();
	my $y = $height * rand();

	for (0 .. 500000 * $edges * $edges * $edges){
		my $i = int ($edges*rand());
		$x = .5*($x + $x[$i]);
		$y = .5*($y + $y[$i]);
		$im->setPixel(int $x, int $y, $black);
	}

	my $fn = sprintf("sierpinski-%02d.png", $edges);

	open(OUT, ">", $fn) or die "$0: can't write to file '$fn': $!";
	print "Writing file $fn\n";

	binmode OUT;
	print OUT $im->png;
	close OUT;
}
