#!/usr/bin/perl
#
# Matthew Lewis, 2003
# http://www.accad.ohio-state.edu/~mlewis
#
# convert c3d text mocap files into a VRML wrl representation
# print to stdout
#
if ($#ARGV != 0) {
    print "usage: mocaptxt2wrl in.txt\n";
    exit;
}

$txtfn = $ARGV[0];

# open txt file
open(TXT,"<$txtfn");

# parse special first line, pop off first two words: "Field Time"
# create entries in "data" for this first line's names
chop($line = <TXT>);
$line =~ s/\s+/ /g;
@names = split / /, $line;
$junk = shift @names; # "Field"
$junk = shift @names; # "Time"

# read frames
$nframes = 0;
$time = 0;
while ($line = <TXT>) {
    if($line =~ /\S/) {   # if some non-white space on line
	chop $line;
	$line =~ s/\s+/ /g;
	@p = split / /, $line;
	$f = shift @p; # frame number
	$time = shift @p; # time
	push @frames, [ @p ];
	++$nframes;
    }
}

close TXT;

########################################
# write timer

# hard code time here in an emergency
# if(!$time) { $time = 41.175; }

print <<EOF
#VRML V2.0 utf8

Viewpoint { position 0 1 10 }
NavigationInfo { type "EXAMINE" }
Background { skyColor 1 1 1 }

DEF TIMER TimeSensor {
   loop TRUE
   cycleInterval $time
}

# floor
#Shape {
#    appearance Appearance { material Material {diffuseColor .75 .75 .75 } }
#    geometry Box { size 4 .1 4 }
#}

Switch {
   choice [
    DEF MARKER Shape {
       appearance Appearance { material Material {diffuseColor .75 .75 .75 } }
       geometry IndexedFaceSet {
          coord Coordinate { point [ .075 .075 .075, -.075 .075 .075, 
	   -.075 .075 -.075, .075 .075 -.075, .075 -.075 .075, -.075 -.075 .075, 
	   -.075 -.075 -.075, .075 -.075 -.075 ] }
          coordIndex [ 3 2 1 0 -1, 0 4 7 3 -1, 3 7 6 2 -1, 
           2 6 5 1 -1, 1 5 4 0 -1, 4 5 6 7 -1 ]
       }
    }
   ]
}

Transform { translation 0 0 0
children [
EOF
;

# write markers
for ($i=0; $i<@names; $i+=3) {    
    $names[$i] =~ /([^\: ]+)\:\w$/;
#    $names[$i] =~ /([^\:]+)\:([^\: ]+)\:\w$/;
    $name = $1;
    print "DEF $name Transform {children[USE MARKER]}\n";
}

print "]}\n";  # close outer transform

for ($i=0; $i<@names; $i+=3) {    
    $names[$i] =~ /([^\: ]+)\:\w$/;
    $name = $1;
    #write interpolators
    print "DEF pi_$name PositionInterpolator {";
    print "key [ ";

    foreach $j (0..($nframes-1)) {
	$key = $j/($nframes-1);
	$key = int($key*10000)/10000;
	print "$key ";
    }

    print "\n]\n";    
    print "keyValue [\n";    
    foreach $frame (0..($nframes-1)) {
	$x = $frames[$frame][$i]*0.0017;
	$y = $frames[$frame][$i+2]*0.0017;
	$z = $frames[$frame][$i+1]*0.0017;
	print "$x $y $z ";
    }
    print "]}\n";
}

for ($i=0; $i<@names; $i+=3) {    
    $names[$i] =~ /([^\: ]+)\:\w$/;
    $name = $1;
    print "ROUTE TIMER.fraction_changed TO pi_$name.set_fraction\n";
    print "ROUTE pi_$name.value_changed TO $name.translation\n";
}



########################################
########################################
