// Copyright (C) 1997-2004 Alias Systems Corp.
// 
// The information in this file is provided for the exclusive use of the
// licensees of Alias.  Such users have the right to use, modify,
// and incorporate this code into other products for purposes authorized
// by the Alias license agreement, without fee.
// 
// ALIAS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
// INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
// EVENT SHALL ALIAS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
// DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

//  Alias Script File
//  MODIFY THIS AT YOUR OWN RISK
//
//  Creation Date:  12 March, 1999
//
//  Description:
//      Functions called from "Subdiv Create".
//


//
//  Procedure Name:
//      doSubdivCreate
//
//  Description:
//		This is the actual function that gets called from "Subdiv Create" 
//      option box.
//
//  Input Arguments:
//	    $version: The version of this option box.  This is used to know how to 
//	              interpret the $args array.
//      $args:
//      If Version 1:
//      [0]  $origObjectAction:  what to do with the original object
//                               options are: replace, hide, or show it
//      If Version 2:
//      [1]  $globalHist:        global construction history setting
//
//      [2]  $maxPolys:          max polys that can be converted (if creating
//                               from poly
//
//      [3]  $maxEdgesPerVert:   max edges per vertex of a polymesh that
//                               can be handled
//                               
//
//  Return Value:
//      None.
//
//  Note:
//
global proc int doSubdivCreate( string $version, string $args[] )
{
	int $status = 0;
	int $versionNum = $version;

	if ($versionNum == 1 && size($args) != 1){
		error("Incorrect number of arguments for doSubdivCreate.");
		return $status;
	}

	if ($versionNum == 2 && size($args) < 4){
		error("Incorrect number of arguments for doSubdivCreate.");
		return $status;
	}

	if ($versionNum == 3 && size($args) < 5){
		error("Incorrect number of arguments for doSubdivCreate.");
		return $status;
	}

	int $origObjectAction = $args[0];
	int $globalHist       = ($versionNum >= 2 ? $args[1] : 0);
	int $maxPolys         = ($versionNum >= 2 ? $args[2] : 1000); 
	int $maxEdgesPerVert  = ($versionNum >= 2 ? $args[3] : 32);
	int $ap  = ($versionNum >= 3 ? $args[4] : 0);

	// extract all poly meshes
	string $polyList[] = `filterExpand -ex true -fp true -sm 12`; 
	int    $polyLen = size($polyList);

	// extract all nurbs
	string $nurbsList[] = `filterExpand -ex true -fp true -sm 10`; 
	int    $nurbsLen = size($nurbsList);

	int    $len = $polyLen + $nurbsLen;

	if ($len == 0) {
	  error ("Select a polygon or a NURBS surface " +
			 "from which you want to create a subdivision surface.");
  	  return $status;
	}

	string $polyCmd = "polyToSubdiv -ap " + $ap + " ";
	string $nurbsCmd = "nurbsToSubdiv -rn false -mp true ";

	// set up commands with appropriate options
	//
	switch ($origObjectAction) {
	  case 0:
	  case 1:
		// replace original object, forces history off, but delete
		// will take care of that...
		$polyCmd = $polyCmd + "-ch off -aut on ";
		$nurbsCmd = $nurbsCmd + "-ch off -aut on ";
		break;

	  case 2:
		// forces history on
		$polyCmd = $polyCmd + "-ch on -aut on ";
		$nurbsCmd = $nurbsCmd + "-ch on -aut on ";
		if( !$globalHist ) {
			warning( "Forcing construction history to on." );
		}
		break;

	  case 3:
		// show original object, respects global construction history
		$polyCmd = $polyCmd + "-ch 0 -aut off ";
		$nurbsCmd = $nurbsCmd + "-ch 0 -aut off ";
		break;
	}

	$polyCmd  += (" -maxPolyCount " + $maxPolys + " ");
	$polyCmd  += (" -maxEdgesPerVert " + $maxEdgesPerVert + " ");

	// nurbs uses max polys as well
	//
	$nurbsCmd  += (" -maxPolyCount " + $maxPolys + " ");

	// Create
	string $selList = "";
  	string $polyRes[];
  	string $nurbsRes[];
  	int    $retVal;

	//  Convert each polymesh, one at a time so we can catch errors
	//
	for($i = 0; $i < $polyLen; $i++) {
		int $smart = 1;
		if ($smart) {
			string $pruneCmd = "deleteInternalValence2Verts "+$polyList[$i]+";\n";
			$pruneCmd = $pruneCmd + $polyCmd + $polyList[$i];
			$retVal = catch ($polyRes = evalEcho($pruneCmd));
		} else {
			$retVal = catch ($polyRes = evalEcho ($polyCmd + $polyList[$i]));
		}
		
		// if there's no error, do post work and add results 
		if ($retVal != 1){
			switch ($origObjectAction){
			  case 0:
			  case 1:
				string $polyParents[] = `listRelatives -allParents $polyList[$i]`;
				if( size($polyParents) <= 1 ) {
					// delete original only if original poly has only one
					// parent. 
					//
					evalEcho ("delete "  + $polyList[$i]);
				}
				else {
					// If original poly has more than one original, remove
					// the shape as a child of the selected transform using
					// the parent command - fix for bug #150166.
					//
					evalEcho ("parent -removeObject -shape " + $polyList[$i]);
				}
				// Since "$polyRes" is being filled in the "for" loop, the
				// first entry is the entry of interest for every iteration.
				//
				string $parent[] = `listRelatives -parent $polyRes[0]`;
				rename $parent[0] polyToSubd1;
				break;

			  case 2:
				// disconnect the shader:
				string $shade[] = `listConnections -p 1 ($polyList[$i] + ".iog")`;
				int $nShade = size($shade);
				int $j;
				for( $j=0; $j<$nShade; $j+=1 ) {
					disconnectAttr ($polyList[$i] + ".iog") $shade[$j];
				}
				//
				// When creating the subd and keeping the original,
				// we want the new subd shape to be the first child, so
				// its menu will appear on RMB.
				reorder -f $polyRes[$i];
				break;

			  case 3:
			  default:
				break;
			}

			for ($s in $polyRes) {
				$selList += ($s + " ");
			}
		}
	}

	//  Convert each nurbs, one at a time so we can catch errors
	//
	for($i = 0; $i < $nurbsLen; $i++) {
		$retVal = catch ($nurbsRes = evalEcho ($nurbsCmd + $nurbsList[$i]));

		// if there's no error, do post work and add results 
		if ($retVal != 1){
			switch ($origObjectAction){
			  case 0:
			  case 1:
				string $nurbsParents[] = `listRelatives -allParents $nurbsList[$i]`;
				if( size($nurbsParents) <= 1 ) {
					// delete original only if original nurbs has only one
					// parent. 
					//
					evalEcho ("delete "  + $nurbsList[$i]);
				}
				else {
					// If original nurbs has more than one original, remove
					// the shape as a child of the selected transform using
					// the parent command - fix for bug #150166.
					//
					evalEcho ("parent -removeObject -shape " + $nurbsList[$i]);
				}
				// Since "$nurbsRes" is being filled in the "for" loop, the
				// first entry is the entry of interest for every iteration.
				//
				string $parent[] = `listRelatives -parent $nurbsRes[0]`;
				rename $parent[0] nurbsToSubd1;
				break;
			  case 2:
				break;
			  case 3:
			  default:
				break;
			}

			for ($s in $nurbsRes) {
				$selList += ($s + " ");
			}
		}
	}

	// In case our new subdiv shapes have no shader,
	// assign them to the default initialShadingGroup.
	// This can happen if users delete the subdiv shape
	// while in polygon-proxy mode, and then create a new
	// subdiv from the polygon-proxy.
	//
	// It's easier to work with an array of results...
	//
	string  $results[];
	string  $r;
	if( size( $selList ) > 0 ) {
		tokenize( $selList, " ", $results );
	}

	for( $r in $results ) {
		subdAssignDefaultShader( $r );
	}

	if (size($selList) > 0){
  		$selList += ";";
		eval ("select -r " + $selList);
	}

	return $status;
}


