#!/usr/bin/perl -w
use strict;

use Math::Vector::Real;

my $thick = 4;

my $small_dia = 20;
my $large_dia = 30;
my $slope_angle = 45;
my $jcurverad = 5;
my $tall = 50;

my $lin_len = 10;
my $lin2_len = 9;
my $sine_len = 8;
my $sine_height = 6;

my $ballend_xr = $thick/2;

my @i_sections = qw(ball0   6
		    sine0  10
		    lin0    2
		    circle 20
		    lin1    2
		    sine1  10
		    lin2    2
		    ball2   6);

my @j_sections = qw(lin0    2
		    !
		    curve1 10
		    |
		    curveE 5
		    |
		    curve2 10
		    |
		    );

sub point ($$) {
    my ($ip,$it, $jp,$jt) = @_;

    my ($i_offset, $i_outward);

    $i_outward = V( 0,
		  ($ip =~ m/0$/ ? -1 : +1),
		  0 );

    $i_thickscale = 1.0;

    if ($ip =~ m/^lin[01]$/) {
	$i_offset = V( $lin_len * ($ip =~ m/1/ ? $it : 1-$it),
		       0,
		       0 );
    } elsif ($ip =~ m/^circle$/) {
	$i_offset = V( 0,0,0 );
	$i_outward = V(  sin($it * TAU/2),
			 -cos($ip * TAU/2),
			 0 );
    } elsif ($ip =~ m/^lin2$/) {
	$i_offset = V( -$lin_len -$sine_len + $it*$lin2_len,
		       0,
		       +1 );
    } elsif ($ip =~ m/^sine[01]$/) {
	$i_offset = V( -$lin_len -$it*$sine_len,
		       0,
		       $sine_height * ( 0.5 - 0.5*cos( $it*TAU/2 ) )
		     );
    } elsif ($ip =~ m/^ball[02]$/) {
	my $angle = ($ip =~ m/0/ ? (1-$it) : $it) * TAU/4;
	$i_offset = V( -$lin_len -$sine_len
		       -($ip =~ m/2/ ? $lin2_len : 0)
		       -sin($angle) * $ballend_xr,
		       0,
		       +$sine_height;
		     );
    } else {
	die "$ip ?";
    }

    my $j_plus_th = $jp =~ m/2$/ ? $thick : 0;

    my $i_thick = $thick * $i_thickscale;
    my $j_p_x = $small_dia/2 + $thick;
    my $j_rs_x = $large_dia/2 + $thick;
    my $j_dqr_x = (1-cos($slope_angle)) * $jcurverad;
    my $j_q_x = $j_rs_x - $j_dqr_x;
    my $j_dpq = ($j_q_x - $j_p_x) / asin($slope_angle);
    my $j_p_y = 0;
    my $j_q_y = $j_p_y + $j_dpq * cos($slope_angle);
    my $j_r_y = $j_q_y + sin($slope_angle) * $jcurverad;
    my $j_s_y = $tall;
    my $j_qrc_x = $j_rs_x - $jcurverad;
    my $j_qrc_y = $j_r_y;

    if ($jp =~ m/^curveE$/) {
	my $angle = ($jt + 1) * TAU/2 - $slope_angle;
	$j_x = $j_p_x + $i_thick * cos($angle);
	$j_y = $j_p_y + $i_thick * sin($angle);
    } elsif ($jp =~ m/^curve[12]E$/) {
	my $angle = $slope_angle * ($jp =~ m/1/ ? $jt : (1-$jt));
	my $outwards = $jp =~ m/1/ ? -1 : +1;
	$j_x = $j_qrc_x + cos($angle) * ($jcurverad + $outwards * $i_thick);
	$j_y = $j_qrc_y + sin($angle) * ($jcurverad + $outwards * $i_thick);
    } elsif ($jp =~ m/^lin0$/) {
	$j_x = $j_rs_x + $i_thick * (-0.5 + 0.5 * jt);
	$j_y = $j_s_y;
    } else {
	die "$jp ?";
    }

    return
	$i_offset +
	$i_outward * $j_x +
	[0,0,1] * $j_y;
}
