#!/bin/bash

set -e

make bulles2incc

source ./configuration.sh

set +e

POVOPT=" -d +q9 +a +W1280 +H1024 -v +WT2"
DDIR="frames/sculpt"
PASS=99
NBFRAMES=720

STDERR="WS/sculpt.stderr"
TMPIMG="/dev/shm/tmpsculpt2.png"
LAST="WS/sculpt.last"

if [ ! -r $LAST ] 
then
	echo 0 >  $LAST
fi


# ~/bin/read_obj sculpture.obj
# ./bub2inc.awk < bulles.vertices > vertices.incc
# ./bulles2incc
# ./edg2inc.awk < edges.values > edges.incc


for pass in $(seq 0 $PASS)
do

	idx=$(cat $LAST)
	next=$(( ( idx + 1 ) % NBFRAMES ))

	outfile=$(printf "%s/%04d.png" $DDIR $idx ) 
	printf "  %4d / %4d  =  %s\n" $pass $PASS $outfile

	povray -isculpture.pov -K${idx} $POVOPT -O${TMPIMG}  2> ${STDERR}
	error=$?
	# echo "ERRCODE" $error
	if [ $error -ne 0 ]
	then
		echo "+++++++++++++ EPICFAIL ++++++++++++++"
		tail ${STDERR}
		exit 1
	fi

	txt=$(printf "Konrad+tTh %3d" $idx )
 
	convert ${TMPIMG}				\
		-fill Black				\
		-pointsize 18				\
		-font ${TEXT_IT}			\
		-gravity South-West			\
		-annotate +30+5  "$txt"			\
		$outfile

	grep  'Trace Time' $STDERR	; echo

	echo $next > $LAST

	sleep   10

done

echo ; echo "Encoding mp4..."

ffmpeg  -nostdin                                                \
        -loglevel error                                         \
        -y -r 30 -f image2 -i $DDIR/%04d.png			\
	-metadata artist='---[ tTh ]---'			\
	-metadata title='* photogrammetry by Reep Reep *'	\
 	-preset veryslow					\
        -c:v libx264 -pix_fmt yuv420p                           \
        wtf2.mp4

sync
