#! /bin/csh -f -e
# Last edited on 2008-01-13 00:59:38 by stolfi

set usage = "$0 [ -size WD HT ] [ -quick ] [ -duals ] [ -rot "RX,RY,RZ" ] [ -filter N.N ] infile"

set rot = "0,0,0"
set width = 320
set height = 240
set filter = 0.80
set rays = 2
set dualfilter = ( "|" top-remove-dual-edges )

set povbin = "${STOLFIHOME}/pkg/povray-3.1a-1/PUB/${PLATFORM}/bin"

while ( ( $#argv >= 1 ) && ( "x$1" =~ x-* ) )
  if ( ( $#argv >= 1 ) && ( "x$1" == "x-duals" ) ) then
    set dualfilter = ( )
    shift
  else if ( ( $#argv >= 1 ) && ( "x$1" == "x-quick" ) ) then
    set rays = 1 
    shift
  else if ( ( $#argv >= 2 ) && ( "x$1" == "x-filter" ) ) then
    set filter = $2
    shift; shift
  else if ( ( $#argv >= 2 ) && ( "x$1" == "x-rot" ) ) then
    set rot = $2
    shift; shift
  else if ( ( $#argv >= 3 ) && ( "x$1" == "x-size" ) ) then
    set width = $2
    set height = $3
    shift; shift; shift
  else
    echo "unrecognized option $1"; exit 1
  endif
end

if ( $#argv != 1 ) then
  echo "usage: ${usage}"; exit 1
endif

set name = "$1"; shift;
set name = "${name:r}"
set tempname = "/tmp/$$"

if ( ! ( -e ${name}.inc ) ) then
  echo "fixing up colors and radiuses in .top ..."
  cat ${name}.top \
    ${dualfilter} \
    | top-remove-huge-edges  > ${tempname}.top
  TriangToPOV \
    -inFile ${tempname} -outFile ${tempname}
  echo "making colors in ${name}.inc symbolic ..."
  cat ${tempname}.inc \
    | top-make-pov-colors-symbolic > ${name}.inc
  # /bin/rm ${tempname}.top
  /bin/rm ${tempname}.inc
endif

if ( ! ( -e top-pov-header.inc ) ) then
  ln -s ~/lib/top-pov-header.inc
endif

echo "creating ${name}.pov ..."

cat > ${name}.pov <<EOF
#declare facefilter = ${filter}
#include "top-pov-header.inc"
union{
#include "${name}.inc"
rotate <${rot}>
}
EOF

echo "running POVRAY on ${name}.pov ..."
nice \
  ${povbin}/povray \
    +I${name}.pov +O${name}.ppm \
    +A0.0 +R${rays} +FP +H${height} +W${width} \
    +Linclude

echo "converting ${name}.ppm to ${name}.png ..."
linear-ppm-to-png < ${name}.ppm > ${name}.png

xv ${name}.png ${name}.ppm &

