User:Gustavb/regular polygon.pl

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search

Usage[edit]

$ perl regular_polygon.pl number_of_edges

Source[edit]

#!/usr/bin/perl

# Command line argument
$n = $ARGV[0];

# Presentation parameters
$dim = 400;
$vdim = 200;
$margin = 4;
$stroke = 2.5;

# Constants 
$pi = 3.14159265358979323846264338327950288419717;

@names_special = 
    ('', '', '', 'triangle', 'quadrilateral', 'pentagon', 'hexagon', 
     'heptagon', 'octagon', 'nonagon', 'decagon', 'hendecagon', 
     'dodecagon', 'tridecagon', 'tetradecagon', 'pentadecagon', 
     'hexadecagon', 'heptadecagon', 'octadecagon', 'enneadecagon');

@names_tens = 
    ('', 'deca', 'icosa', 'triaconta', 'tetraconta', 'pentaconta', 
     'hexaconta', 'heptaconta', 'octaconta', 'enneaconta');

@names_ones = 
    ('', 'hena', 'di', 'tri', 'tetra', 'penta', 'hexa', 'hepta', 
     'octa', 'ennea');

# Derived meassures
$d = 2*$pi/$n;
$a = ($pi - $d) / 2;
$r = $vdim/2 - $margin;
$o = $r + $margin;

# Determine max/min y-coordinate in order to center polygon
$min_y = $max_y = 0;
for($v=$a; $v<2*$pi+$a; $v+=$d) {
    $y = sin($v);
    if($y < $min_y) { $min_y = $y; }
    if($y > $max_y) { $max_y = $y; }
}
$o_y = $o - ($r/2)*($max_y + $min_y);

# Determine polygon name
if($n < 20) { $name = $names_special[$n]; }
else {
    $name = $names_tens[$n/10];
    if ($n%10 != 0) { $name .= "kai".$names_ones[$n%10]; }
    $name .= "gon";
}
$name = "Regular_$name.svg";

# Write SVG
open(FD, "> $name");

print FD <<ENDL;
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
ENDL

print FD '  <svg width="'.$dim.'px" height="'.$dim.'px" viewBox="0 0 '.$vdim.' '.$vdim.'"'."\n";
print FD '       xmlns="http://www.w3.org/2000/svg" version="1.1">'."\n";
print FD '    <polygon style="fill:none;stroke:#000000;stroke-width:'.$stroke.'px"'."\n";
print FD '             points="';


for($v=$a; $v<2*$pi+$a-$d; $v+=$d) {
    $x = $o + $r*cos($v); $y = $o_y + $r*sin($v);
    print FD $x . "," . $y . " ";
}

$v+=d; $x = $o + $r*cos($v); $y = $o_y + $r*sin($v);
print FD $x . "," . $y.'" />'."\n";
print FD '</svg>'."\n";

close FD;