#!/usr/bin/php
<?php

/*
	(C)2009 by Tom Vogt <tom@lemuria.org>
	
	licensed under the GPL License version 3 or later, see http://www.gnu.org/licenses/gpl-3.0.html
	
	This script shows how easy it is to modify arbitrary values within a .tgd file using PHP's
	built-in XML parsing. In this version, the script moves the camera along a linear path
	that you define as x/y/z increments. But you can modify the script to change other values,
	as many as you like.
	

	Parameters:
		-f			file to render (required)
		-n			number of steps (required)
		-x		\
		-y		 | value to add to position each frame (all optional, but set at least one)
		-z		/
*/

function newname($file, $tag) {
	$myfile = basename($file);
	$nameonly = substr($myfile,0,-strlen(strrchr($myfile, '.')));
	return dirname($file).'/'.$nameonly."-$tag.tgd";
}

$options = getopt("f:n:x::y::z::");
if (!isset($options['f'])) {
	echo "File to render (-f) required.\n";
	exit;
}
$file=$options['f'];
if (!file_exists($file)) {
	echo "File $file doesn't exist.\n";
	exit;
}
if (!isset($options['n'])) {
	echo "Number of steps (-n) required.\n";
	exit;
}
if (isset($options['x'])) $x=$options['x']; else $x=0;
if (isset($options['y'])) $y=$options['y']; else $y=0;
if (isset($options['z'])) $z=$options['z']; else $z=0;
print("$x - $y - $z\n");

for ($i=0; $i<$options['n']; $i++) {

	echo "rendering frame $i\n";

	$dom = DOMDocument::load($file);

	$renders = $dom->getElementsByTagName('render');
	foreach ($renders as $render) {
		$master = $render->getAttribute('master');
		if ($master) {
			$cam = $render->getAttribute('camera');
			$cameras = $dom->getElementsByTagName('camera');
			foreach ($cameras as $camera) {
				if ($camera->getAttribute('name')==$cam) {
					// now set position 
					$pos = $camera->getAttribute('position');
					$coords = explode(" ", $pos);
					$coords[0]+=$x*$i; $coords[1]+=$y*$i; $coords[2]+=$z*$i;
					$newpos = "$coords[0] $coords[1] $coords[2]";
					$camera->setAttribute('position', $newpos);
				}
			}
		}
	}

	$fname = newname($file, $i);
	file_put_contents($fname, $dom->saveXML());

	// now render it...
	$target = substr($fname,0,-strlen(strrchr($fname, '.'))).'.exr';
	
	$command = 'tgdcli -p "'.$fname.'" -exit -r -o "'.$target.'"';
	passthru($command);
	
	unlink($fname); // cleanup
}
echo "\n";

?>
