Beispiel #1
0
//******************************************************************************
MString replaceFrameCookies( const MString &in, int frame )
{
    char fn[40];
    sprintf( fn, "%04d", frame );
    MStringArray array;
    in.split( '#', array );

    MString out = array[0];

    for( size_t i=1; i < array.length(); i++ )
    {
        out += fn;
        out += array[i];
    }

    return out;
}
//-----------------------------------------------------------------------------
// Changes any \'s to /'s in place and then splits on /
//-----------------------------------------------------------------------------
uint SplitPath(
	const MString &path,
	MStringArray &splitPath )
{
	char *pC( const_cast< char *>( path.asChar() ) );
	for ( const char *const pEnd( pC + path.length() ); pC != pEnd; ++pC )
	{
		if ( *pC == '\\' )
		{
			*pC = '/';
		}
	}

	splitPath.clear();
	path.split( '/', splitPath );

	return splitPath.length();
}
bool
atomImport::checkPlugAgainstTemplate(const MString& nodeName,
									 const MPlug& plug,
									 atomTemplateReader* templateReader)
{
	// Check if the plug is filtered out
	//
	if (NULL != templateReader) {
		// get long attribute name
		MString plugName = plug.partialName(true,false,false,false,false,true);
		MStringArray nameParts;
		plugName.split('.', nameParts);
		MString leafAttr = nameParts[nameParts.length()-1];
		return (templateReader->findNodeAndAttr(nodeName,leafAttr));
	}
	// No template, nothing to do
	//
	return true;
}
Beispiel #4
0
MString truncateName(const MString & in_Name)
{
   MString name = in_Name;
   MString trail = removeTrailFromName(name);
   if(name.substring(name.length()-3,name.length()-1).toLowerCase() == "xfo")
      name = name.substring(0,name.length()-4);
   else if(name.substring(name.length()-5,name.length()-1).toLowerCase() == "shape")
      name = name.substring(0,name.length()-6);

   // replace the name space
   MStringArray nameParts;
   name.split(':',nameParts);
   name = nameParts[0];
   for(unsigned int i=1;i<nameParts.length();i++)
   {
      name += ".";
      name += nameParts[i];
   }

   return name + trail;
}
MStatus CVsDmxIOTranslator::reader(
  const MFileObject &i_mFileObject,
  const MString &i_optionsString,
  const FileAccessMode i_fileAccessMode )
{
	MString cmd( "vsDmxIO -import" );

	if ( i_optionsString.length() )
	{
		MStringArray options;
		if ( !i_optionsString.split( ';', options ) )
		{
			merr << "Can't split " << s_name << " translator arguments" << std::endl;
			return MS::kFailure;
		}

		for ( unsigned oi( 0 ); oi < options.length(); ++oi )
		{
			MStringArray keyValue;
			if ( options[ oi ].split( '=', keyValue ) && keyValue.length() == 2 )
			{
				const MString &key( keyValue[ 0 ] );
				const MString &val( keyValue[ 1 ] );

				if ( key == "timeOffset" )
				{
					cmd += " -timeOffset ";
					cmd += val.asDouble();
					continue;
				}
			}	
		}
	}

	cmd += " -filename \"";
	cmd += i_mFileObject.fullName();
	cmd += "\";";

	return MGlobal::executeCommand( cmd, true, true );
}
Beispiel #6
0
MStatus OSGFileTranslator::writer( const MFileObject &file, const MString &optionsString,
                                   MPxFileTranslator::FileAccessMode mode )
{
	// Set Config ExportSelection Attribute
	if ( ( mode == MPxFileTranslator::kExportAccessMode ) || ( mode == MPxFileTranslator::kSaveAccessMode ) )
		Config::instance()->setExportSelection( false ) ;

	else if( mode == MPxFileTranslator::kExportActiveAccessMode )
		Config::instance()->setExportSelection( true ) ;

	// the first character in the optinsString is a ";", so get rid of it with substring
	MString			options = optionsString.substring( 1 , optionsString.length() -1 ) ;
	MStringArray	argStringArray ;

	std::cout << optionsString.asChar() ;

	// split the String with " " to get and option Array
	MStatus status = options.split( ' ' , argStringArray ) ;

	OSGWrite::parseArgs( argStringArray ) ;
	OSGWrite::exporta( file.expandedFullName() ) ;

	return MStatus::kSuccess;
}
MStatus CVsDmxIOTranslator::writer(
	const MFileObject &i_mFileObject,
	const MString &i_optionsString,
	const FileAccessMode i_fileAccessMode )
{
	MString cmd( "vsDmxIO -export" );

	if ( i_optionsString.length() )
	{
		bool useTimeline( true );
		double fs( MAnimControl::minTime().as( MTime::uiUnit() ) );
		double fe( MAnimControl::maxTime().as( MTime::uiUnit() ) );
		double fi( 1.0 );

		MStringArray options;
		if ( !i_optionsString.split( ';', options ) )
		{
			merr << "Can't split " << s_name << " translator arguments" << std::endl;
			return MS::kFailure;
		}

		for ( unsigned int oi( 0 ); oi != options.length(); ++oi )
		{
			MStringArray keyValue;
			if ( options[ oi ].split( '=', keyValue ) && keyValue.length() == 2 )
			{
				const MString &key( keyValue[ 0 ] );
				const MString &val( keyValue[ 1 ] );

				if ( key == "useTimeline" )
				{
					useTimeline = val.asInt() ? true : false;
					continue;
				}

				if ( !useTimeline )
				{
					if ( key == "fs" )
					{
						fs = val.asDouble();
						continue;
					}

					if ( key == "fe" )
					{
						fe = val.asDouble();
						continue;
					}

					if ( key == "fi" )
					{
						fi = val.asDouble();
						continue;
					}
				}
			}	
		}

		if ( !useTimeline )
		{
			if ( fs > fe )
			{
				merr << "Invalid frame start " << fs << " > frame end " << fe << ", ignoring and using timeline" << std::endl;
			}
			else
			{
				cmd += " -time \"";
				cmd += fs;
				cmd += "-";
				cmd += fe;
				if ( fi <= 0 )
				{
					mwarn << "Invalid frame increment " << fi << " specified, using 1" << std::endl;
				}
				else
				{
					cmd += "x";
					cmd += fi;
				}
				cmd += "\"";
			}
		}
	}

	if ( i_fileAccessMode == MPxFileTranslator::kExportActiveAccessMode )
	{
		cmd += " -selection";
	}

	cmd += " -filename \"";
	cmd += i_mFileObject.fullName();
	cmd += "\";";

	return MGlobal::executeCommand( cmd, true, true );
}
Beispiel #8
0
MStatus	parseShader(MObject &src, SXRShaderData& d)
{
	MStatus status;

	MFnSet fnSet( src, &status );
	if (status == MStatus::kFailure) {
		status.perror("Unable to lookup shader from set of shaders for object");
		return status;
	}

	MObject shaderNode = findShader(src,d);
	if (shaderNode == MObject::kNullObj)
		return (MStatus::kFailure);

	MPlug colorPlug = MFnDependencyNode(shaderNode).findPlug("color", &status);
	if (status == MStatus::kFailure)
		return (status);

	MItDependencyGraph dgIt(colorPlug, MFn::kFileTexture,
		MItDependencyGraph::kUpstream, 
		MItDependencyGraph::kBreadthFirst,
		MItDependencyGraph::kNodeLevel, 
		&status);

	if (status == MStatus::kFailure)
		return (status);

	dgIt.disablePruningOnFilter();

	// If no texture file node was found, just continue.
	//
	if (dgIt.isDone()) {
		//		cout << "no textures found for " << colorPlug.name() << "\n";
		return (MStatus::kSuccess);
	}

	// Print out the texture node name and texture file that it references.
	//
	MObject textureNode = dgIt.thisNode();
	MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
	MString textureName;
	filenamePlug.getValue(textureName);

	MStringArray rgFolders;

	if (strchr (textureName.asChar(), '\\')) 
	{
		textureName.split ('\\', rgFolders);
	} else {
		textureName.split ('/', rgFolders);
	}
	d.tex_name = rgFolders[rgFolders.length() -1];
	//	cout << "Found texture file: '" << filename.asChar() << "'\n";

	short index;
	//double side flag
	MPlug xrDoubleSidePlug= MFnDependencyNode(shaderNode).findPlug("xrayDoubleSide", &status);
	if (status == MS::kSuccess)
	{
		MFnEnumAttribute enm = xrDoubleSidePlug.attribute();
		if ((status == MS::kSuccess)&&(MS::kSuccess==xrDoubleSidePlug.getValue(index))) 
			d.double_side = index;
	}
	//engine
	MPlug xrEnginePlug= MFnDependencyNode(shaderNode).findPlug("xrayEngineShader", &status);
	if (status == MS::kSuccess)
	{
		MFnEnumAttribute enm = xrEnginePlug.attribute();

		if ((status == MS::kSuccess)&&(MS::kSuccess==xrEnginePlug.getValue(index))) 
			d.eng_name = enm.fieldName(index);
	}
	//compiler
	MPlug xrCompilerPlug = MFnDependencyNode(shaderNode).findPlug("xrayCompilerShader", &status);
	if (status == MS::kSuccess)
	{
		MFnEnumAttribute enm = xrCompilerPlug.attribute();
		if ((status == MS::kSuccess)&&(MS::kSuccess==xrCompilerPlug.getValue(index))) 
			d.comp_name = enm.fieldName(index);
	}
	//game material
	MPlug xrGameMaterialPlug = MFnDependencyNode(shaderNode).findPlug("xrayGameMaterial", &status);
	if (status == MS::kSuccess)
	{
		MFnEnumAttribute enm = xrGameMaterialPlug.attribute();
		if ((status == MS::kSuccess)&&(MS::kSuccess==xrGameMaterialPlug.getValue(index)))
			d.gmat_name = enm.fieldName(index);
	}

	return (MStatus::kSuccess);
}
MStatus atomImport::reader(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;

	MString fileName = file.fullName();
#if defined (OSMac_)	
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ifstream animFile(fname);
#else
	ifstream animFile(fileName.asChar());
#endif
	// 	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//

	if(animFile.good()==false)
		return status;
	MString pasteFlags;
	MString	prefix;
	MString	suffix;
	MString	search;
	MString	replace;
	MString	mapFile;
	bool replaceLayers = false;
	MString	exportEditsFile;	
	bool includeChildren = false;
	atomNodeNameReplacer::ReplaceType type = atomNodeNameReplacer::eHierarchy;
	MString templateName;
	MString viewName;
	bool useTemplate = false;

	if (options.length() > 0) {
		//	Set up the flags for the paste command.
		//
		const MString flagSrcTime("srcTime");
		const MString flagDstTime("dstTime");
		const MString flagOldDstTime("time");
		const MString flagCopies("copies");
		const MString flagOption("option");
		const MString flagConnect("connect");
		const MString flagMatch("match");
		const MString flagSearch("search");
		const MString flagReplace("replace");
		const MString flagPrefix("prefix");
		const MString flagSuffix("suffix");
		const MString flagMapFile("mapFile");
		const MString flagHierarchy("hierarchy");
		const MString flagString("string");
		const MString flagSelected("selected");
		const MString flagTemplate("template");
		const MString flagView("view");
		const MString optionChildrenToo("childrenToo");
		const MString optionTemplate("template");
		const MString flagExportEdits("exportEdits");
		MString copyValue;
		MString flagValue;
		MString connectValue;
		MString match;
		MString srcTimeValue;
		MString dstTimeValue;

		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {

			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagCopies && theOption.length() > 1) {
				copyValue = theOption[1];;
			} else if (theOption[0] == flagOption && theOption.length() > 1) {
				flagValue = theOption[1];
			} else if (theOption[0] == flagConnect && theOption.length() > 1) {
				if (theOption[1].asInt() != 0) {
					connectValue += theOption[1];
				}
			} 
			else if( theOption[0] == flagTemplate && theOption.length() > 1)
			{
				templateName = theOption[1];
			}
			else if( theOption[0] == flagView && theOption.length() > 1)
			{
				viewName = theOption[1];
			}
			else if (theOption[0] == flagSrcTime && theOption.length() > 1) {
				srcTimeValue += theOption[1];
			}
			else if ((theOption[0] == flagDstTime || theOption[0] == flagOldDstTime )&& theOption.length() > 1) {
				dstTimeValue += theOption[1];
			}
			else if (theOption[0] == flagMatch && theOption.length() > 1) {
				match =  theOption[1];
			} 
			else if (theOption[0] == flagSearch && theOption.length() > 1) {
				search =  theOption[1];
			} 
			else if (theOption[0] == flagReplace && theOption.length() > 1) {
				replace =  theOption[1];
			} 
			else if (theOption[0] == flagPrefix && theOption.length() > 1) {
				prefix =  theOption[1];
			} 
			else if (theOption[0] == flagSuffix && theOption.length() > 1) {
				suffix =  theOption[1];
			} 
			else if (theOption[0] == flagMapFile && theOption.length() > 1) {
				mapFile =  theOption[1];
			}
			else if (theOption[0] == flagSelected && theOption.length() > 1) {
				includeChildren =   (theOption[1] == optionChildrenToo) ? true : false;
				if(theOption[1] == optionTemplate)
					useTemplate = true;
			}
			else if (theOption[0] == flagExportEdits && theOption.length() > 1) {
				exportEditsFile =  theOption[1];
			}
		}
	
		if (copyValue.length() > 0) {
			pasteFlags += " -copies ";
			pasteFlags += copyValue;
			pasteFlags += " ";
		} 
		if (flagValue.length() > 0) {
			pasteFlags += " -option \"";
			pasteFlags += flagValue;
			pasteFlags += "\" ";
			if(flagValue == MString("replace"))
				replaceLayers = true;
		} 
		if (connectValue.length() > 0) {
			pasteFlags += " -connect ";
			pasteFlags += connectValue;
			pasteFlags += " ";
		} 
		if (dstTimeValue.length() > 0) {
			bool useQuotes = !dstTimeValue.isDouble();
			pasteFlags += " -time ";
			if (useQuotes) pasteFlags += "\"";
			pasteFlags +=  dstTimeValue;
			if (useQuotes) pasteFlags += "\"";
			pasteFlags += " ";
		} 		
		if (srcTimeValue.length() > 0) 
		{
			MTime lClipStartTime;
			MTime lClipEndTime;
			MStringArray lTimes;

			if ( MStatus::kSuccess == srcTimeValue.split( L':', lTimes ) )
			{
				if ( lTimes.length() > 0 )
				{
					double lImportStartFrame = lTimes[0].asDouble();
					double lImportEndFrame   = lImportStartFrame;
					
					if ( lTimes.length() > 1 )
					{
						lImportEndFrame = lTimes[1].asDouble();
					}
					fReader.setImportFrameRange( lImportStartFrame, lImportEndFrame );
				}
				else
				{
					fReader.clearImportFrameRange();
				}
			}
		} 
        else
        {
            fReader.clearImportFrameRange();
        }
		if(match.length() >0)
		{
			if(match == flagHierarchy)
				type = atomNodeNameReplacer::eHierarchy;
			else if(match == flagString)
				type = atomNodeNameReplacer::eSearchReplace;
			else if(match == flagMapFile)
				type = atomNodeNameReplacer::eMapFile;
		} //not set, then we leave what we had

		
	}

	//	If the selection list is empty, there is nothing to import.
	//
	MSelectionList sList;
	std::vector<unsigned int> depths;
	atomTemplateReader templateReader;
	if(useTemplate == true)
	{
		templateReader.setTemplate(templateName,viewName);
		includeChildren = false;
		templateReader.selectNodes(); //make the selection set be us.
	}
	SelectionGetter::getSelectedObjects(includeChildren,sList,depths);
	if (sList.isEmpty()) {
		MString msg = MStringResource::getString(kNothingSelected, status);
		MGlobal::displayError(msg);
		return (MS::kFailure);
	}


	atomNodeNameReplacer replacer(type,sList,depths,prefix,suffix,search,replace,mapFile);
	if (mode == kImportAccessMode) {
		status = importAnim(sList,animFile,pasteFlags,replacer,exportEditsFile,templateReader,replaceLayers);
	}

	animFile.close();
	return status;
}
    /** Parse the options String */
    void ImportOptions::set ( const MString& optionsString, MPxFileTranslator::FileAccessMode mode )
    {
        // Default option values
        mImportUpAxis = true;
        mImportUnits = true;
        mImportNormals = true;

        mHasError = false;

        /**
        * MPxFileTranslator::kUnknownAccessMode unknown file access mode
        * MPxFileTranslator::kReferenceAccessMode reference data into current scene
        * MPxFileTranslator::kImportAccessMode import data into current scene
        * MPxFileTranslator::kOpenAccessMode import data into new scene
        * MPxFileTranslator::kSaveAccessMode save data
        * MPxFileTranslator::kExportAccessMode export data
        * MPxFileTranslator::kExportActiveAccessMode export active (selected) data 
         */
        switch ( mode )
        {

        case MPxFileTranslator::kOpenAccessMode:
            mIsOpenCall = true;
            mIsReferenceCall = false;
            break;
#if MAYA_API_VERSION >= 650

        case MPxFileTranslator::kReferenceAccessMode:
            mIsOpenCall = false;
            mIsReferenceCall = true;
            break;
#endif

        case MPxFileTranslator::kImportAccessMode:
            mIsOpenCall = false;
            mIsReferenceCall = false;
            break;

        default:
            mIsOpenCall = false;
            break;
        }

        // Parse option String
        if ( optionsString.length() > 0 )
        {
            MStringArray optionList;
            optionsString.split ( ';', optionList );
            uint optionCount = optionList.length();

            for ( uint i = 0; i < optionCount; ++i )
            {
                MString& currentOption = optionList[i];

                // Process option name and values.
                MStringArray decomposedOption;
                currentOption.split ( '=', decomposedOption );
                MString& optionName = decomposedOption[0];

                // For boolean values, the value is assumed to be true if omitted.
                bool value = true;

                if ( decomposedOption.length() > 1 && decomposedOption[1] != "true" && decomposedOption[1] != "1" )
                {
                    value = false;
                }

                // Process options.
                if ( optionName == "importUpAxis" ) mImportUpAxis = value;
                else if ( optionName == "importUnits" ) mImportUnits = value;
                else if ( optionName == "importNormals" ) mImportNormals = value;
            }
        }
    }
Beispiel #11
0
	// Load material data
	MStatus Material::load(MFnDependencyNode* pShader,MStringArray& uvsets,ParamList& params)
	{
		MStatus stat;
		clear();
		//read material name, adding the requested prefix
		MString tmpStr = params.matPrefix;
		if (tmpStr != "")
			tmpStr += "/";
		tmpStr += pShader->name();
		MStringArray tmpStrArray;
		tmpStr.split(':',tmpStrArray);
		m_name = "";
		for (int i=0; i<tmpStrArray.length(); i++)
		{
			m_name += tmpStrArray[i];
			if (i < tmpStrArray.length()-1)
				m_name += "_";
		}

		//check if we want to export with lighting off option
		m_lightingOff = params.lightingOff;

		// GET MATERIAL DATA

		// Check material type
		if (pShader->object().hasFn(MFn::kPhong))
		{
			stat = loadPhong(pShader);
		}
		else if (pShader->object().hasFn(MFn::kBlinn))
		{
			stat = loadBlinn(pShader);
		}
		else if (pShader->object().hasFn(MFn::kLambert))
		{
			stat = loadLambert(pShader);
		}
		else if (pShader->object().hasFn(MFn::kPluginHwShaderNode))
		{
			stat = loadCgFxShader(pShader);
		}
		else
		{
			stat = loadSurfaceShader(pShader);
		}

		// Get textures data
		MPlugArray colorSrcPlugs;
		MPlugArray texSrcPlugs;
		MPlugArray placetexSrcPlugs;
		if (m_isTextured)
		{
			// Translate multiple textures if material is multitextured
			if (m_isMultiTextured)
			{
				// Get layered texture node
				MFnDependencyNode* pLayeredTexNode = NULL;
				if (m_type == MT_SURFACE_SHADER)
					pShader->findPlug("outColor").connectedTo(colorSrcPlugs,true,false);
				else
					pShader->findPlug("color").connectedTo(colorSrcPlugs,true,false);
				for (int i=0; i<colorSrcPlugs.length(); i++)
				{
					if (colorSrcPlugs[i].node().hasFn(MFn::kLayeredTexture))
					{
						pLayeredTexNode = new MFnDependencyNode(colorSrcPlugs[i].node());
						continue;
					}
				}

				// Get inputs to layered texture
				MPlug inputsPlug = pLayeredTexNode->findPlug("inputs");

				// Scan inputs and export textures
				for (int i=inputsPlug.numElements()-1; i>=0; i--)
				{
					MFnDependencyNode* pTextureNode = NULL;
					// Search for a connected texture
					inputsPlug[i].child(0).connectedTo(colorSrcPlugs,true,false);
					for (int j=0; j<colorSrcPlugs.length(); j++)
					{
						if (colorSrcPlugs[j].node().hasFn(MFn::kFileTexture))
						{
							pTextureNode = new MFnDependencyNode(colorSrcPlugs[j].node());
							continue;
						}
					}

					// Translate the texture if it was found
					if (pTextureNode)
					{
						// Get blend mode
						TexOpType opType;
						short bm;
						inputsPlug[i].child(2).getValue(bm);
						switch(bm)
						{				
						case 0:
							opType = TOT_REPLACE;
							break;
						case 1:
							opType = TOT_ALPHABLEND;
							break;				
						case 4:
							opType = TOT_ADD;
							break;
						case 6:
							opType = TOT_MODULATE;
							break;
						default:
							opType = TOT_MODULATE;
						}

						stat = loadTexture(pTextureNode,opType,uvsets,params);
						delete pTextureNode;
						if (MS::kSuccess != stat)
						{
							std::cout << "Error loading layered texture\n";
							std::cout.flush();
							delete pLayeredTexNode;
							return MS::kFailure;
						}
					}
				}
				if (pLayeredTexNode)
					delete pLayeredTexNode;
			}
			// Else translate the single texture
			else
			{
				// Get texture node
				MFnDependencyNode* pTextureNode = NULL;
				if (m_type == MT_SURFACE_SHADER)
					pShader->findPlug("outColor").connectedTo(colorSrcPlugs,true,false);
				else
					pShader->findPlug("color").connectedTo(colorSrcPlugs,true,false);
				for (int i=0; i<colorSrcPlugs.length(); i++)
				{
					if (colorSrcPlugs[i].node().hasFn(MFn::kFileTexture))
					{
						pTextureNode = new MFnDependencyNode(colorSrcPlugs[i].node());
						continue;
					}
				}
				if (pTextureNode)
				{
					TexOpType opType = TOT_MODULATE;
					stat = loadTexture(pTextureNode,opType,uvsets,params);
					delete pTextureNode;
					if (MS::kSuccess != stat)
					{
						std::cout << "Error loading texture\n";
						std::cout.flush();
						return MS::kFailure;
					}
				}
			}
		}

		return MS::kSuccess;
	}
Beispiel #12
0
//The writer simply goes gathers all objects from the scene.
//We will check if the object has a transform, if so, we will check
//if it's either a nurbsSphere, nurbsCone or nurbsCylinder.  If so,
//we will write it out.
MStatus LepTranslator::writer ( const MFileObject& file,
                                const MString& options,
                                MPxFileTranslator::FileAccessMode mode)
{
    MStatus status;
	bool showPositions = false;
    unsigned int  i;
    const MString fname = file.fullName();

    ofstream newf(fname.asChar(), ios::out);
    if (!newf) {
        // open failed
        cerr << fname << ": could not be opened for reading\n";
        return MS::kFailure;
    }
    newf.setf(ios::unitbuf);

    if (options.length() > 0) {
        // Start parsing.
        MStringArray optionList;
        MStringArray theOption;
        options.split(';', optionList);    // break out all the options.
        
        for( i = 0; i < optionList.length(); ++i ){
            theOption.clear();
            optionList[i].split( '=', theOption );
            if( theOption[0] == MString("showPositions") &&
                                                    theOption.length() > 1 ) {
                if( theOption[1].asInt() > 0 ){
                    showPositions = true;
                }else{
                    showPositions = false;
                }
            }
        }
    }

    // output our magic number
    newf << "<LEP>\n";

    MItDag dagIterator( MItDag::kBreadthFirst, MFn::kInvalid, &status);

    if ( !status) {
        status.perror ("Failure in DAG iterator setup");
        return MS::kFailure;
    }

    MSelectionList selection;
    MGlobal::getActiveSelectionList (selection);
    MItSelectionList selIterator (selection, MFn::kDagNode);

    bool done = false;
    while (true) 
    {
        MObject currentNode;
        switch (mode)
        {
            case MPxFileTranslator::kSaveAccessMode:
            case MPxFileTranslator::kExportAccessMode:
                if (dagIterator.isDone ())
                    done = true;
                else {
                    currentNode = dagIterator.item ();
                    dagIterator.next ();
                }
                break;
            case MPxFileTranslator::kExportActiveAccessMode:
                if (selIterator.isDone ())
                    done = true;
                else {
                    selIterator.getDependNode (currentNode);
                    selIterator.next ();
                }
                break;
            default:
                cerr << "Unrecognized write mode: " << mode << endl;
                break;
        }
        if (done)
            break;

        //We only care about nodes that are transforms
        MFnTransform dagNode(currentNode, &status);
        if ( status == MS::kSuccess ) 
        {
            MString nodeNameNoNamespace=MNamespace::stripNamespaceFromName(dagNode.name());
            for (i = 0; i < numPrimitives; ++i) {                
                if(nodeNameNoNamespace.indexW(primitiveStrings[i]) >= 0){
                    // This is a node we support
                    newf << primitiveCommands[i] << " -n " << nodeNameNoNamespace << endl;
                    if (showPositions) {
                        MVector pos;
                        pos = dagNode.getTranslation(MSpace::kObject);
                        newf << "move " << pos.x << " " << pos.y << " " << pos.z << endl;
                    }
                }
            }
        }//if (status == MS::kSuccess)
    }//while loop

    newf.close();
    return MS::kSuccess;
}
    // Parse the options String
    void ExportOptions::set ( const MString& optionsString )
    {
        // Reset everything to the default value
        mBakeTransforms = false;
        mRelativePaths = true;

        /** True, if the texture files should be copied to the destination folder. */
        mCopyTextures = false;
       
        mIsSampling = false;
        mCurveConstrainSampling = false;
        mRemoveStaticCurves = true;
        mExportCameraAsLookat = false;
        mExportTriangles = false;
        
        mExportPolygonMeshes = true;
        mExportLights = true;
        mExportCameras = true;
        mExportMaterialsOnly = false;
        mExportReferencedMaterials = true;
        mExportJointsAndSkin = true;
        mExportAnimations = true;
        mExportInvisibleNodes = false;
        mExportDefaultCameras = false;
        mExportNormals = true;
        mExportNormalsPerVertex = true;
        mExportTexCoords = true;
        mExportVertexColors = true;
        mExportVertexColorsPerVertex = true;
        mExportTangents = false;
        mExportTexTangents = false;
        mExportXRefs = true;
        mDereferenceXRefs = true;
        mCameraXFov = false;
        mCameraYFov = true;
        mDoublePrecision = false;
        mExportCgfxFileReferences = true;

        // Parse option String
        if ( optionsString.length() > 0 )
        {
            MStringArray optionList;
            optionsString.split ( ';', optionList );
            uint optionCount = optionList.length();

            for ( uint i = 0; i < optionCount; ++i )
            {
                MString& currentOption = optionList[i];

                // Process option name and values.
                MStringArray decomposedOption;
                currentOption.split ( '=', decomposedOption );
                MString& optionName = decomposedOption[0];

                // For boolean values, the value is assumed to be true
                // if omitted.
                bool value = true;

                if ( decomposedOption.length() > 1 &&
                        decomposedOption[1] != "true" &&
                        decomposedOption[1] != "1" )
                    value = false;

                // Process options.
                if ( optionName == "bakeTransforms" ) mBakeTransforms = value;
                else if ( optionName == "relativePaths" ) mRelativePaths = value;
                else if ( optionName == "exportTriangles" ) mExportTriangles = value;
                else if ( optionName == "cgfxFileReferences" ) mExportCgfxFileReferences = value;
                else if ( optionName == "copyTextures" ) mCopyTextures = value;
                else if ( optionName == "exportPolygonMeshes" ) mExportPolygonMeshes = value;
                else if ( optionName == "exportLights" ) mExportLights = value;
                else if ( optionName == "exportCameras" ) mExportCameras = value;
                else if ( optionName == "exportJointsAndSkin" ) mExportJointsAndSkin = value;
                else if ( optionName == "exportMaterialsOnly" ) mExportMaterialsOnly = value;
                else if ( optionName == "exportReferencedMaterials" ) mExportReferencedMaterials = value;
                else if ( optionName == "exportAnimations" ) mExportAnimations = value;
                else if ( optionName == "exportInvisibleNodes" ) mExportInvisibleNodes = value;
                else if ( optionName == "exportDefaultCameras" ) mExportDefaultCameras = value;
                else if ( optionName == "exportNormals" ) mExportNormals = value;
                else if ( optionName == "exportNormalsPerVertex" ) mExportNormalsPerVertex = value;
                else if ( optionName == "exportTexCoords" ) mExportTexCoords = value;
                else if ( optionName == "exportVertexColors" ) mExportVertexColors = value;
                else if ( optionName == "exportVertexColorsPerVertex" ) mExportVertexColorsPerVertex = value;
                else if ( optionName == "exportTangents" ) mExportTangents = value;
                else if ( optionName == "exportTexTangents" ) mExportTexTangents = value;
                else if ( optionName == "exportCameraAsLookat" ) mExportCameraAsLookat = value;
                else if ( optionName == "cameraXFov" ) mCameraXFov = value;
                else if ( optionName == "cameraYFov" ) mCameraYFov = value;
                else if ( optionName == "doublePrecision" ) mDoublePrecision = value;
                else if ( optionName == "isSampling" ) mIsSampling = value;
                else if ( optionName == "curveConstrainSampling" ) mCurveConstrainSampling = value;
                else if ( optionName == "removeStaticCurves" ) mRemoveStaticCurves = value;
                else if ( optionName == "exportXRefs" ) mExportXRefs = value;
                else if ( optionName == "dereferenceXRefs" ) mDereferenceXRefs = value;
            }
        }

        if ( !mIsSampling )
        {
            AnimationHelper::generateSamplingFunction();
        }
    }
Beispiel #14
0
MStatus rtgTranslator::writer ( const MFileObject & fileObject,
								  const MString & options,
								  MPxFileTranslator::FileAccessMode mode)
{
	char            LTmpStr[MAXPATHLEN];
	unsigned int	i;
	int             LN;

	const MString   fname = fileObject.fullName ();
	MString         extension;
	MString         baseFileName;

    int             TimeSlider = 0;
    int             AnimEnabled = 0;


	// Lets strip off the known extension of .rtg if it is there.
	
	extension.set (".rtg");
	int  extLocation = fileObject.name ().rindex ('.');

	if (extLocation > 0 && fileObject.name ().substring (extLocation,
			     fileObject.name ().length () - 1) == extension)
	{
		baseFileName = fileObject.name ().substring (0, extLocation - 1);
	} else
	{
		baseFileName = fileObject.name ();
		extension.clear ();
	}


    DtExt_SceneInit( (char *)baseFileName.asChar() );
	
	// Lets now do all of the option processing
	
	if (options.length () > 0)
	{
		//Start parsing.

		MStringArray optionList;
		MStringArray    theOption;

		options.split (';', optionList);

		//break out all the options.

		for ( i = 0; i < optionList.length (); ++i)
		{
			theOption.clear ();
			optionList[i].split ('=', theOption);
			if (theOption.length () > 1)
			{
				if (theOption[0] == MString ("v18compatible"))
				{
					rtg_v18_compatible = (int) (theOption[1].asInt() );
					
				} else if (theOption[0] == MString ("timeslider"))
				{
					TimeSlider = (int) (theOption[1].asInt ());
                } else if (theOption[0] == MString ("animEnabled"))
                {
                    AnimEnabled = (int) (theOption[1].asInt ());

				} else if (theOption[0] == MString ("animStart"))
				{
                    DtFrameSetStart( (int) (theOption[1].asInt ()) );

				} else if (theOption[0] == MString ("animEnd"))
				{
                    DtFrameSetEnd( (int) (theOption[1].asInt ()) );

				} else if (theOption[0] == MString ("animStep"))
				{
                    DtFrameSetBy( (int) (theOption[1].asInt ()) );

				} else if (theOption[0] == MString ("hrcType"))
				{
                    switch ( theOption[1].asInt () - 1)
                    {
                        case VRHRC_FLAT:
                            DtExt_setOutputTransforms (kTRANSFORMMINIMAL);
                            DtExt_setParents (0);
                            break;
                            
                        case VRHRC_WORLD:
                            DtExt_setOutputTransforms (kTRANSFORMNONE);
                            DtExt_setParents (0);
                            break;
                            
                        case VRHRC_FULL:
                        default:
                            DtExt_setOutputTransforms (kTRANSFORMALL);
                            DtExt_setParents (1);
                            break;
                    }       

                } else if (theOption[0] == MString ("joints"))
                { 
                    // Allow user to specify if the hierarchy should include
					// NULL geometry nodes - usually joints 
                    
                    DtExt_setJointHierarchy( theOption[1].asInt() );
 
				} else if (theOption[0] == MString ("exportSel"))
				{
                    switch ( theOption[1].asInt () - 1)
                    {
                        case VRSEL_ALL:
                            DtExt_setWalkMode (ALL_Nodes);
                            break;
                        case VRSEL_ACTIVE:
                            DtExt_setWalkMode (ACTIVE_Nodes);
                            break;
                        case VRSEL_PICKED:
                            DtExt_setWalkMode (PICKED_Nodes);
                            break;
                    }      
				} else if (theOption[0] == MString ("texsample"))
				{
                    // Allow user to specify if the textures should be sampled 
                    // with the Texture Placement options
                    
                    DtExt_setSoftTextures ( theOption[1].asInt() );

				} else if (theOption[0] == MString ("texevaluate"))
				{
                    // Allow the user to specify if the tex should be eval with
                    // convertSolidTx command or read in if is a file texture.
                    
                    DtExt_setInlineTextures( theOption[1].asInt() );

				} else if (theOption[0] == MString ("texoriginal"))
				{
                    // Allow the user to specify if the tex should be eval at all.
                    
                    DtExt_setOriginalTexture( theOption[1].asInt() );
					
				} else if (theOption[0] == MString ("Xtexres"))
				{
                    // Set the X size of the texture swatches to use  
                    
                    DtExt_setXTextureRes ( theOption[1].asInt () );

				} else if (theOption[0] == MString ("Ytexres"))
				{
                    // Set the Y size of the texture swatches to use  
                    DtExt_setYTextureRes ( theOption[1].asInt () );

				} else if (theOption[0] == MString ("MaxXtexres"))
				{
                    // Set the Max X size of the texture swatches to use  
                    DtExt_setMaxXTextureRes( theOption[1].asInt () );
                
				} else if (theOption[0] == MString ("MaxYtexres"))
				{
                    // Set the Max Y size of the texture swatches to use  
                    DtExt_setMaxYTextureRes( theOption[1].asInt () );

				} else if (theOption[0] == MString ("precision"))
				{
					//VR_Precision = theOption[1].asInt ();
				} else if (theOption[0] == MString ("verbose"))
				{
                   // DtExt_setDebug ( theOption[1].asInt () );

                } else if (theOption[0] == MString ("debug"))
                { 
                    int levelG = DtExt_Debug();
                    if ( (int) (theOption[1].asInt () ) )
                        levelG |= DEBUG_GEOMAT;
                    else 
                        levelG &= ~DEBUG_GEOMAT;
                        
                    DtExt_setDebug( levelG );
                    
                } else if (theOption[0] == MString ("debugC"))
                { 
                    int levelC = DtExt_Debug();
                    if ( (int) (theOption[1].asInt () ) )
                        levelC |= DEBUG_CAMERA;
                    else 
                        levelC &= ~DEBUG_CAMERA;
                        
                    DtExt_setDebug( levelC );
                    
                } else if (theOption[0] == MString ("debugL"))
                { 
                    int levelL = DtExt_Debug();
                    if ( (int) (theOption[1].asInt () ) )
                        levelL |= DEBUG_LIGHT;
                    else 
                        levelL &= ~DEBUG_LIGHT;
                        
                    DtExt_setDebug( levelL );

				} else if (theOption[0] == MString ("reversed"))
				{
					DtExt_setWinding( theOption[1].asInt() );

				} else if (theOption[0] == MString ("tesselation"))
				{
					if ( theOption[1].asInt() == 2 )
					{
						DtExt_setTesselate( kTESSQUAD );
					} else {
						DtExt_setTesselate( kTESSTRI );
					}

				//
				// Now come the translator specific options
				//

                } else if (theOption[0] == MString ("imageformat"))
                {
					rtg_output_image_format = theOption[1].asInt();

                } else if (theOption[0] == MString ("fileformat"))
                {
                    rtg_output_file_format = theOption[1].asInt();

                } else if (theOption[0] == MString ("vnormals"))
                { 
                    rtg_output_vert_norms = theOption[1].asInt();

                } else if (theOption[0] == MString ("vcolors"))
                { 
                    rtg_output_vert_colors = theOption[1].asInt();

                } else if (theOption[0] == MString ("tcoords"))
                { 
                    rtg_output_tex_coords = theOption[1].asInt();

                } else if (theOption[0] == MString ("pnormals"))
                { 
                    rtg_output_poly_norms = theOption[1].asInt();

                } else if (theOption[0] == MString ("idxcnt"))
                { 
                    rtg_show_index_counters = theOption[1].asInt();

                } else if (theOption[0] == MString ("anglesdeg"))
                { 
                    rtg_output_degrees = theOption[1].asInt();

                } else if (theOption[0] == MString ("materials"))
                { 
                    rtg_output_materials = theOption[1].asInt();

                } else if (theOption[0] == MString ("multitexture"))
                {
                    DtExt_setMultiTexture( theOption[1].asInt() );

                } else if (theOption[0] == MString ("mdecomp"))
                { 
                    rtg_output_decomp = theOption[1].asInt();

                } else if (theOption[0] == MString ("pivoth"))
                { 
                    rtg_output_pivots = theOption[1].asInt();

                } else if (theOption[0] == MString ("transforms"))
                { 
                    rtg_output_transforms = theOption[1].asInt();

                } else if (theOption[0] == MString ("ltransforms"))
                { 
                    rtg_output_local = theOption[1].asInt();

                } else if (theOption[0] == MString ("animation"))
                { 
                    rtg_output_animation = theOption[1].asInt();

                } else if (theOption[0] == MString ("allnodes"))
                { 
                    rtg_output_all_nodes = theOption[1].asInt();

                } else if (theOption[0] == MString ("script"))
                {
                    scriptToRun = theOption[1];

                } else if (theOption[0] == MString ("scriptAppend"))
                {
                    scriptAppend = (int)(theOption[1].asInt() );
                }

			}
		}
	}

	// Lets see how we entered this plug-in, either with the export all
	// or export selection flag set.

    if ( mode == MPxFileTranslator::kExportActiveAccessMode )
	{ 
        DtExt_setWalkMode ( ACTIVE_Nodes );
	}

    // Lets check the TimeSlider control now:

    if ( TimeSlider )
    {
        MTime start( MAnimControl::minTime().value(), MTime::uiUnit() );
		DtFrameSetStart( (int) start.value() );

        MTime end( MAnimControl::maxTime().value(), MTime::uiUnit() );
		DtFrameSetEnd( (int) end.value() );
    }


    // Now see if the animation is really enabled.
    // Else we will set the end frame to the beginning frame automatically

    if ( !AnimEnabled )
    {
        DtFrameSetEnd( DtFrameGetStart() );
    }

	// Find out where the file is supposed to end up.
	
	MDt_GetPathName ((char *) (fname.asChar ()), LTmpStr, MAXPATHLEN);

	LN = (int)strlen (LTmpStr);
	if (LTmpStr[LN - 1] == '/')
		LTmpStr[LN - 1] = '\0';

	DtSetDirectory (LTmpStr);

    // Now lets setup some paths to do basic texture file searching
    // for those textures with relative paths
    
    MStringArray wSpacePaths;
    MStringArray rPaths;
    MString      usePath;
    MString      separator;
    
    MGlobal::executeCommand( "workspace -q -rd", wSpacePaths );
    MGlobal::executeCommand( "workspace -q -rtl", rPaths );
    
    if ( DtExt_getTextureSearchPath() )
        separator.set( "|" );
    else
        separator.set( "" );
    
    for (i = 0; i < wSpacePaths.length (); ++i)
    {   
        for ( unsigned int j = 0; j < rPaths.length(); j++ )
        {   
            usePath = usePath + separator + wSpacePaths[i] + MString( "/" ) + rPaths[j];    
            separator.set( "|" );
            
            if ( rPaths[j] == MString( "sourceImages" ) )
                usePath = usePath + separator + wSpacePaths[i] + MString( "/" )
                + MString( "sourceimages" );
        
        }
    }
    
    DtExt_addTextureSearchPath( (char *)usePath.asChar() );
    

    // Now we can setup the database from the wire file geometry.
    // This is where all the Maya data are retrieved, cached, and processed.
    //
    
    // Say that we want to have camera info
    
    DtExt_setOutputCameras( 1 );
    
    //Now we can setup the database from the wire file geometry
    
    DtExt_dbInit();
    
	DtFrameSet( DtFrameGetStart() );

    // Now do the export

    rtgExport();
    


    // Now lets see if the user wants something else to be done
    
    if ( 0 < scriptToRun.length() )
    {
        if ( scriptAppend )
        {
            scriptToRun += MString( " " ) + MString( LTmpStr );
        }   
        
        system( scriptToRun.asChar() );
    }   

    // Clean house.
    //
    
    DtExt_CleanUp();

	
	return MS::kSuccess;
}
Beispiel #15
0
// Write method of the GE2.0 translator / file exporter
MStatus ge2Translator::writer ( const MFileObject & fileObject,
								  const MString & options,
								  MPxFileTranslator::FileAccessMode mode)
{
	char            LTmpStr[MAXPATHLEN];
	unsigned int	i,
					LN;

	// const MString   fname = fileObject.fullName ();
	MString         extension;
	MString         baseFileName;


	// Lets strip off the known extension of .grp if it is there.
	extension.set (".grp");
	int  extLocation = fileObject.name ().rindex ('.');

	if ( (extLocation != -1) && // no '.' in name
		 (extLocation != 0) && // name was ".grp" -- that's ok??
		 (fileObject.name ().substring (extLocation, fileObject.name ().length () - 1) == extension) )
	{
		baseFileName = fileObject.name ().substring (0, extLocation - 1);
	} else
	{
		baseFileName = fileObject.name ();
		extension.clear ();
	}

	geWrapper.setBaseFileName( baseFileName );
	geWrapper.setPathName( fileObject.fullName() );

	geWrapper.pluginVersion = version;

	// Set the directory at the Dt level
	strncpy( LTmpStr, geWrapper.getPathName().asChar(), MAXPATHLEN );
	LN = (int)strlen( LTmpStr );
	if ( LTmpStr[LN - 1] == '/' )
		LTmpStr[LN - 1] = '\0';
	DtSetDirectory( LTmpStr );	

	// in an ideal world, everything in setDefaults() should be overridden
	// with the option parsing. If the mel script doesn't get run for whatever
	// reason, or neglects to return some values, hopefully setDefaults will
	// enable the export to go through anyway
	geWrapper.setDefaults();

// Turn off this pesky warning on NT - performance warning
// for int -> bool conversion.
#ifdef WIN32
#pragma warning ( disable : 4800 )
#endif

	// Lets now do all of the option processing	
	if ( options.length () > 0 )
	{
		//Start parsing.

		MStringArray optionList;
		MStringArray    theOption;

		options.split(';', optionList);

		//break out all the options.

		for ( i = 0; i < optionList.length (); ++i )
		{
			theOption.clear ();
			optionList[i].split( '=', theOption );
			if ( theOption.length () > 1 )
			{
				if ( theOption[0] == MString( "enableAnim" ) )
				{
					geWrapper.enableAnim = (bool) ( theOption[1].asInt() );
				}  else if ( theOption[0] == MString( "animStart" ) )
				{
					geWrapper.frameStart = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animEnd" ) )
				{
					geWrapper.frameEnd = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animStep" ) )
				{
					geWrapper.frameStep = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animVertices" ) )
				{
					geWrapper.animVertices = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animDisplacement" ) )
				{
					if ( theOption[1].asInt() == 1 )
						geWrapper.vertexDisplacement = ge2Wrapper::kVDRelative;
					else
						geWrapper.vertexDisplacement = ge2Wrapper::kVDAbsolute;
				} else if ( theOption[0] == MString( "animTransforms" ) )
				{
					geWrapper.animTransforms = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animShaders" ) )
				{
					geWrapper.animShaders = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animLights" ) )
				{
					geWrapper.animLights = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animCamera" ) )
				{
					geWrapper.animCamera = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "keyCurves" ) )
				{
					geWrapper.keyCurves = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "keySample" ) )
				{
					geWrapper.keySample = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "sampRate" ) )
				{
					geWrapper.sampleRate = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "sampTol" ) )
				{
					geWrapper.sampleTolerance = (float) ( theOption[1].asFloat() );
				} else if ( theOption[0] == MString( "useGL" ) )
				{
					geWrapper.useDomainGL = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "usePSX" ) )
				{
					geWrapper.useDomainPSX = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "useN64" ) )
				{
					geWrapper.useDomainN64 = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "useCustom" ) )
				{
					geWrapper.useDomainCustom = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "hrcType" ) )
				{
					geWrapper.hrcMode = static_cast <ge2Wrapper::GEHrcMode> ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportSel" ) )
				{					
					geWrapper.selType = static_cast <ge2Wrapper::GESelType> ( theOption[1].asInt() );
					if ( (mode == MPxFileTranslator::kExportActiveAccessMode) &&
						 (geWrapper.selType == ge2Wrapper::kSelAll) )
					{
						geWrapper.selType = ge2Wrapper::kSelActive;
					}
				} else if ( theOption[0] == MString( "exportLights" ) )
				{
					geWrapper.outputLights = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportCamera" ) )
				{
					geWrapper.outputCamera = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportJoints" ) )
				{
					geWrapper.outputJoints = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportNormals" ) )
				{
					geWrapper.outputNormals = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "opposite" ) )
				{
					geWrapper.oppositeNormals = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportGeometry" ) )
				{ 
					geWrapper.outputGeometry = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "reverse" ) )
				{
					geWrapper.reverseWinding = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportTextures" ) )
				{
					geWrapper.outputTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "tesselation" ) )
				{
					if ( theOption[1].asInt() == 2 )
						DtExt_setTesselate( kTESSQUAD );
					else
						DtExt_setTesselate( kTESSTRI );
				} else if ( theOption[0] == MString( "texsample" ) )
				{
					geWrapper.sampleTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "texevaluate" ) )
				{
					geWrapper.evalTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "texOriginal" ) )
				{
					geWrapper.useOriginalFileTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "Xtexres" ) )
				{
					geWrapper.xTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "Ytexres" ) )
				{
					geWrapper.yTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "MaxXtexres" ) )
				{
					geWrapper.xMaxTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "MaxYtexres" ) )
				{
					geWrapper.yMaxTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "texType" ) )
				{
					geWrapper.texType = theOption[1];
				} else if ( theOption[0] == MString( "precision" ) )
				{
					geWrapper.precision = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "format" ) )
				{
					geWrapper.useTabs = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "comments" ) )
				{
					geWrapper.writeComments = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "verboseGeom" ) )
				{
					geWrapper.verboseGeom = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "verboseLgt" ) )
				{
					geWrapper.verboseLgt = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "verboseCam" ) )
				{
					geWrapper.verboseCam = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "script" ) )
				{
					geWrapper.userScript = theOption[1];
				} else if ( theOption[0] == MString( "scriptAppend" ) )
				{
					geWrapper.scriptAppendFileName = (int) ( theOption[1].asInt() );
				}
			}
		}
	}

#ifdef WIN32
#pragma warning ( default : 4800 )
#endif

	geWrapper.initScene(); // do some initialization
	geWrapper.writeScene(); // write it to the appropriate files
	geWrapper.killScene(); // clean-up

	return MS::kSuccess;
}
MStatus MayaFileTranslator::writer( 	const MFileObject& file,
const MString& options,
FileAccessMode mode){

//-------------------détection des options transmises par le script MEL---------------


	// this will store our option strings
	MStringArray optionList;

	// seperate the option string
	options.split(' ', optionList);

	
	// check all of the options
	int len = optionList.length();

	for( int i = 0; i < len; ++i ){
  		MString Option = optionList[i];

	

		// if we recognised option 1
		if( Option == "vertexcolorFlag" ) {
  			// check for true or false
			if(optionList[++i]=="0")
				Flags.vertex_colors=0;
			else
				Flags.vertex_colors=1;

		}

		// if we recognised our second option
		if( Option == "vertexnormalFlag" ) {
  		// check for true or false
			if(optionList[++i]=="0")
				Flags.Normals=0;
			else
  				Flags.Normals=1;

		}



		// if we recognised our third option
		if( Option == "brushFX" ) {
  			// check for true or false
			if(optionList[++i]=="0")
				Flags.use_vertex_colors=1;
			else
  				Flags.use_vertex_colors=0;

		}
		
	}

	//----------------------------------fin------------------------

	//export Selected Objects
    if(mode == kExportActiveAccessMode) 
	{
		//liste des objets sélectionnés
		MSelectionList selection;
		MGlobal::getActiveSelectionList( selection );
		
		//MStringArray strings;
		//MDagPath dagPath;

			MObject components;
			MDagPath path;

		//-----

//		int temp;
		//MGlobal::displayInfo("Début exportation des objets sélectionnés");
		// ouverture du fichier [BB3D]
		MString output_filename = file.fullName();
		::output.open(output_filename.asChar(),ios::out |ios::binary);
		// ecriture header fichier
		
		::output << "BB3D"; // mise en place du Header fichier B3D
		StartChunck();

		// sauv garde de la position du début de fichier
		//write_int(1);// mise en place d'une valeur entière quelconque pour mise en place ultérieure de la longeur du fichier
		write_int(1);//écriture de la version BB3D
	

#ifdef OLD_TEXS
		// écriture des textures si présentent [TEXS]|detection des textures à enregistrer| + fermeture texs
::output << "TEXS";//header Brush
								StartChunck();
		OutputTextures(selection);
EndChunck();

		// écriture des matériaux [BRUS]|detection des materiaux à enregistrer| +fermeture brus
	
		
//Matid.clear();
		
OutputMaterials(selection);

#else

		//nouvelles textures

#endif	
		
	//------------------------------------fin materials----------------------------------


#ifdef SCENE_ROOT
		// algo des nodes [NODE] réplication de la hierarchie, 
		::output << "NODE"; // mise en place du Header fichier B3D
		StartChunck();
		

		//write_int(1);// mise en place d'une valeur quelconque
		::output << "Scene Root";//nom du Node
		::output << char(0x00);//fin de chaîne

		//écriture des coordonnées spatiales
		//transaltion
		write_float(0);// translation x
		write_float(0);// translation y
		write_float(0);// translation z
		
		write_float(1);//scale x
		write_float(1);//scale y
		write_float(1);//scale z
		
		write_float(0);// rotation  x
		write_float(0);// rotation  y
		write_float(0);// rotation  z
		write_float(0);// rotation  w
		
#else
#endif
		



		int pos_objet=0,pos_nouvel_objet;
		MString nom_objet_precedent;


 	

		// create an iterator to go through all transforms
		//MItDag it(MItDag::depth, MFn::kTransform); 
		MItDag it(MItDag::kDepthFirst, MFn::kTransform);
		// keep looping until done
		int position_hierarchie=0;
		int pos=0;
		while(!it.isDone())
		{
  				MString temp;
				MDagPath path;
				it.getPath(path);
				MFnTransform trans(path);	
				MObject obj=it.item();

	
			
		

				MStringArray chemin_split;
			MString chemin=path.fullPathName();

		
			chemin.split((char)'|',chemin_split);

			pos=chemin_split.length();
			//temp=pos;

			//MGlobal::displayInfo(temp);
		
			if(obj.apiType()== MFn::kTransform && path.child(0).apiType()== MFn::kMesh){
						//MGlobal::displayInfo("Transform trouvé avec child Kmesh");
						//écriture du node avec transform
						//incrément de la hierarchie
						if(pos<position_hierarchie || pos==position_hierarchie){
							//MGlobal::displayInfo("fermeture des nodes précédents");
							for(int i=position_hierarchie;i>pos-1;i--){
							//temp = i;
							//MGlobal::displayInfo(temp);

							EndChunck();
							}//fin for
						
						}//fin if
							
								//MGlobal::displayInfo("Ouverture node");
								::output << "NODE"; // mise en place du Header node
								StartChunck();
								MString nom_objet;
								nom_objet=chemin_split[chemin_split.length()-1];
								
							
									::output << nom_objet.substring(0,nom_objet.length());//nom du Node
								
									::output << char(0x00);//caractêre de fin de chaîne


									
			

			
MVector Translation;
				// get the transforms local translation
		
Translation = trans.getTranslation(MSpace::kTransform);
		
			
			float temp=(float)Translation.x;
			//écriture des coordonnées spaciales
			//transaltion
			write_float(temp);// translation x
			temp=(float)Translation.y;
			write_float(temp);// translation y
			temp=-(float)Translation.z;
			write_float(temp);// translation z
			
				
			double scale[3];
			trans.getScale(scale);
			temp=(float)scale[0];
			write_float(temp);
			temp=(float)scale[1];
			write_float(temp);
			temp=(float)scale[2];
			write_float(temp);

			
			MQuaternion Rotation;
			
			trans.getRotation(Rotation,MSpace::kTransform);



			temp=(float)Rotation.w;
			write_float(temp);
			temp=(float)Rotation.x;
			write_float(temp);
			temp=(float)Rotation.y;
			write_float(temp);
			temp=(float)Rotation.z; 
			write_float(temp);

		


							
		
			


						path.getPath(path);
						if(selection.hasItem(path)!=MStatus::kSuccess){
							//MGlobal::displayInfo("présent dans la liste de selection");
							
							//---------exportation du mesh

						//mais avec des nodes vides, pour les mesh non sélectionnés
					//----------------------------ecriture mesh si objet polygonal présent
						::output << "MESH"; // mise en place du Header mesh
						StartChunck();
										MPointArray vertexArray;// coordonnées des point format double x,y,z;
										MIntArray vertexList;// stockage des indexs des points pour les triangles
										MVector Normal;//stockage d'une normal d'un vertex
		
						//----------------------coordonnées Vertexs  (normal & color si présent et demandés)
						//master brush
						//write_int(0xffffffff);
						write_int(-1);//-1 master brush
						
						MFnMesh meshFn(path.child(0)); // crée une fonction pour le mesh
										
						MItMeshVertex polyperVertex(path, MObject::kNullObj);// crée une fonction pour le mesh , mais avec les fonctions de itmesh
						
						//récupération des coordonnées des points
						//obtient les coordonnées des vertex en mode global
						//meshFn.getPoints(vertexArray,MSpace::kObject);
						meshFn.getPoints(vertexArray,MSpace::kTransform);

						//MFloatArray uArray;
						//MFloatArray vArray;

						//meshFn.getUVs(uArray,vArray);//getUVs( MFloatArray& uArray, MFloatArray& vArray,const MString * uvSet = NULL )
						
						MIntArray uvCounts,uvIds;

						meshFn.getAssignedUVs(uvCounts,uvIds,0);



						//ecriture VRTS
						::output<<"VRTS";
						StartChunck();

										//flags 0=none just vertices coords 1=normal values present, 2=rgba values present
										//The way the flags work, is that you combine them.
										//1 = Vertex Normal
										//2 = Vertex Color
										//3 = Vertex Normal + Color
int flag_normal_colors=0;
//info = "Normals ";
//info += Flags.Normals;
//Affich(info);
//info = "vertex colors ";
//info += Flags.vertex_colors;
//Affich(info);
flag_normal_colors = Flags.Normals+((Flags.use_vertex_colors && Flags.vertex_colors)*2);
//info = flag_normal_colors;
//Affich(info);
						write_int(flag_normal_colors);//présence normale
						
						//int tex_coord_sets          ;texture coords per vertex (eg: 1 for simple U/V) max=8
						write_int(1);//uv simple
						//  int tex_coord_set_size      ;components per set (eg: 2 for simple U/V) max=4
						write_int(2);//2 coordonées textures






										
										




						float x,y,z,normx,normy,normz;//,normx,normy,normz;
						for (unsigned int i=0;i<vertexArray.length();i++){


							x =float(vertexArray[i].x); // -  pour replacer l'axe X dans le sens de celui de blitz
							y =float(vertexArray[i].y);
							z =-float(vertexArray[i].z);// -



							//vertices coords

							write_float(x);
							write_float(y);
							write_float(z);

							//récupère la normale du point
							if(flag_normal_colors==1 || flag_normal_colors==3){
											meshFn.getVertexNormal(i, Normal ,MSpace::kObject);
											normx=float(Normal.x);
											normy=float(Normal.y);
											normz=float(Normal.z);

											
											
											write_float(normx);
											write_float(normy);
											write_float(normz);
							}
											


							//-----------------------------------------
											//vertex_colors_present=1;
											
											if (flag_normal_colors == 2 || flag_normal_colors==3){
											
											
											MStringArray colorsets;
											MColorArray color;
											
											//status = meshFn.getColorSetNames(colorsets);
											meshFn.getColorSetNames(colorsets);
										
												   
												MColor couleur;
												MString colorset = colorsets[0];
												//récupère la couleur moyenne des faces connectés au point
												meshFn.getVertexColors(color,&colorset);

												
												
												
												//polyperVertex.getColor
												//int a;
												//meshFn.getColor(a,couleur);
												//meshFn.getColors(color);
												couleur=color[i];
												float col=float(couleur.r);
												//R
												::output.write((char*)&couleur.r,sizeof(couleur.r));
												//write_float(col);
												col=float(couleur.g);
												//G
												::output.write((char*)&couleur.g,sizeof(couleur.g));
												//write_float(col);
												col=float(couleur.b);
												//B
												::output.write((char*)&couleur.b,sizeof(couleur.b));
												//write_float(col);
												col=float(couleur.a);
												//Alpha
												::output.write((char*)&couleur.a,sizeof(couleur.a));
												//write_float(col);
											
											
											
											}
											//-----------------------------------------
											

//float tempo;
float u,v;

MFloatArray uArray;
MFloatArray vArray;
MIntArray FaceIds;

polyperVertex.getUVs(uArray,vArray,FaceIds);

//meshFn.getUV(i*2,u,v);

u=uArray[0];
v=vArray[0];



//tempo = uArray[0];
//write_float(tempo);

//tempo = vArray[0];
//write_float(tempo);

write_float(u);
write_float(-v);


polyperVertex.next();













						}//fin for

	

						//-----------------fermeture coordonées Vertex
						EndChunck();
						// ----------------------------------export des triangles


#ifdef OLD_TRIS

							//ecriture TRIS
						::output<<"TRIS";
						StartChunck();

										//brush ID
										write_int(-1);//write_int(0);




										//MItMeshPolygon  itPolygon( path, MObject::kNullObj );
										MItMeshPolygon  itPolygon(path.child(0));

	

										for ( /* nothing */; !itPolygon.isDone(); itPolygon.next() )
										{		
					
	

											// Get triangulation of this poly.
											int  numTriangles; 
											itPolygon.numTriangles(numTriangles);

											while ( numTriangles-- )
											{
												//MGlobal::displayInfo("  triangle");
												MStatus status;

												MIntArray                           polygonVertices;

												itPolygon.getVertices( polygonVertices );

												MPointArray                     nonTweaked;
												// object-relative vertex indices for each triangle
												MIntArray                       triangleVertices;
												// face-relative vertex indices for each triangle
												MIntArray                       localIndex;

												status = itPolygon.getTriangle( numTriangles,
												nonTweaked,
												triangleVertices,
												MSpace::kObject );
		
												if ( status == MS::kSuccess )
												{



													//traitement du triangle
			
													// Get face-relative vertex indices for this triangle

			
													//int temp=triangleVertices[0];
						
						
													write_int(triangleVertices[0]);
													write_int(triangleVertices[2]);
													write_int(triangleVertices[1]);
													//::output.write((char*)&triangleVertices[0],sizeof(triangleVertices[0]));
													//::output.write((char*)&triangleVertices[2],sizeof(triangleVertices[2]));
													//::output.write((char*)&triangleVertices[1],sizeof(triangleVertices[1]));
			
			

												} // fin if	


											};// fin while



									}; //fin for

										EndChunck();

#else

			

	unsigned int instancenumbers;
	MObjectArray shaders;
	MIntArray indices;
	//MFnMesh		Fn(path.instanceNumber);
	meshFn.getConnectedShaders(instancenumbers,shaders,indices);
	MString info="shaders.lenght ";
	info += shaders.length();
	Affich(info);

	for (int i=-1;i<shaders.length();i++){//création de tris en fonction du nombre de brush appliqué
		//___________ouput tris________
	
		info = "shader ";
		info += i;
	Affich(info);

							//ecriture TRIS
						::output<<"TRIS";
						StartChunck();
						


	//trouver le brush id par rapport à matid
	//recup nom shader et compare à matid
	MString nameshader;
	nameshader=GetShaderName(shaders[i]);

	info = "Matid id lenght";
	info += Matid.length();
	Affich(info);

int BrushId=0;
	for (int b=0;b<Matid.length();b++){
		if (nameshader==Matid[b]){
		BrushId=b;
		}	
	}

							//brush ID
						write_int(BrushId);
						//write_int(-1);//default
			info= "BrushId ";
		info += BrushId;
	Affich(info);

	info = Matid[BrushId];
	Affich(info);

	MItMeshPolygon  itPolygon(path.child(0));
	int d=0;
	for ( /* nothing */; !itPolygon.isDone(); itPolygon.next() )
		{

			nameshader=GetShaderName(shaders[indices[d]]);
			if(nameshader==Matid[BrushId]){

				// Get triangulation of this poly.
				int  numTriangles; 
				itPolygon.numTriangles(numTriangles);
				while ( numTriangles-- )
											{
												//MGlobal::displayInfo("  triangle");
												MStatus status;

												MIntArray                           polygonVertices;

												itPolygon.getVertices( polygonVertices );
											
												MPointArray                     nonTweaked;
												// object-relative vertex indices for each triangle
												MIntArray                       triangleVertices;
												// face-relative vertex indices for each triangle
												MIntArray                       localIndex;

												status = itPolygon.getTriangle( numTriangles,
												nonTweaked,
												triangleVertices,
												MSpace::kObject );
		
												if ( status == MS::kSuccess )
												{



													
						
						
													write_int(triangleVertices[0]);
													write_int(triangleVertices[2]);
													write_int(triangleVertices[1]);
													
			

												} // fin if	


											};// fin while


			}
		d++;

		}
					
	for (int i=0;i<indices.length();i++){
		//info = " indice ";
		//info += indices[i];
		//Affich(info);

		nameshader=GetShaderName(shaders[indices[i]]);
		if(nameshader==Matid[BrushId]){
		//info=nameshader;
		//Affich(info);

//*********************ecrire triangle*******


		}

	}

	
						EndChunck();

	}
	//for (int i=0;i<Matid.length();i++){
	//	info = Matid[i];
	//	Affich(info);
	//}
//Affich("fin objet");

#endif

						


					//---------------------fermeture mesh
						EndChunck();

							//------------------------------------------------------------
						
						}
						position_hierarchie=pos;
				}
				// move on to next node
				it.next();
			 
			
		}//fin while
		

				//fermeture du node
		//fermeture fichier
		//fermeture de tous les nodes ouverts
			//for (int i=posfichier.length();i>0;i--){

#ifdef SCENE_ROOT
				EndChunck();
#else
#endif

				//}
		//écriture de la longueur du fichier

		output.close();
		Matid.clear();
		Texid.clear();
		nb_Tex_by_Brush.clear();
		Texids_by_brush.clear();
	}
	else		
		//export all polygonal scene objects
	{
	}
	


	return MS::kSuccess;
}
void GlobalComponent::updateComponent(MDGModifier & dgMod,bool forceUpdate, bool globalPos) {
    MStatus status;
    if( !this->m_metaDataNode.isNull() ) {
        //get the rig name
        MFnDependencyNode metaDataNodeFn( m_metaDataNode );
        MString metaNodeName = metaDataNodeFn.name();
        MStringArray nameArray;
        metaNodeName.split('_', nameArray);
        MString rigName = nameArray[1];
        //get the controller name
        MString controllerName = nameArray[2];
        MString compXmlName = this->m_pCompGuide->getName();
        //update names of component objects
        if( rigName != this->m_rigName || controllerName != compXmlName ) {
            //set the metadata node name
            lrutils::stringReplaceAll(metaNodeName, rigName, this->m_rigName);
            lrutils::stringReplaceAll(metaNodeName, controllerName, this->m_pCompGuide->getName());
            metaDataNodeFn.setName(metaNodeName);
            //set controller object name
            MObject globalCtlObj;
            lrutils::getMetaNodeConnection(this->m_metaDataNode, globalCtlObj, "controller");
            MFnDependencyNode globalCtlFn( globalCtlObj );
            MString globalCtlName = globalCtlFn.name();
            lrutils::stringReplaceAll(globalCtlName, rigName, this->m_rigName);
            lrutils::stringReplaceAll(globalCtlName, controllerName, this->m_pCompGuide->getName());
            globalCtlFn.setName(globalCtlName);
            //set controller group object name
            MObject globalCtlGroupObj;
            lrutils::getMetaNodeConnection(this->m_metaDataNode, globalCtlGroupObj, "controllerGroup");
            MFnDependencyNode globalCtlGroupFn( globalCtlGroupObj );
            MString globalCtlGroupName = globalCtlGroupFn.name();
            lrutils::stringReplaceAll(globalCtlGroupName, rigName, this->m_rigName);
            lrutils::stringReplaceAll(globalCtlGroupName, controllerName, this->m_pCompGuide->getName());
            globalCtlGroupFn.setName(globalCtlGroupName);
            //set rigParentConstraint object name
            MObject rigParentConstraintObj;
            lrutils::getMetaNodeConnection(this->m_metaDataNode, rigParentConstraintObj, "rigParentConstraint");
            MFnDependencyNode rigParentConstraintFn( rigParentConstraintObj );
            MString rigParentConstraintName = rigParentConstraintFn.name();
            lrutils::stringReplaceAll(rigParentConstraintName, rigName, this->m_rigName);
            lrutils::stringReplaceAll(rigParentConstraintName, controllerName, this->m_pCompGuide->getName());
            rigParentConstraintFn.setName(rigParentConstraintName);
            //set rigScaleConstraint object name
            MObject rigScaleConstraintObj;
            lrutils::getMetaNodeConnection(this->m_metaDataNode, rigScaleConstraintObj, "rigScaleConstraint");
            MFnDependencyNode rigScaleConstraintFn( rigScaleConstraintObj );
            MString rigScaleConstraintName = rigScaleConstraintFn.name();
            lrutils::stringReplaceAll(rigScaleConstraintName, rigName, this->m_rigName);
            lrutils::stringReplaceAll(rigScaleConstraintName, controllerName, this->m_pCompGuide->getName());
            rigScaleConstraintFn.setName(rigScaleConstraintName);
            //set noTransformScaleConstraint object name
            MObject noTransformScaleConstraintObj;
            lrutils::getMetaNodeConnection(this->m_metaDataNode, noTransformScaleConstraintObj, "noTransformScaleConstraint");
            MFnDependencyNode noTransformScaleConstraintFn( noTransformScaleConstraintObj );
            MString noTransformScaleConstraintName = noTransformScaleConstraintFn.name();
            lrutils::stringReplaceAll(noTransformScaleConstraintName, rigName, this->m_rigName);
            lrutils::stringReplaceAll(noTransformScaleConstraintName, controllerName, this->m_pCompGuide->getName());
            noTransformScaleConstraintFn.setName(noTransformScaleConstraintName); 
        }
        //update component settings, if the version increment is raised
        //or force update is true
        MPlug versionPlug = metaDataNodeFn.findPlug( "version" );
        float nodeVersion; 
        versionPlug.getValue(nodeVersion);
        if( (this->m_pCompGuide->getVersion() > nodeVersion) || forceUpdate ) {
            versionPlug.setValue( this->m_pCompGuide->getVersion() );
            //make a new controller object based upon the xml settings    
            GlobalComponentGuidePtr globalGuide = boost::dynamic_pointer_cast<GlobalComponentGuide>(this->m_pCompGuide);
            MString ctlColor = globalGuide->getColor();
            MString ctlIcon = globalGuide->getIcon();

            MGlobal::executeCommand( "python(\"control = rig101().rig101WCGetByName('" + ctlIcon + "')\");" );
            MGlobal::executeCommand( "python(\"Utils.setControllerColor(control, '" + ctlColor + "')\");" );
            MCommandResult res;
            MGlobal::executeCommand( MString("python(\"control.fullPath()\");"), res );        
            MString sResult;
            res.getResult(sResult);
            MObject ctlObj;
            MStatus status = lrutils::getObjFromName(sResult, ctlObj);
            MyCheckStatus(status, "lrutils::getObjFromName() failed");
            //apply the scale of the controller location to the new shape
            MVectorArray ctlLocation = this->m_pCompGuide->getLocation(0);
            MFnTransform ctlFn( ctlObj );
            lrutils::setLocation(ctlObj, ctlLocation, MFnTransform::MFnTransform(), false, false, true);


            //get the global transforms of the controller for all keyframes and save them for later use
            MObject oldCtlObj;
            status = lrutils::getMetaNodeConnection( this->m_metaDataNode, oldCtlObj, "controller" );
            MyCheckStatus(status, "getMetaNodeConnection() failed");
            MFnTransform oldCtlFn( oldCtlObj );
            std::map<double, MMatrix> oldCtlWorldMatrices;
            if(globalPos) {
                status = lrutils::getAllWorldTransforms(oldCtlObj, oldCtlWorldMatrices);
                MyCheckStatus(status, "lrutils::getAllWorldTransforms() failed");
            }

            //get the shape node of the original controller object
            MStringArray sResults;
            MGlobal::executeCommand( "listRelatives -s -fullPath "+oldCtlFn.name()+";", sResults );
            MString oldCtlShapePath = sResults[0];
            MGlobal::executeCommand( "listRelatives -s -path "+oldCtlFn.name()+";", sResults );
            MString oldCtlShapeName = sResults[0];
            MObject oldCtlShapeObj; lrutils::getObjFromName(oldCtlShapePath, oldCtlShapeObj);
            //delete the old shape node
            MGlobal::deleteNode( oldCtlShapeObj );
            //get the new shape node
            MGlobal::executeCommand( "listRelatives -s -fullPath "+ctlFn.name()+";", sResults );
            MString ctlShapePath = sResults[0];
            MObject ctlShapeObj; lrutils::getObjFromName(ctlShapePath, ctlShapeObj);
            //instance the new shape node under the old controller node
            MString command = "parent -s -add " + ctlShapePath + " " + oldCtlFn.name() + ";";
            MGlobal::executeCommand( command );
            MFnDependencyNode ctlShapeFn( ctlShapeObj );
            ctlShapeFn.setName( oldCtlShapeName );
            //set the old controller group translation to the new location
            MObject oldCtlGroupObj;
            lrutils::getMetaNodeConnection( this->m_metaDataNode, oldCtlGroupObj, "controllerGroup" );
            MFnTransform oldCtlGroupFn( oldCtlGroupObj );
            //save the original old controller position
            MTransformationMatrix oldXForm = oldCtlGroupFn.transformation();
            lrutils::setLocation(oldCtlGroupObj, ctlLocation, oldCtlGroupFn, true, true, false);
            //compute the inverse transformation matrix of the old control group
            MTransformationMatrix oldCtlGrpXform = oldCtlGroupFn.transformation();
            MTransformationMatrix inverseXform = MTransformationMatrix(oldCtlGrpXform.asMatrixInverse());
            //set the target offset for the rigParentConstraint node
            lrutils::getMetaNodeConnection(this->m_metaDataNode, this->m_rigParentConstraint, "rigParentConstraint");
            lrutils::setParentConstraintOffset( this->m_rigParentConstraint, inverseXform );
            //delete the new controller transform
            MGlobal::deleteNode( ctlObj );
            
            //find the global transformation matrix of the controller group
            MDagPath groupPath;
            status = oldCtlGroupFn.getPath(groupPath);
            MyCheckStatus(status, "MFnDagNode.getPath() failed");
            MMatrix oldCtlGroupWorldMatrix = groupPath.inclusiveMatrix(&status);
            MyCheckStatus(status, "MDagPath.inclusiveMatrix() failed");
            if(globalPos) {
                //update the animation curves attached to the old controller
                lrutils::updateAnimCurves(oldCtlObj, oldCtlWorldMatrices, oldCtlGroupWorldMatrix);
            }
        }
    }
}
Beispiel #18
0
// *****************************************************************************
MStatus GtoIO::writer( const MFileObject &file, 
                       const MString &optionsString,
                       MPxFileTranslator::FileAccessMode mode )
{
    MTime fs = MAnimControl::currentTime(); 
    MTime fe = fs;
    double shutter = 0.0;
    MString filename = file.fullName();
    bool subd = false;
    bool normals = false;
    bool exportST = false;
    int maxRecurse = 1;
    bool normalize = false;
    bool hidden = true;
    bool verify = true;
    bool doAnim = false;
    bool diffPoints = false;
    bool diffMatrix = false;
    bool diffNormals = false;
    bool isDifferenceFile = false;
    bool quiet = false;
    bool allUserAttributes = false;
    bool allMayaAttributes = false;
    bool allXformAttributes = false;
    bool faceMaterials = false;
    bool ascii = false;

    if( ( mode == MPxFileTranslator::kExportAccessMode ) ||
        ( mode == MPxFileTranslator::kSaveAccessMode ) )
    {
        MGlobal::displayError( "The GTO plugin can only be used for Export "
                               "Selection...");
        return MS::kFailure;
    }

    MStringArray args;
    optionsString.split( ';', args );
    for( size_t i = 0; i < args.length(); ++i )
    {
        MStringArray thisArg;
        args[i].split( '=', thisArg );
        MString argName( thisArg[0] );
        MString argValue( thisArg[1] );

        if( argName == "recurse" && argValue == "1" )
        {
            maxRecurse = 100000;
        }
        else if( argName == "quiet" && argValue == "1" )
        {
            quiet = true;
        }
        else if( argName == "ascii" && argValue == "1" )
        {
            ascii = true;
        }
        else if( argName == "subd" && argValue == "1" )
        {
            subd = true;
        }
        else if( argName == "normals" && argValue == "1" )
        {
            normals = true;
        }
        else if( argName == "st" && argValue == "1" )
        {
            exportST = true;
        }
        else if( argName == "faceMat" && argValue == "1" )
        {
            faceMaterials = true;
        }
        else if( argName == "diffpositions" && argValue == "1" )
        {
            diffPoints = true;
        }
        else if( argName == "diffmatrices" && argValue == "1" )
        {
            diffMatrix = true;
        }
        else if( argName == "diffnormals" && argValue == "1" )
        {
            diffNormals = true;
        }
        else if( argName == "isdifference" && argValue == "1" )
        {
            isDifferenceFile = true;
        }
        else if( argName == "normalize" && argValue == "1" )
        {
            normalize = true;
        }
        else if( argName == "hidden" && argValue == "0" )
        {
            hidden = false;
        }
        else if( argName == "verify" && argValue == "0" )
        {
            verify = false;
        }
        else if( argName == "userAttr" && argValue == "1" )
        {
            allUserAttributes = true;
        }
        else if( argName == "mayaAttr" && argValue == "1" )
        {
            allMayaAttributes = true;
        }
        else if( argName == "xformAttr" && argValue == "1" )
        {
            allXformAttributes = true;
        }
        else if( argName == "anim" && argValue == "1" )
        {
            doAnim = true;
            // If user didn't include a # in the filename, but
            // is exporting multiple frames, do it automatically
            if( filename.index( '#' ) < 0 )
            {
                // By this point, Maya will have already appended a 
                // ".gto" to the filename if the user didn't include it,
                // so we're guaranteed to find a '.' in the filename
                filename = filename.substring( 0, filename.rindex( '.' ) )
                           + "#.gto";
            }
        }
        else if( argName == "fs" && doAnim )
        {
            fs = MTime( argValue.asDouble(), MTime::uiUnit() );
        }
        else if( argName == "fe" && doAnim  )
        {
            fe = MTime( argValue.asDouble(), MTime::uiUnit() );
        }
        else if( argName == "shutter" && doAnim )
        {
            shutter = argValue.asDouble() / 360.0;
        }
        else if( argName == "recurseLimit" )
        {
            if( argValue.asInt() > 0 )
            {
                maxRecurse = argValue.asInt();
            }
        }
    }
    
    if( ! isDifferenceFile )
    {
        diffPoints = false;
        diffMatrix = false;
        diffNormals = false;
    }
    
    // TODO: Find a more graceful way to get options to GtoExporter

    GtoExporter exporter( fs, fe, quiet, shutter, subd, normals, exportST, filename, 
                          maxRecurse, normalize, hidden, verify, 
                          isDifferenceFile, diffPoints, diffMatrix, 
                          diffNormals, allUserAttributes, allMayaAttributes, 
                          faceMaterials, ascii, allXformAttributes );

    MStatus result = exporter.doIt();
    return result;
}
Beispiel #19
0
MStatus animImport::reader(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;

	MString fileName = file.fullName();
#if defined (OSMac_)	
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ifstream animFile(fname);
#else
	ifstream animFile(fileName.asChar());
#endif
	// 	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//
	MString pasteFlags;
	if (options.length() > 0) {
		//	Set up the flags for the paste command.
		//
		const MString flagTargetTime("targetTime");
		const MString flagTime("time");
		const MString flagCopies("copies");
		const MString flagOption("option");
		const MString flagConnect("connect");

		MString copyValue;
		MString flagValue;
		MString connectValue;
		MString timeValue;

		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {

			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagCopies && theOption.length() > 1) {
				copyValue = theOption[1];;
			} else if (theOption[0] == flagOption && theOption.length() > 1) {
				flagValue = theOption[1];
			} else if (theOption[0] == flagConnect && theOption.length() > 1) {
				if (theOption[1].asInt() != 0) {
					connectValue += theOption[1];
				}
			} else if (theOption[0] == flagTime && theOption.length() > 1) {
				timeValue += theOption[1];
			}
		}
	
		if (copyValue.length() > 0) {
			pasteFlags += " -copies ";
			pasteFlags += copyValue;
			pasteFlags += " ";
		} 
		if (flagValue.length() > 0) {
			pasteFlags += " -option \"";
			pasteFlags += flagValue;
			pasteFlags += "\" ";
		} 
		if (connectValue.length() > 0) {
			pasteFlags += " -connect ";
			pasteFlags += connectValue;
			pasteFlags += " ";
		} 
		if (timeValue.length() > 0) {
			bool useQuotes = !timeValue.isDouble();
			pasteFlags += " -time ";
			if (useQuotes) pasteFlags += "\"";
			pasteFlags += timeValue;
			if (useQuotes) pasteFlags += "\"";
			pasteFlags += " ";
		} 
	}

	if (mode == kImportAccessMode) {
		status = importAnim(animFile, pasteFlags);
	}

	animFile.close();
	return status;
}
Beispiel #20
0
// *****************************************************************************
MStatus GtoIO::reader( const MFileObject &file, 
                       const MString &optionsString,
                       MPxFileTranslator::FileAccessMode mode )
{
    MString filename = file.fullName();
    bool readAsDifference = false;
    int fs = 0;
    int fe = 0;

    MStringArray args;
    optionsString.split( ';', args );
    for( size_t i = 0; i < args.length(); ++i )
    {
        MStringArray thisArg;
        args[i].split( '=', thisArg );
        MString argName( thisArg[0] );
        MString argValue( thisArg[1] );

        if( argName == "readDiff" && argValue == "1" )
        {
            readAsDifference = true;
        }
        else if( argName == "fs" )
        {
            fs = argValue.asInt();
        }
        else if( argName == "fe" )
        {
            fe = argValue.asInt();
        }
    }

    if( readAsDifference )
    {
        MGlobal::displayInfo( "PreMunge name: " + filename );

        if( filename.index( '#' ) < 0 )
        {
            // By this point, Maya will have already appended a 
            // ".gto" to the filename if the user didn't include it,
            // so we're guaranteed to find a '.' in the filename
            filename = filename.substring( 0, filename.index( '.' ) )
                       + "#.gto";
        }

        for( int f = fs; f <= fe; ++f )
        {
            MGlobal::viewFrame( MTime( double(f) ) );

            MString fname = replaceFrameCookies( filename, f );

            MGlobal::displayInfo( "Reading " + fname );

            DataBase dataBase;
            Set *set = dataBase.set( fname.asChar() );
            if( set == NULL )
            {
                MGlobal::displayError( "Unable to open file for some "
                                       "reason.  Permissions?" );
                return MS::kFailure;
            }

            set->computeLocalTransforms();

            set->declareMayaDiff();

            dataBase.destroyAll();
        }
    }
    else
    {
        DataBase dataBase;
        Set *set = dataBase.set( filename.asChar() );
        if( set == NULL )
        {
            MGlobal::displayError( "Unable to open file for some "
                                   "reason.  Permissions?" );
            return MS::kFailure;
        }

        set->computeLocalTransforms();

        set->declareMaya();

        set->reparentAll();

        dataBase.destroyAll();
    }

    return MS::kSuccess;
}
Beispiel #21
0
MStatus animExport::writer(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;


	MString fileName = file.fullName();
#if defined (OSMac_)
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ofstream animFile(fname);
#else
	ofstream animFile(fileName.asChar());
#endif
	//	Defaults.
	//
	MString copyFlags("copyKey -cb api -fea 1 ");
	int precision = kDefaultPrecision;
	bool nodeNames = true;
	bool verboseUnits = false;

	//	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//
	MString exportFlags;
	if (options.length() > 0) {
		const MString flagPrecision("precision");
		const MString flagNodeNames("nodeNames");
		const MString flagVerboseUnits("verboseUnits");
		const MString flagCopyKeyCmd("copyKeyCmd");

		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {
			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagPrecision && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					precision = theOption[1].asInt();
				}
			} else if (	theOption[0] == 
						flagNodeNames && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					nodeNames = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
					flagVerboseUnits && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					verboseUnits = (theOption[1].asInt()) ? true : false;
				}
			} else if (	theOption[0] == 
						flagCopyKeyCmd && theOption.length() > 1) {

				//	Replace any '>' characters with '"'. This is needed
				//	since the file translator option boxes do not handle
				//	escaped quotation marks.
				//
				const char *optStr = theOption[1].asChar();
				size_t nChars = strlen(optStr);
				char *copyStr = new char[nChars+1];

				copyStr = strcpy(copyStr, optStr);
				for (size_t j = 0; j < nChars; j++) {
					if (copyStr[j] == '>') {
						copyStr[j] = '"';
					}
				}
		
				copyFlags += copyStr;
				delete [] copyStr;
			}
		}
	}
	
	//	Set the precision of the ofstream.
	//
	animFile.precision(precision);

	status = exportSelected(animFile, copyFlags, nodeNames, verboseUnits);

	animFile.flush();
	animFile.close();

	return status;
}
Beispiel #22
0
void atomImport::connectionFailedCallback(MPlug& srcPlug,
										  MPlug& dstPlug,
										  const MString& srcName,
										  const MString& dstName,
										  void* clientData)
{
//	MString output = "Connection failed callback: ";
//	output += srcName;  output += " ";	output += dstName;
//	MGlobal::displayInfo(output);

	atomEditsHelper* helper = (NULL != clientData) ? (atomEditsHelper*)clientData : NULL;
	atomNodeNameReplacer* replacer = (NULL != helper) ? helper->fReplacer : NULL;
	atomTemplateReader* templateReader = (NULL != helper) ? helper->fTemplateReader : NULL;

	if (NULL != replacer && srcPlug.isNull()) {
		// Import of the edits didn't find a match for the source name, use the 
		// replacer and see if that helps
		//
		if (replaceNameAndFindPlug(srcName,*replacer,srcPlug)) {
			if (!dstPlug.isNull()) {
				// we've found the proper source plug to use and we already
				// had a dest, so connect them up and we're done
				//
				MDagModifier mod;
				mod.connect(srcPlug,dstPlug);
				return;
			}
		}
	}

	if (NULL != replacer && dstPlug.isNull()) {
		// Import of the edits didn't find a match for the dest name, use the 
		// replacer and see if that helps
		//
		if (replaceNameAndFindPlug(dstName,*replacer,dstPlug)) {
			MStringArray dstParts;
			dstName.split('.', dstParts);			
			if (!checkPlugAgainstTemplate(dstParts[0],dstPlug,templateReader))
				return;

			if (!srcPlug.isNull()) {
				// we've found the proper dest plug to use and we already
				// had a source, so connect them up and we're done
				//
				MDagModifier mod;
				mod.connect(srcPlug,dstPlug);
				return;
			}
		}
	}
	
	if (!dstPlug.isNull()) {
		
		MObject dstNode = dstPlug.node();

		// Check whether the failed connection was to a setDrivenKey curve
		//
		if (dstNode.hasFn(MFn::kAnimCurveUnitlessToAngular) ||
			dstNode.hasFn(MFn::kAnimCurveUnitlessToDistance) ||
			dstNode.hasFn(MFn::kAnimCurveUnitlessToTime) ||
			dstNode.hasFn(MFn::kAnimCurveUnitlessToUnitless)) {

			// If so, create a stand-in driver for that curve
			//
			MDagModifier mod;
			MObject locator = mod.createNode( "locator", MObject::kNullObj );
			MFnDependencyNode fnLoc(locator);

			MStringArray nameParts;
			srcName.split('.', nameParts);
			MString leafAttr(nameParts[nameParts.length()-1]);
			MPlug leafPlug = fnLoc.findPlug(leafAttr);
			if (!leafPlug.isNull()) {
				mod.connect(leafPlug,dstPlug);

				// rename the locator to the name of the original source
				// so that any subsequent connections will work
				//
				fnLoc.setName(nameParts[0]);
			}
		}
	}
}
Beispiel #23
0
MStatus
usdTranslatorExport::writer(const MFileObject &file, 
                 const MString &optionsString,
                 MPxFileTranslator::FileAccessMode mode ) {

    std::string fileName(file.fullName().asChar());
    JobExportArgs jobArgs;
    double startTime=1, endTime=1;
    bool append=false;
    
    // Get the options 
    if ( optionsString.length() > 0 ) {
        MStringArray optionList;
        MStringArray theOption;
        optionsString.split(';', optionList);
        for(int i=0; i<(int)optionList.length(); ++i) {
            theOption.clear();
            optionList[i].split('=', theOption);            
            if (theOption[0] == MString("exportReferencesAsInstanceable")) {
                jobArgs.exportRefsAsInstanceable = theOption[1].asInt();
            }
            if (theOption[0] == MString("shadingMode")) {
                // Set default (most common) options
                jobArgs.exportDisplayColor = true;
                jobArgs.shadingMode = PxrUsdMayaShadingModeTokens->none;
                
                if (theOption[1]=="None") {
                    jobArgs.exportDisplayColor = false;
                }else if (theOption[1]=="Look Colors") {
                    jobArgs.shadingMode = PxrUsdMayaShadingModeTokens->displayColor;
                } else if (theOption[1]=="RfM Shaders") {
                    TfToken shadingMode("pxrRis");
                    if (PxrUsdMayaShadingModeRegistry::GetInstance().GetExporter(shadingMode)) {
                        jobArgs.shadingMode = shadingMode;
                    }
                }
            }
            if (theOption[0] == MString("exportUVs")) {
                jobArgs.exportMeshUVs = theOption[1].asInt();
                jobArgs.exportNurbsExplicitUV = theOption[1].asInt();
            }
            if (theOption[0] == MString("normalizeUVs")) {
                jobArgs.normalizeMeshUVs = theOption[1].asInt();
                jobArgs.nurbsExplicitUVType = PxUsdExportJobArgsTokens->Uniform;
            }
            if (theOption[0] == MString("exportColorSets")) {
                jobArgs.exportColorSets = theOption[1].asInt();
            }
            if (theOption[0] == MString("renderableOnly")) {
                jobArgs.excludeInvisible = theOption[1].asInt();
            }
            if (theOption[0] == MString("allCameras")) {
                jobArgs.exportDefaultCameras = theOption[1].asInt();
            }
            if (theOption[0] == MString("renderLayerMode")) {
                jobArgs.renderLayerMode = PxUsdExportJobArgsTokens->defaultLayer;

                if (theOption[1]=="Use Current Layer") {
                    jobArgs.renderLayerMode = PxUsdExportJobArgsTokens->currentLayer;
                } else if (theOption[1]=="Modeling Variant Per Layer") {
                    jobArgs.renderLayerMode = PxUsdExportJobArgsTokens->modelingVariant;
                }
            }
            if (theOption[0] == MString("mergeXForm")) {
                jobArgs.mergeTransformAndShape = theOption[1].asInt();
            }
            if (theOption[0] == MString("defaultMeshScheme")) {            
                if (theOption[1]=="Polygonal Mesh") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->none;
                } else if (theOption[1]=="Bilinear SubDiv") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->bilinear;
                } else if (theOption[1]=="CatmullClark SDiv") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->catmullClark;
                } else if (theOption[1]=="Loop SDiv") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->loop;
                }
            }
            if (theOption[0] == MString("exportVisibility")) {
                jobArgs.exportVisibility = theOption[1].asInt();
            }
            if (theOption[0] == MString("animation")) {
                jobArgs.exportAnimation = theOption[1].asInt();
            }
            if (theOption[0] == MString("startTime")) {
                startTime = theOption[1].asDouble();
            }
            if (theOption[0] == MString("endTime")) {
                endTime = theOption[1].asDouble();
            }
        }
        // Now resync start and end frame based on animation mode
        if (jobArgs.exportAnimation) {
            if (endTime<startTime) endTime=startTime;
        } else {
            startTime=MAnimControl::currentTime().value();
            endTime=startTime;
        }
    }

    MSelectionList objSelList;
    if(mode == MPxFileTranslator::kExportActiveAccessMode) {
        // Get selected objects
        MGlobal::getActiveSelectionList(objSelList);
    } else if(mode == MPxFileTranslator::kExportAccessMode) {
        // Get all objects at DAG root
        objSelList.add("|*", true);
    }

    // Convert selection list to jobArgs dagPaths
    for (unsigned int i=0; i < objSelList.length(); i++) {
        MDagPath dagPath;
        if (objSelList.getDagPath(i, dagPath) == MS::kSuccess) {
            jobArgs.dagPaths.insert(dagPath);
        }
    }
    
    if (jobArgs.dagPaths.size()) {
        MTime oldCurTime = MAnimControl::currentTime();
        usdWriteJob writeJob(jobArgs);
        if (writeJob.beginJob(fileName, append, startTime, endTime)) {
            for (double i=startTime;i<(endTime+1);i++) {
                MGlobal::viewFrame(i);
                writeJob.evalJob(i);
            }
            writeJob.endJob();
            MGlobal::viewFrame(oldCurTime);
        }
    } else {
        MGlobal::displayWarning("No DAG nodes to export. Skipping");
    }
    
    return MS::kSuccess;
}
Beispiel #24
0
MStatus atomExport::writer(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;


	MString fileName = file.fullName();
#if defined (OSMac_)
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ofstream animFile(fname);
#else
	ofstream animFile(fileName.asChar());
#endif
	//	Defaults.
	//
	MString copyFlags("copyKey -cb api -fea 1 ");
	int precision = kDefaultPrecision;
	bool statics = false;
	bool includeChildren = false;
	std::set<std::string> attrStrings;
	//	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//
	bool useSpecifiedRange = false;
	bool useTemplate = false;
	bool cached = false;
	bool constraint = false;
	bool sdk = false;
	bool animLayers = true;
	MString templateName;
	MString viewName;
	MTime startTime = MAnimControl::animationStartTime();
	MTime endTime = MAnimControl::animationEndTime();
	MString	exportEditsFile;

	MString exportFlags;
	if (options.length() > 0) {
		const MString flagPrecision("precision");
		const MString flagStatics("statics");
		const MString flagConstraint("constraint");
		const MString flagSDK("sdk");
		const MString flagAnimLayers("animLayers");
		const MString flagCopyKeyCmd("copyKeyCmd");
		const MString flagSelected("selected");
		const MString flagTemplate("template");
		const MString flagView("view");
		const MString optionChildrenToo("childrenToo");
		const MString optionTemplate("template");
		const MString flagAttr("at");
		const MString flagWhichRange("whichRange");
		const MString flagRange("range");
		const MString flagExportEdits("exportEdits");		
		const MString flagCached("baked");		
		
		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {
			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagPrecision && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					precision = theOption[1].asInt();
				}
			} 
			else if( theOption[0] == flagTemplate && theOption.length() > 1)
			{
				templateName = theOption[1];
			}
			else if( theOption[0] == flagView && theOption.length() > 1)
			{
				viewName = theOption[1];
			}
			else if (	theOption[0] == 
						flagWhichRange && theOption.length() > 1) {
				if (theOption[1].isInt()) 
					useSpecifiedRange = (theOption[1].asInt() ==1) ? false : true;
			}
			else if (	theOption[0] == 
						flagRange && theOption.length() > 1) 
			{
				MStringArray rangeArray;
				theOption[1].split(':',rangeArray);
				if(rangeArray.length()==2)
				{
					if(rangeArray[0].isDouble())
					{
						double val = rangeArray[0].asDouble();
						startTime = MTime(val,MTime::uiUnit());
					}
					else if(rangeArray[0].isInt())
					{
						double val = (double)rangeArray[0].asInt();
						startTime = MTime(val,MTime::uiUnit());
					}
					if(rangeArray[1].isDouble())
					{
						double val = rangeArray[1].asDouble();
						endTime = MTime(val,MTime::uiUnit());
					}
					else if(rangeArray[1].isInt())
					{
						double val = (double)rangeArray[1].asInt();
						endTime = MTime(val,MTime::uiUnit());
					}
				}
			}
			else if (	theOption[0] == 
						flagStatics && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					statics = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagSDK && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					sdk = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagConstraint && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					constraint = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagAnimLayers && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					animLayers = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagCached && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					cached = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (theOption[0] == flagSelected && theOption.length() > 1) {
				includeChildren = (theOption[1] == optionChildrenToo) ? true : false;
				if(theOption[1] == optionTemplate)
					useTemplate = true;
			} 
			else if (theOption[0] == flagAttr && theOption.length() > 1) {
				std::string str(theOption[1].asChar());
				attrStrings.insert(str);
			} 
			else if (	theOption[0] == 
						flagCopyKeyCmd && theOption.length() > 1) {

				//	Replace any '>' characters with '"'. This is needed
				//	since the file translator option boxes do not handle
				//	escaped quotation marks.
				//
				const char *optStr = theOption[1].asChar();
				size_t nChars = strlen(optStr);
				char *copyStr = new char[nChars+1];

				copyStr = strcpy(copyStr, optStr);
				for (size_t j = 0; j < nChars; j++) {
					if (copyStr[j] == '>') {
						copyStr[j] = '"';
					}
				}
		
				copyFlags += copyStr;
				delete [] copyStr;
			}
			else if (theOption[0] == flagExportEdits && theOption.length() > 1)
			{
				exportEditsFile =  theOption[1];
			}
		}
	}
	
	//	Set the precision of the ofstream.
	//
	animFile.precision(precision);


	atomTemplateReader templateReader;
	if(useTemplate == true)
	{
		includeChildren = false;
		templateReader.setTemplate(templateName,viewName);
		templateReader.selectNodes(); //make the template nodes be the selection
	}
	status = exportSelected(animFile, copyFlags, attrStrings, includeChildren,
							useSpecifiedRange, startTime, endTime, statics,
							cached,sdk,constraint, animLayers, exportEditsFile,templateReader);

	animFile.flush();
	animFile.close();

	return status;
}
Beispiel #25
0
MStatus AbcExport::doIt(const MArgList & args)
{
    MStatus status;

    MTime oldCurTime = MAnimControl::currentTime();

    MArgParser argData(syntax(), args, &status);
    if (status != MS::kSuccess)
        return status;

    unsigned int numberOfArguments = args.length();

    MString msg;
    msg += "AbcExport  [options] tranlation_jobs_description_string\n\n";
    msg += "Options:\n";
    msg += "-h  / help  Print this message.\n";
    msg += "\n";
    msg += "-sa / startAt float (default: 0.0f)\n";
    msg += "The frame to start scene evaluation at. This is used to set\n";
    msg += "the starting frame for time dependent translations and can\n";
    msg += "be used to add run-up that isn't actually translated.\n";
    msg += "\n";
    msg += "-sf / skipFrame boolean (default: false)\n";
    msg += "When evaluating multiple translate jobs, this flag decides\n";
    msg += "whether or not to skip frame if possible.\n";
    msg += "\n";
    msg += "-sl / selection\n";
    msg += "If this flag is present: if tranlation_jobs_description_string\n";
    msg += "is empty, write out all nodes from the active selection list;\n";
    msg += "if tranlation_jobs_description_string is not empty, write out\n";
    msg += "only the nodes in the active selection list.\n";
    msg += "\n";
    msg += "-d  / debug  Print debug log\n";
    msg += "\n";
    msg += "(Each translation job is seperated by ;)\n";
    msg += "\n";
    msg += "per translation job optional flags:\n";
    msg += "\n";
    msg += "range float startTime float endTime\n";
    msg += "The frame range to write.\n";
    msg += "\n";
    msg += "uv\n";
    msg += "If set, AbcExport will bake the current uv set of polygons\n";
    msg += "and subD meshes into property \"st\" on the nodes.\n";
    msg += "By default this flag is not set.\n";
    msg += "\n";
    msg += "shutterOpen float (default: 0.0)\n";
    msg += "Motion blur starting time.\n";
    msg += "\n";
    msg += "shutterClose float (default: 0.0)\n";
    msg += "Motion blur end time\n";
    msg += "\n";
    msg += "numSamples unsigned int (default: 2)\n";
    msg += "The number of times to sample within a given frame with\n";
    msg += "motion blur applied.  If shutterOpen is equal to\n";
    msg += "shutterClose then numSamples is ignored.\n";
    msg += "\n";
    msg += "noSampleGeo\n";
    msg += "If set, only write out geometry on whole frames, not\n";
    msg += "subframes. This flag is not set by default.\n";
    msg += "Transforms may still be written out on subframes.\n";
    msg += "\n";
    msg += "attrPrefix string (default: SPT_)\n";
    msg += "Prefix filter for determining which attributes to write out\n";
    msg += "\n";
    msg += "attrs string\n";
    msg += "Comma seperated list of attributes to write out, these\n";
    msg += "attributes will ignore the attr prefix filter.\n";
    msg += "\n";
    msg += "writeVisibility bool (default: false)\n";
    msg += "Whether or not to write the visibility state to the file.\n";
    msg += "If false then visibility is not written and everything is\n";
    msg += "assumed to be visible.\n";
    msg += "\n";
    msg += "worldSpace\n";
    msg += "If set, the root nodes will be stored in world space.\n";
    msg += "By default it is stored in local space.\n";
    msg += "\n";
    msg += "melPerFrameCallback string (default: "")\n";
    msg += "When each frame (and the static frame) is evaluated the\n";
    msg += "string specified is evaluated as a Mel command.\n";
    msg += "See below for special processing rules.\n";
    msg += "Example: melPerFrameCallback print(\"#FRAME#\")\n";
    msg += "\n";
    msg += "melPostCallback string (default: "")\n";
    msg += "When the translation has finished the string specified is\n";
    msg += "evaluated as a Mel command.\n";
    msg += "See below for special processing rules.\n";
    msg += "Example: melPostCallback print(\"Done!\")\n";
    msg += "\n";
    msg += "pythonPerFrameCallback string (default: "")\n";
    msg += "When each frame (and the static frame) is evaluated the\n";
    msg += "string specified is evaluated as a python command.\n";
    msg += "See below for special processing rules.\n";
    msg += "Example: pythonPerFrameCallback print(\"#FRAME#\")\n";
    msg += "\n";
    msg += "pythonPostCallback string (default: "")\n";
    msg += "When the translation has finished the string specified is\n";
    msg += "evaluated as a python command.\n";
    msg += "See below for special processing rules.\n";
    msg += "Example: pythonPostCallback print(\"Done!\")\n";
    msg += "\n";
    msg += "On the callbacks, special tokens are replaced with other\n";
    msg += "data, these tokens and what they are replaced with are as\n";
    msg += "follows:\n";
    msg += "\n";
    msg += "#FRAME# replaced with the frame number being evaluated, if\n";
    msg += "the static frame is being evaluated then #FRAME# is not\n";
    msg += "replaced.  #FRAME# is ignored in the post callbacks.\n";
    msg += "\n";
    msg += "#BOUNDS# replaced with the bounding box values in minX minY\n";
    msg += "minZ maxX maxY maxZ space seperated order.\n";
    msg += "\n";
    msg += "#BOUNDSARRAY# replaced with the bounding box values as\n";
    msg += "above, but in array form. In Mel:\n";
    msg += "In Mel: {minX, minY, minZ, maxX, maxY, maxZ}\n";
    msg += "In Python: [minX, minY, minZ, maxX, maxY, maxZ]";
    msg += "\n";
    msg += "Command Examples:\n";
    msg += "AbcExport -d -sf \"range 1 24 test_hi test_lo /tmp/test.abc\"\n";
    msg += "AbcExport \"worldSpace test_hi /tmp/test_hi.abc\"\n";
    msg += "AbcExport \"range 1 24 shutterOpen 0.0 shutterClose 0.5 ";
    msg += "numSamples 2 test_hi test_lo /tmp/test.abc\"\n";
    msg += "AbcExport -d \"range 101 700 test_hi /tmp/test.abc; range 10";
    msg += " 55 test_lo /tmp/test1.abc\"\n";
    msg += "\n";
    msg += "Note that multiple nodes can be written to the same file,\n";
    msg += "but these nodes should not have any parenting relationships\n";
    msg += "or the job will not be written out.\n";

    if (argData.isFlagSet("help"))
    {
        MGlobal::displayInfo(msg);
        return MS::kSuccess;
    }

    bool debug = argData.isFlagSet("debug");

    // If skipFrame is true, when going through the playback range of the
    // scene, as much frames are skipped when possible.  This could cause
    // a problem for, time dependent solutions like
    // particle system / hair simulation
    bool skipFrame = false;
    if (argData.isFlagSet("skipFrame"))
        skipFrame = true;

    bool useSelectionList = false;
    if (argData.isFlagSet("selection"))
        useSelectionList = true;

    double startEvaluationTime = FLT_MAX;
    if (argData.isFlagSet("startAt"))
    {
        double startAt = 0.0;
        argData.getFlagArgument("startAt", 0, startAt);
        startEvaluationTime = startAt;
    }

    // Very rudimentary argument parser: no syntax checking at all !!!
    MString argStr;

    // status = argData.getCommandArgument(0, argStr);
    argStr = args.asString(numberOfArguments-1, &status);
    MStringArray jobStringArray;
    status = argStr.split(';', jobStringArray);
    unsigned int jobSize = jobStringArray.length();

    if (jobSize == 0)
        return status;

    // the frame range we will be iterating over for all jobs,
    // includes frames which are not skipped and the startAt offset
    std::set<double> allFrameRange;

    // this will eventually hold only the animated jobs.
    // its a list because we will be removing jobs from it
    std::list < AbcWriteJobPtr > jobList;

    for (unsigned int jobIndex = 0; jobIndex < jobSize; jobIndex++)
    {
        unsigned int argc = 0;

        // parse the string
        MString tstr = jobStringArray[jobIndex];
        MStringArray strArr;
        status = tstr.split(' ', strArr);
        unsigned int length = strArr.length();

        double  startTime = oldCurTime.value();
        double  endTime = oldCurTime.value();

        double  shutterOpen = 0.0;
        double  shutterClose = 0.0;
        int     numSamples = 1;
        bool    sampleGeo  = true;     // whether or not to subsample geometry

        bool    worldSpace = false;
        bool    writeVisibility = false;
        bool    writeUVs   = false;

        // DAG path array of nodes to be written out as root nodes in the file
        util::ShapeSet dagPath;

       // name of the abc file the job will be written into
        std::string fileName;

        // the list of frames written into the abc file
        std::set<double> geoSamples;
        std::set<double> transSamples;

        std::string melPerFrameCallback;
        std::string melPostCallback;
        std::string pythonPerFrameCallback;
        std::string pythonPostCallback;

        // attribute filtering stuff
        std::string prefixFilter = "SPT_";
        std::set<std::string> attribsSet;

        // parser for each job
        while (argc < length)
        {
            if (strArr[argc] == "range")  // range start end
            {
                // guard against overruns
                if (argc + 2 >= length)
                    return MS::kFailure;

                // looking for two floating point numbers
                util::isFloat(strArr[argc+1], msg);
                util::isFloat(strArr[argc+2], msg);

                startTime = floor(strArr[argc+1].asDouble());
                endTime = ceil(strArr[argc+2].asDouble());

                // make sure start frame is smaller or equal to endTime
                if (startTime > endTime)
                {
                    double temp = startTime;
                    startTime = endTime;
                    endTime = temp;
                }

                argc += 3;
            }
            else if (strArr[argc] == "uv")
            {
                writeUVs = true;
                argc++;
            }
            else if (strArr[argc] == "shutterOpen")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                util::isFloat(strArr[argc+1], msg);
                shutterOpen = strArr[argc+1].asDouble();
                argc += 2;
            }
            else if (strArr[argc] == "shutterClose")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                util::isFloat(strArr[argc+1], msg);
                shutterClose = strArr[argc+1].asDouble();
                argc += 2;
            }
            else if (strArr[argc] == "numSamples")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                util::isUnsigned(strArr[argc+1], msg);
                numSamples = strArr[argc+1].asInt();
                argc += 2;
            }
            else if (strArr[argc] == "writeVisibility")
            {
                writeVisibility = true;
                argc++;
            }
            else if (strArr[argc] == "worldSpace")
            {
                worldSpace = true;
                argc++;
            }
            else if (strArr[argc] == "noSampleGeo")
            {
                sampleGeo = false;
                argc++;
            }
            else if (strArr[argc] == "melPerFrameCallback")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                melPerFrameCallback = strArr[argc+1].asChar();
                argc += 2;
            }
            else if (strArr[argc] == "melPostCallback")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                melPostCallback = strArr[argc+1].asChar();
                argc += 2;
            }
            else if (strArr[argc] == "pythonPerFrameCallback")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                pythonPerFrameCallback = strArr[argc+1].asChar();
                argc += 2;
            }
            else if (strArr[argc] == "pythonPostCallback")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                pythonPostCallback = strArr[argc+1].asChar();
                argc += 2;
            }

            else if (strArr[argc] == "attrPrefix")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                prefixFilter = strArr[argc+1].asChar();
                argc += 2;
            }

            else if (strArr[argc] == "attrs")
            {
                if (argc + 1 >= length)
                    return MS::kFailure;

                MString attrString = strArr[argc+1];

                MStringArray attribs;
                attrString.split(',', attribs);
                unsigned int attribsLength = attrString.length();
                for (unsigned int i = 0; i < attribsLength; ++i)
                {
                    MString & attrib = attribs[i];
                    if (attrib != "" && attrib != "visibility")
                    {
                        attribsSet.insert(attrib.asChar());
                    }
                }
                argc += 2;
            }
            else
            // assume in the order of node names and then abc file name
            {
                for (; argc < length-1; argc++)
                {
                    MSelectionList sel;
                    if (!sel.add(strArr[argc]))
                    {
                        MString warn = "Could not select ";
                        warn += strArr[argc];
                        warn += ". Skipping...";
                        MGlobal::displayWarning(warn);
                        continue;
                    }

                    MDagPath path;
                    if (!sel.getDagPath(0, path))
                    {
                        MGlobal::displayWarning(
                            "Not a DAG Node. Skipping... ");
                        continue;
                    }

                    dagPath.insert(path);
                }

                // check for validity of the DagPath relationships
                // complexity : n^2
                bool isAncestor = false;
                if (dagPath.size() > 1)
                {
                    util::ShapeSet::iterator m, n;
                    const util::ShapeSet::iterator end = dagPath.end();
                    for (m = dagPath.begin(); m != end; )
                    {
                        MDagPath path1 = *m;
                        m++;
                        for (n = m; n != end; n++)
                        {
                            MDagPath path2 = *n;
                            if (util::isAncestorDescendentRelationship(path1, path2))
                                isAncestor = true;
                        }  // for n
                    }  // for m
                }
                if (isAncestor == true)
                    return MS::kFailure;

                if (argc >= length)
                    return MS::kFailure;

                fileName = strArr[argc++].asChar();
            }
        }

        std::set <double> origSamples;
        for (double f = startTime; f <= endTime; f++)
            origSamples.insert(f);

        transSamples = origSamples;
        geoSamples = origSamples;

        Alembic::AbcCoreAbstract::v1::chrono_t fps24 = 1/24.0;
        Alembic::AbcCoreAbstract::v1::TimeSamplingType transTime(fps24);
        Alembic::AbcCoreAbstract::v1::TimeSamplingType geoTime(fps24);

        // post process, add extra motion blur samples
        if (numSamples > 1 && shutterOpen < shutterClose)
        {
            transTime = Alembic::AbcCoreAbstract::v1::TimeSamplingType(
                numSamples, fps24);

            // if we are't subsampling the geometry, leave it as uniform
            if (sampleGeo)
                geoTime = transTime;

            std::set<double> offsetSamples;
            offsetSamples.insert(shutterOpen);
            offsetSamples.insert(shutterClose);

            double offset = (shutterClose - shutterOpen) / (numSamples-1);
            double curVal = shutterOpen + offset;
            for (int i = 0; i < numSamples - 2; ++i, curVal += offset)
            {
                offsetSamples.insert(curVal);
            }

            // Add an extra leading or trailing frame on an
            // integer boundary for the rest of the pipeline
            double floorVal = floor(startTime + shutterOpen);
            double ceilVal = ceil(endTime + shutterClose);

            transSamples.insert(floorVal);
            transSamples.insert(ceilVal);
            geoSamples.insert(floorVal);
            geoSamples.insert(ceilVal);

            std::set<double>::iterator samp = origSamples.begin();
            std::set<double>::iterator sampEnd = origSamples.end();
            for (; samp != sampEnd; ++samp)
            {
                double curSamp = *samp;
                std::set<double>::iterator offset = offsetSamples.begin();
                std::set<double>::iterator offsetEnd = offsetSamples.end();
                for (; offset != offsetEnd; ++offset)
                {
                    double curVal = curSamp + (*offset);
                    double rndVal = roundf(curVal);

                    // if the value is close enough to the integer value
                    // insert the integer value
                    if (fabs(curVal - rndVal) < 1e-4)
                    {
                        transSamples.insert(rndVal);

                        // ignore geometry sampling flag because it is a whole
                        // frame and for some reason we always want to
                        // translate the whole frames
                        geoSamples.insert(rndVal);
                    }
                    else if (sampleGeo)
                    {
                        transSamples.insert(curVal);
                        geoSamples.insert(curVal);
                    }
                    else
                    {
                        // we aren't include subsampled geometry
                        transSamples.insert(curVal);
                    }
                }  // for offset
            }  // for samp
        }  // if we need to apply motion blur

        AbcWriteJobPtr job(new AbcWriteJob(dagPath, fileName.c_str(),
            useSelectionList, worldSpace, writeVisibility, writeUVs,
            transSamples, transTime, geoSamples, geoTime,
            melPerFrameCallback, melPostCallback,
            pythonPerFrameCallback, pythonPostCallback, prefixFilter,
            attribsSet));

       jobList.push_front(job);

        // make sure we add additional whole frames, if we arent skipping
        // the inbetween ones
        if (!skipFrame && !allFrameRange.empty() && !transSamples.empty())
        {
            double localMin = *(transSamples.begin());
            std::set<double>::iterator last = transSamples.end();
            last--;
            double localMax = *last;

            double globalMin = *(allFrameRange.begin());
            last = allFrameRange.end();
            last--;
            double globalMax = *last;

            // if the min of our current frame range is beyond
            // what we know about, pad a few more frames
            if (localMin > globalMax)
            {
                for (double f = globalMax; f < localMin; f++)
                {
                    allFrameRange.insert(f);
                }
            }

            // if the max of our current frame range is beyond
            // what we know about, pad a few more frames
            if (localMax < globalMin)
            {
                for (double f = localMax; f < globalMin; f++)
                {
                    allFrameRange.insert(f);
                }
            }
        }

        // right now we just copy over the translation samples since
        // they are guaranteed to contain all the geometry samples
        if (!transSamples.empty())
            allFrameRange.insert(transSamples.begin(), transSamples.end());
    }

    // ================ end of argument parsing =========================

    // add extra evaluation run up, if necessary
    if (startEvaluationTime != FLT_MAX && !allFrameRange.empty())
    {
        double firstFrame = *allFrameRange.begin();
        for (double f = startEvaluationTime; f < firstFrame; ++f)
        {
            allFrameRange.insert(f);
        }
    }

    std::set<double>::iterator it = allFrameRange.begin();
    std::set<double>::iterator itEnd = allFrameRange.end();

    // loop through every frame in the list, if a job has that frame in it's
    // list of transform or shape frames, then it will write out data and
    // call the perFrameCallback, if that frame is also the last one it has
    // to work on then it will also call the postCallback.
    // If it doesn't have this frame, then it does nothing
    for (; it != itEnd; it++)
    {
        if (debug)
        {
            double frame = *it;
            MString info;
            info = frame;
            MGlobal::displayInfo(info);
        }

        MGlobal::viewFrame(*it);
        std::list< AbcWriteJobPtr >::iterator j = jobList.begin();
        std::list< AbcWriteJobPtr >::iterator jend = jobList.end();
        while (j != jend)
        {
            bool lastFrame = (*j)->eval(*it);

            //
            if (lastFrame)
            {
                j = jobList.erase(j);
            }
            else
                j++;
        }
    }

    // set the time back
    MGlobal::viewFrame(oldCurTime);

    return MS::kSuccess;
}