예제 #1
0
rigid_body_t::pointer boingRbCmd::getPointerFromName(MString &name)
{
    
    rigid_body_t::pointer rb = 0;
    
    shared_ptr<solver_impl_t> solv = solver_t::get_solver();
    std::set<rigid_body_t::pointer> rbds = solver_t::get_rigid_bodies();
    shared_ptr<bSolverNode> b_solv = bSolverNode::get_bsolver_node();
    MStringArray names = b_solv->get_all_keys();
    for( int i=0; i<names.length(); i++) {
        bSolverNode::m_custom_data * data = b_solv->getdata(names[i]);
        if (NULL != data) {
            if (name == data->name) {
                rb = data->m_rigid_body;
                break;
            }
        } 
    }
    
    return rb;
}
예제 #2
0
MStatus peltOverlap::parseArgs( const MArgList& args )
{
    MStatus		status = MS::kSuccess;
    MArgDatabase	argData(syntax(), args);

    if (argData.isFlagSet(kExitFlag)) {
        status = argData.getFlagArgument(kExitFlag, 0, fNthPairs);
        if (status != MS::kSuccess) {
            MGlobal::displayError("-ea/exitAfterNthPairs is missing an int argument");
            return status;
        }
    }

    status = argData.getObjects(fShadingGroups);
    if (status != MS::kSuccess || fShadingGroups.length() < 1) {
        MGlobal::displayError("Missing shading group(s) input");
        status = MS::kFailure;
    }

    return status;
}
// Get semantic string back from enum:
MString& CUniformParameterBuilder::getLightParameterSemantic(int lightParameterType) {

	if (lightParameterType < 0 || lightParameterType >= eLastParameterType)
		lightParameterType = eUndefined;

	static MStringArray semanticNames;

	if (!semanticNames.length()) {
		semanticNames.append(dx11ShaderSemantic::kUndefined);
		semanticNames.append(dx11ShaderSemantic::kPosition);
		semanticNames.append(dx11ShaderSemantic::kDirection);
		semanticNames.append(dx11ShaderSemantic::kLightColor);
		semanticNames.append(dx11ShaderSemantic::kLightSpecularColor);
		semanticNames.append(dx11ShaderSemantic::kLightAmbientColor);
		semanticNames.append(dx11ShaderSemantic::kLightDiffuseColor);
		semanticNames.append(dx11ShaderSemantic::kLightRange);          // Not recognized!
		semanticNames.append(dx11ShaderSemantic::kFalloff);
		semanticNames.append(dx11ShaderSemantic::kLightAttenuation0);   // Not recognized!
		semanticNames.append(dx11ShaderSemantic::kLightAttenuation1);   // Not recognized!
		semanticNames.append(dx11ShaderSemantic::kLightAttenuation2);   // Not recognized!
		semanticNames.append(dx11ShaderSemantic::kLightTheta);   // Not recognized!
		semanticNames.append(dx11ShaderSemantic::kLightPhi);   // Not recognized!
		semanticNames.append(dx11ShaderSemantic::kShadowMap);
		semanticNames.append(dx11ShaderSemantic::kShadowMapBias);
		semanticNames.append(dx11ShaderSemantic::kShadowColor);
		semanticNames.append(dx11ShaderSemantic::kShadowMapMatrix);
		semanticNames.append(dx11ShaderSemantic::kShadowFlag);
		semanticNames.append(dx11ShaderSemantic::kLightIntensity);
		semanticNames.append(dx11ShaderSemantic::kHotspot);
		semanticNames.append(dx11ShaderSemantic::kLightEnable);
		semanticNames.append(dx11ShaderSemantic::kLightType);
		semanticNames.append(dx11ShaderSemantic::kDecayRate);
		semanticNames.append(dx11ShaderSemantic::kAreaPosition0);
		semanticNames.append(dx11ShaderSemantic::kAreaPosition1);
		semanticNames.append(dx11ShaderSemantic::kAreaPosition2);
		semanticNames.append(dx11ShaderSemantic::kAreaPosition3);
	}
	return semanticNames[lightParameterType];
}
예제 #4
0
//
// Write out the "fileInfo" command for the freeform information associated
// with the scene.
//
void maTranslator::writeFileInfo(fstream& f)
{
	//
	// There's no direct access to the scene's fileInfo from within the API,
	// so we have to call MEL's 'fileInfo' command.
	//
	MStringArray	fileInfo;

	if (MGlobal::executeCommand("fileInfo -q", fileInfo))
	{
		unsigned	numEntries = fileInfo.length();
		unsigned	i;

		for (i = 0; i < numEntries; i += 2)
		{
			f << "fileInfo " << quote(fileInfo[i]).asChar() << " "
					<< quote(fileInfo[i+1]).asChar() << ";" << endl;
		}
	}
	else
		MGlobal::displayWarning("Could not get scene's fileInfo.");
}
예제 #5
0
MStatus 
XmlCacheFormat::readFloatVectorArray( MFloatVectorArray& array, unsigned arraySize )
{
	MStringArray value;
	readXmlTagValue(floatVectorArrayTag, value);

	assert( value.length() == arraySize * 3 );

	array.clear();
	array.setLength( arraySize );
	for (unsigned i = 0; i < arraySize; i++ )
	{
		float v[3];
		v[0] = (float)strtod( value[i*3].asChar(), NULL );
		v[1] = (float)strtod( value[i*3+1].asChar(), NULL );
		v[2] = (float)strtod( value[i*3+2].asChar(), NULL );

		array.set(v,i);
	}

	return MS::kSuccess;
}
예제 #6
0
bool AbcWriteJob::checkInstance(MDagPath dag, MayaTransformWriterPtr iParent)
{
    MFnDagNode fnDagNode(dag.node());
    if (fnDagNode.isInstanced(false))
    {
        MDagPathArray paths;
        fnDagNode.getAllPaths(paths);
        if (!(mCurDag == paths[0]))
        {
            MStringArray pathparts;
            paths[0].fullPathName().split('|', pathparts);
            Alembic::Abc::OObject rootobj = mRoot.getTop();
            Alembic::Abc::OObject tmpobj(rootobj);
            std::string tmpstring;
            unsigned partscount = pathparts.length();
            for (unsigned i(0); i < partscount; i++)
            {
                tmpstring = pathparts[i].asChar();
                tmpobj = tmpobj.getChild(tmpstring);

                // for selections of non-root objects, the first parts of a dag will not be a child of mRoot
                // traverse hierarchy until valid matching child is found, break loop only if each part of dag is invalid
                if (!tmpobj.valid())
                {
                    if (i == (partscount - 1))
                        break;
                    tmpobj = rootobj;
                }
            }
            if (tmpobj.valid())
            {
                iParent->getObject().addChildInstance(tmpobj, fnDagNode.name().asChar());
                return true;
            }
        }
    }
    return false;
}
    // --------------------------------------
    void ReferenceManager::initialize()
    {
        deleteReferences ();
        deleteFiles ();

        if ( !ExportOptions::exportXRefs() || ExportOptions::dereferenceXRefs() ) return;

#if MAYA_API_VERSION >= 600

        MStatus status;
        MStringArray referenceFilenames;
        MFileIO::getReferences ( referenceFilenames );

        uint referenceCount = referenceFilenames.length();
        mReferences.reserve( referenceCount );
        for (uint i = 0; i < referenceCount; ++i)
        {
            MString& filename = referenceFilenames[i];
            MObject referenceNode = getReferenceNode ( filename );
            if ( referenceNode != MObject::kNullObj ) processReference ( referenceNode );
        }
#endif
    }
예제 #8
0
MStatus
XmlCacheFormat::readDoubleVectorArray( MVectorArray& array, unsigned arraySize )
{
	MStringArray value;
	if( !readXmlTagValue(doubleVectorArrayTag, value) )
	{
		return MS::kFailure;
	}

	assert( value.length() == arraySize * 3 );
	array.setLength( arraySize );
	for (unsigned i = 0; i < arraySize; i++ )
	{
		double v[3];
		v[0] = strtod( value[i*3].asChar(), NULL );
		v[1] = strtod( value[i*3+1].asChar(), NULL );
		v[2] = strtod( value[i*3+2].asChar(), NULL );

		array.set( v, i );
	}
	
	return MS::kSuccess;
}
예제 #9
0
MStatus uninitializePlugin( MObject obj)
{
	MStatus   status;
	MFnPlugin plugin( obj );

	// Loop through all the ids and remove the callbacks
	//
	int i;
	int len = eventNames.length();

	for (i = 0; i < len; ++i)
	{
		if (callbackId[i] != 0)
		{
			MGlobal::displayWarning("Removing callback for " +
									eventNames[i] +
									"\n");
			MMessage::removeCallback(callbackId[i]);
			callbackId[i] = 0;
		}
	}

	eventNames.clear();

	delete [] callbackId;

	// Deregister the command
	//
	status = plugin.deregisterCommand("eventTest");

	if (!status)
	{
		status.perror("deregisterCommand");
	}

	return status;
}
void OutputMaterials(MSelectionList selected){
	
	//::output << "BRUS";//header Brush
	//StartChunck();
MString temp;
MString affich;
	

	
int MatExists=0;

	for(int i=0;i<selected.length();i++){
Affich("element selectioné");

	MDagPath path;
	MObject obj;
	
	int index;
	selected.getDagPath(i,path);
	index = path.childCount();
	affich ="childs ";affich+=index;
	Affich(affich);

	selected.getDependNode(index,obj);


	
	
	//obj=path.child(0);//.child(0);

	

	//MFnMesh fn(path);
	//obj=fn.parent(0);
	//path.getPath(path);
	MFnMesh fna(path.child(1));
	
	
	unsigned int instancenumbers;
	MObjectArray shaders;
	MIntArray indices;
	
	fna.getConnectedShaders(instancenumbers,shaders,indices);

	affich = "shaders lenght "; 
	affich += shaders.length();
Affich(affich);

switch(shaders.length()) {

		// if no shader applied to the mesh instance
		case 0:
			{
				//***************Affich("pas de matériaux");
			}
			break;

		// if all faces use the same material
	
		// if more than one material is used, write out the face indices the materials
		// are applied to.
		default:
			{
				//************************Affich("trouvé plusieurs matériaux");

				
				//write_int(shaders.length());

				// now write each material and the face indices that use them
				
				for(int j=0;j < shaders.length();++j)
				{						
					for(int matest=0;matest<Matid.length();matest++){
						//**************************Affich(Matid[matest].asChar());
						//*****************************Affich(GetShaderName( shaders[j] ).asChar());
						if(Matid[matest]== GetShaderName( shaders[j] )){
						MatExists = 1;
						
						}//fin if matid
						
						}// fin for matest
					if(MatExists != 1){
					//*****************************Affich("matériau absent de la liste, enregistrement");
					Matid.append(GetShaderName( shaders[j] ).asChar());
					::output << "BRUS";//header Brush
						StartChunck();
							//write_int(Matid.length());//id Brush
						//écrire le nb de textures
						int a=nb_Tex_by_Brush[Matid.length()-1];
						if (a==0) a=1;
						info="nb de textures pour ce brush ";
						info+=nb_Tex_by_Brush[Matid.length()-1];
						Affich(info);

							write_int(a);//nb textures in brush
	
						::output << GetShaderName( shaders[j] ).asChar();
						::output << char(0x00);
						
						
					OutputColors(shaders[j],"color");


						//red
						//write_float(0);
						//green
						//write_float(1);
						//blue
						//write_float(0);
						//alpha
						//write_float(1);
						//shininess
						write_float(0);
						// Brush Blend
						//brush - brush handle
						//blend -
						//1: alpha
						//2: multiply (default)
						//3: add
						write_int(0);
						//blend FX
						//brush - brush handle
						//fx -
						//1: full-bright
						//2: use vertex colors instead of brush color +shininess
						//3:just vertex color no shininess
						//4: flatshaded
						//8: disable fog  
						int flag=0;
						if (Flags.use_vertex_colors==1 && Flags.vertex_colors==1) flag=3; // par défaut 0
						write_int(flag);// écriture uniquement des vertex
						
						//écrire les id textures
						
						
						if (nb_Tex_by_Brush[Matid.length()-1]==0){
							a=-1;
						}else{
						a=Texids_by_brush[Matid.length()-1];
						}
						info="texid ";
						info+=a;
						Affich(info);
						write_int(a);//int texture_id   -1  no texture for this brush
						
						EndChunck();
					//Affich(temp);
					}else {
					//*************************************	Affich("matériau existe dans la liste");
					}// fin if matexists
					
					MatExists = 0;
						

				}//fin for j shaders
			}// fin case default
			break;
		}//fin switches

	}//fin for selected
		


}// fin output materials
void ToMayaMeshConverter::addUVSet( MFnMesh &fnMesh, const MIntArray &polygonCounts, IECore::ConstMeshPrimitivePtr mesh, const std::string &sPrimVarName, const std::string &tPrimVarName, const std::string &stIdPrimVarName, MString *uvSetName ) const
{
	IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( sPrimVarName );
	bool haveS = sIt != mesh->variables.end();
	IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( tPrimVarName );
	bool haveT = tIt != mesh->variables.end();
	IECore::PrimitiveVariableMap::const_iterator stIdIt = mesh->variables.find( stIdPrimVarName );
	bool haveSTId = stIdIt != mesh->variables.end();

	if ( haveS && haveT )
	{
		if ( sIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying )
		{
			IECore::msg( IECore::Msg::Warning,"ToMayaMeshConverter::doConversion",  boost::format(  "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % sPrimVarName );
			return;
		}

		if ( tIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % tPrimVarName);
			return;
		}

		if ( !sIt->second.data )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % sPrimVarName );
		}

		if ( !tIt->second.data )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % tPrimVarName );
		}

		/// \todo Employ some M*Array converters to simplify this
		int numUVs = mesh->variableSize( IECore::PrimitiveVariable::FaceVarying );

		IECore::ConstFloatVectorDataPtr u = IECore::runTimeCast<const IECore::FloatVectorData>(sIt->second.data);

		if ( !u )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % sPrimVarName % sIt->second.data->typeName() );
			return;
		}

		assert( (int)u->readable().size() == numUVs );
		
		IECore::ConstFloatVectorDataPtr v = IECore::runTimeCast<const IECore::FloatVectorData>(tIt->second.data);
		if ( !v )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % tPrimVarName % tIt->second.data->typeName() );
			return;
		}

		assert( (int)v->readable().size() == numUVs );
		
		const std::vector<float> &uAll = u->readable();
		const std::vector<float> &vAll = v->readable();

		if ( uvSetName )
		{
			bool setExists = false;
			MStringArray existingSets;
			fnMesh.getUVSetNames( existingSets );
			for ( unsigned i=0; i < existingSets.length(); ++i )
			{
				if ( *uvSetName == existingSets[i] )
				{
					fnMesh.clearUVs( uvSetName );
					setExists = true;
					break;
				}
			}
			
			if ( !setExists )
			{
				MDagPath dag;
				MStatus s = fnMesh.getPath( dag );
				if ( s )
				{
					fnMesh.createUVSetWithName( *uvSetName );
				}
				else
				{
					fnMesh.createUVSetDataMeshWithName( *uvSetName );
				}
			}
		}
		
		MIntArray uvIds;
		uvIds.setLength( numUVs );
		MFloatArray uArray;
		MFloatArray vArray;
		
		if( haveSTId )
		{
			// Get compressed uv values by matching them with their uvId.
			IECore::ConstIntVectorDataPtr uvId = IECore::runTimeCast<const IECore::IntVectorData>(stIdIt->second.data);
			if ( !uvId )
			{
				IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % stIdPrimVarName % stIdIt->second.data->typeName() );
				return;
			}
			
			const std::vector<int> &uvIdData = uvId->readable();
	
			assert( (int)uvIdData.size() == numUVs );
			
			int highestId = 0;
			for ( int i = 0; i < numUVs; i++)
			{
				uvIds[i] = uvIdData[i];
				if( uvIdData[i] > highestId )
				{
					highestId = uvIdData[i];
				}
			}
			
			// u and v arrays need only be as long as the number of unique uvIds
			uArray.setLength( highestId + 1 );
			vArray.setLength( highestId + 1 );
			
			for ( int i = 0; i < numUVs; i++ )
			{
				uArray[ uvIds[i] ] = uAll[i];
				// FromMayaMeshConverter does the opposite of this
				vArray[ uvIds[i] ] = 1 - vAll[i];
			}
		}
		else
		{
			// If for some reason we cannot find the uv indices, set the UVs using the old way
			// the performances in maya won't be good (for weigth painting in particular)
			uArray.setLength( numUVs );
			vArray.setLength( numUVs );

			for ( int i = 0; i < numUVs; i++)
			{
				uArray[i] = u->readable()[i];
				// FromMayaMeshConverter does the opposite of this
				vArray[i] = 1 - v->readable()[i];
			}
			
			for ( int i = 0; i < numUVs; i++)
			{
				uvIds[i] = i;
			}
		}
		
		MStatus s = fnMesh.setUVs( uArray, vArray, uvSetName );
		if ( !s )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to set UVs." );
			return;
		}

		s = fnMesh.assignUVs( polygonCounts, uvIds, uvSetName );
		if ( !s )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to assign UVs." );
			return;
		}

	}
	else if ( haveS )
	{
		IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % sPrimVarName % tPrimVarName );
	}
	else if ( haveT )
	{
		IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % tPrimVarName % sPrimVarName );
	}
	else
	{
		assert( !uvSetName );
	}
}
예제 #12
0
/** Create a RIB compatible representation of a Maya polygon mesh.
 */
liqRibMeshData::liqRibMeshData( MObject mesh )
: numFaces( 0 ),
  numPoints ( 0 ),
  numNormals ( 0 ),
  nverts(),
  verts(),
  vertexParam(NULL),
  normalParam(NULL)
{
	CM_TRACE_FUNC("liqRibMeshData::liqRibMeshData("<<MFnDagNode(mesh).fullPathName().asChar()<<")");

	unsigned int i;
	unsigned int j;
  areaLight = false;
  LIQDEBUGPRINTF( "-> creating mesh\n" );
  MFnMesh fnMesh( mesh );
  objDagPath = fnMesh.dagPath();
  MStatus astatus;
  
  name = fnMesh.name();
  areaLight =( liquidGetPlugValue( fnMesh, "areaIntensity", areaIntensity, astatus ) == MS::kSuccess )? true : false ; 

  if ( areaLight ) 
  {
    MDagPath meshDagPath;
    meshDagPath = fnMesh.dagPath();
    MTransformationMatrix worldMatrix = meshDagPath.inclusiveMatrix();
    MMatrix worldMatrixM = worldMatrix.asMatrix();
    worldMatrixM.get( transformationMatrix );
  }

  numPoints = fnMesh.numVertices();
  numNormals = fnMesh.numNormals();

  // UV sets -------------------
  //
  //const unsigned numSTs( fnMesh.numUVs() );
  const unsigned numUVSets( fnMesh.numUVSets() );
  MString currentUVSetName;
  MStringArray extraUVSetNames;
  fnMesh.getCurrentUVSetName( currentUVSetName );
  {
    MStringArray UVSetNames;
    fnMesh.getUVSetNames( UVSetNames );

    for ( unsigned i( 0 ); i<numUVSets; i++ ) 
      if ( UVSetNames[i] != currentUVSetName ) 
        extraUVSetNames.append( UVSetNames[i] );
  }

  numFaces = fnMesh.numPolygons();
  const unsigned numFaceVertices( fnMesh.numFaceVertices() );

	if ( numPoints < 1 )
	{
//		MGlobal::displayInfo( MString( "fnMesh: " ) + fnMesh.name() );
//		cerr << "Liquid : Could not export degenerate mesh '"<< fnMesh.fullPathName( &astatus ).asChar() << "'" << endl << flush;
		return;
	}

  unsigned face = 0;
  unsigned faceVertex = 0;
  unsigned count;
  unsigned vertex;
  unsigned normal;
  float S;
  float T;
  MPoint point;
  liqTokenPointer pointsPointerPair;
  liqTokenPointer normalsPointerPair;
  liqTokenPointer pFaceVertexSPointer;
  liqTokenPointer pFaceVertexTPointer;

  // Allocate memory and tokens
  numFaces = numFaces;
  nverts = shared_array< liqInt >( new liqInt[ numFaces ] );
  verts = shared_array< liqInt >( new liqInt[ numFaceVertices ] );

  pointsPointerPair.set( "P", rPoint, numPoints );
  pointsPointerPair.setDetailType( rVertex );

  if ( numNormals == numPoints ) 
  {
    normalsPointerPair.set( "N", rNormal, numPoints );
    normalsPointerPair.setDetailType( rVertex );
  } 
  else 
  {
    normalsPointerPair.set( "N", rNormal, numFaceVertices );
    normalsPointerPair.setDetailType( rFaceVarying );
  }
  	
  // uv
  std::vector<liqTokenPointer> UVSetsArray;
  UVSetsArray.reserve( 1 + extraUVSetNames.length() );

  liqTokenPointer currentUVSetUPtr;
  liqTokenPointer currentUVSetVPtr;
  liqTokenPointer currentUVSetNamePtr;
  liqTokenPointer extraUVSetsUPtr;
  liqTokenPointer extraUVSetsVPtr;
  liqTokenPointer extraUVSetsNamePtr;
  if(liqglo.liqglo_outputMeshAsRMSArrays)
  {
	  currentUVSetUPtr.set( "s", rFloat, numFaceVertices );
	  currentUVSetUPtr.setDetailType( rFaceVarying );

	  currentUVSetVPtr.set( "t", rFloat, numFaceVertices );
	  currentUVSetVPtr.setDetailType( rFaceVarying );

	  currentUVSetNamePtr.set( "currentUVSet", rString, 1 );
	  currentUVSetNamePtr.setDetailType( rConstant );

	  if( numUVSets > 1 )
	  {
		  extraUVSetsUPtr.set( "u_uvSet", rFloat, numFaceVertices, numUVSets-1 );
		  extraUVSetsUPtr.setDetailType( rFaceVarying );

		  extraUVSetsVPtr.set( "v_uvSet", rFloat, numFaceVertices, numUVSets-1 );
		  extraUVSetsVPtr.setDetailType( rFaceVarying );

		  extraUVSetsNamePtr.set( "extraUVSets", rString, numUVSets-1 );
		  extraUVSetsNamePtr.setDetailType( rConstant );
	  }
  }
  else
  {
	  if ( numUVSets > 0 ) 
	  {
		liqTokenPointer pFaceVertexPointerPair;

		pFaceVertexPointerPair.set( "st", rFloat, numFaceVertices, 2 );
		pFaceVertexPointerPair.setDetailType( rFaceVarying );

		UVSetsArray.push_back( pFaceVertexPointerPair );

		for ( unsigned j( 0 ); j<extraUVSetNames.length(); j++) 
		{
		  liqTokenPointer pFaceVertexPointerPair;

		  pFaceVertexPointerPair.set( extraUVSetNames[j].asChar(), rFloat, numFaceVertices, 2 );
		  pFaceVertexPointerPair.setDetailType( rFaceVarying );

		  UVSetsArray.push_back( pFaceVertexPointerPair );
		}

		if( liqglo.liqglo_outputMeshUVs ) 
		{
		  // Match MTOR, which also outputs face-varying STs as well for some reason - Paul
		  // not anymore - Philippe
		  pFaceVertexSPointer.set( "u", rFloat, numFaceVertices );
		  pFaceVertexSPointer.setDetailType( rFaceVarying );

		  pFaceVertexTPointer.set( "v", rFloat, numFaceVertices );
		  pFaceVertexTPointer.setDetailType( rFaceVarying );
		}
	  }
  }

  vertexParam = pointsPointerPair.getTokenFloatArray();
  normalParam = normalsPointerPair.getTokenFloatArray();

  // Read the mesh from Maya
  MFloatVectorArray normals;
  fnMesh.getNormals( normals );

  for ( MItMeshPolygon polyIt ( mesh ); polyIt.isDone() == false; polyIt.next() ) 
  {
    count = polyIt.polygonVertexCount();
    nverts[face] = count;
	for( i=0; i<count; i++ )    // boucle sur les vertex de la face
    {
      vertex = polyIt.vertexIndex( i );
      verts[faceVertex] = vertex;
      point = polyIt.point( i, MSpace::kObject );
      pointsPointerPair.setTokenFloat( vertex, point.x, point.y, point.z );
      normal = polyIt.normalIndex( i );

      if( numNormals == numPoints ) 
        normalsPointerPair.setTokenFloat( vertex, normals[normal].x, normals[normal].y, normals[normal].z );
      else 
        normalsPointerPair.setTokenFloat( faceVertex, normals[normal].x, normals[normal].y, normals[normal].z );

	  if( liqglo.liqglo_outputMeshAsRMSArrays )
	  {
		  for( j=0; j<numUVSets; j++ )
		  {
			  if(j==0)
			  {
				  MString uvSetName = currentUVSetName;
				  // set uvSet name
				  currentUVSetNamePtr.setTokenString( 0, currentUVSetName.asChar() );
				  // set uv values
				  fnMesh.getPolygonUV( face, i, S, T, &uvSetName );

				  currentUVSetUPtr.setTokenFloat( faceVertex, S );
				  currentUVSetVPtr.setTokenFloat( faceVertex, 1-T );
			  }
			  else
			  {
				  MString uvSetName = extraUVSetNames[j-1];
				  // set uvSet name
				  extraUVSetsNamePtr.setTokenString( j-1, extraUVSetNames[j-1].asChar() );
				  // set uv values
				  fnMesh.getPolygonUV( face, i, S, T, &uvSetName );
				  extraUVSetsUPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, S );
				  extraUVSetsVPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, 1-T );
			  }
		  }
	  }
	  else
	  {
		  if ( numUVSets ) 
		  {
			  for( j=0; j<numUVSets; j++ )
			  {
				  MString uvSetName;
				  if(j==0)
				  {
					  uvSetName = currentUVSetName;
				  }
				  else
				  {
					  uvSetName = extraUVSetNames[j-1];
				  }
				  fnMesh.getPolygonUV( face, i, S, T, &uvSetName );
				  UVSetsArray[j].setTokenFloat( faceVertex, 0, S );
				  UVSetsArray[j].setTokenFloat( faceVertex, 1, 1-T );
				  //printf("V%d  %s : %f %f  =>  %f %f \n", i, uvSetName.asChar(), S, T, S, 1-T);

				  if( liqglo.liqglo_outputMeshUVs && j==0)
				  {
					  // Match MTOR, which always outputs face-varying STs as well for some reason - Paul
					  pFaceVertexSPointer.setTokenFloat( faceVertex, S );
					  pFaceVertexTPointer.setTokenFloat( faceVertex, 1-T );
				  }
			  }
		  }
		}
      // printf( "[%d] faceVertex = %d  vertex = %d\n", i, faceVertex, vertex );

      ++faceVertex;
    }
    ++face;
  }
  // Add tokens to array and clean up after
  tokenPointerArray.push_back( pointsPointerPair );
  tokenPointerArray.push_back( normalsPointerPair );

  if(liqglo.liqglo_outputMeshAsRMSArrays)
  {
	  tokenPointerArray.push_back( currentUVSetNamePtr );
	  tokenPointerArray.push_back( currentUVSetUPtr );
	  tokenPointerArray.push_back( currentUVSetVPtr );
	  if( numUVSets > 1 )
	  {
		  tokenPointerArray.push_back( extraUVSetsNamePtr );
		  tokenPointerArray.push_back( extraUVSetsUPtr );
		  tokenPointerArray.push_back( extraUVSetsVPtr );
	  }
  }
  else
  {
	  if( UVSetsArray.size() ) 
		  tokenPointerArray.insert( tokenPointerArray.end(), UVSetsArray.begin(), UVSetsArray.end() );

	  if( liqglo.liqglo_outputMeshUVs ) 
	  {
		  tokenPointerArray.push_back( pFaceVertexSPointer );
		  tokenPointerArray.push_back( pFaceVertexTPointer );
	  }
  }

  addAdditionalSurfaceParameters( mesh );
}
예제 #13
0
//-----------------------------------------------------------------------------
// Purpose: Export the specified bits of the maya scene into the specified file
// Input  : i_mArgDatabase	The command line arguments as passed
// Output : MS::kSuccess if ok, MS::kFailure otherwise
//-----------------------------------------------------------------------------
MStatus CVstSmdIOCmd::DoExport(
	const MArgDatabase &mArgDatabase )
{
	MString optFilename;
	if ( mArgDatabase.getFlagArgument( kOptFilename, 0, optFilename ) != MS::kSuccess || optFilename.length() == 0 )
	{
		MGlobal::displayError( "No filename specified for export" );
		return MS::kFailure;
	}

	MSelectionList optSelectionList;
	if ( GetOptSelection( mArgDatabase, optSelectionList ) != MS::kSuccess )
		return MS::kFailure;

	const uint exportType( GetExportType( mArgDatabase ) );

	const uint exportFlags( GetExportFlags( mArgDatabase ) );

	const uint version(
		mArgDatabase.isFlagSet( kOptRelativeMaterials ) &&
		exportType & ( CSmdExport::kModel | CSmdExport::kPhysModel | CSmdExport::kVertexAnimation ) ? 2 : 1 );

	CSmdExport smdExport( exportType, exportFlags, version );

	smdExport.SetNodeAddPrefix( GetNodeAddPrefix( mArgDatabase ) );
	smdExport.SetNodeDelPrefix( GetNodeDelPrefix( mArgDatabase ) );

	if ( exportType & CSmdExport::kAnimation )
	{
		double fs( 0.0 );
		double fe( 0.0 );
		double fi( 1.0 );

		GetExportFrameRange( mArgDatabase, fs, fe, fi );

		smdExport.SetFrameRange( fs, fe, fi );
	}

	MStringArray result;

	if ( smdExport.DoIt( optFilename, optSelectionList, result ) != MS::kSuccess )
		return MS::kFailure;

	if ( result.length() )
	{
		result.append( "smd" );
		result.append( optFilename );
	}
	else
	{
		result.append( MString( "Exported to " ) + optFilename );
	}

	if ( mArgDatabase.isFlagSet( kOptQci ) )
	{
		MString optQci;
		mArgDatabase.getFlagArgument( kOptQci, 0, optQci );
		MSelectionList qciSelectionList;
		if ( mArgDatabase.isFlagSet( kOptSelection ) )
		{
			mArgDatabase.getObjects( qciSelectionList );
		}

		MStringArray qciResult;
		CQciExport qciExport;
		if ( qciExport.DoIt( optQci, qciSelectionList, qciResult ) && qciResult.length() )
		{
			for ( uint i( 0 ); i != qciResult.length(); ++i )
			{
				result.append( qciResult[ i ] );
			}
		}
	}

	setResult( result );

	return MS::kSuccess;
}
예제 #14
0
/*
 *  get maya poly mesh data
 */
bool liqRibMeshData::getMayaData( MObject mesh, bool useNormals )
{
  bool ret = true;
  
  // LIQDEBUGPRINTF( "-> mesh getMayaData (useNormals = %s )\n", ( ( useNormals )? "Yes" : "No" ) );

  MFnMesh fnMesh( mesh );
  objDagPath = fnMesh.dagPath();
  MStatus astatus;
  
  name = fnMesh.name();
  longName = fnMesh.fullPathName();

  numPoints = fnMesh.numVertices();
  numFaces = fnMesh.numPolygons();
  if ( useNormals ) numNormals = fnMesh.numNormals();
  
  if ( numPoints < 1 )
	{
	  liquidMessage( "Could not export degenerate mesh " + longName, messageInfo );
		return false;
	}
	// UV sets -------------------
  //
  //const unsigned numSTs( fnMesh.numUVs() );
  const unsigned numUVSets( fnMesh.numUVSets() );
  MString currentUVSetName;
	fnMesh.getCurrentUVSetName( currentUVSetName );
  MStringArray extraUVSetNames;
  MStringArray UVSetNames;
  fnMesh.getUVSetNames( UVSetNames );

  for ( unsigned i( 0 ); i < numUVSets ; i++ ) 
    if ( UVSetNames[i] != currentUVSetName ) 
      extraUVSetNames.append( UVSetNames[i] );
  
  const unsigned numFaceVertices( fnMesh.numFaceVertices() );
  unsigned face ( 0 );
  unsigned faceVertex ( 0 );
  unsigned count;
  unsigned vertex;
  unsigned normal;
  float S;
  float T;
  MPoint point;
  liqTokenPointer pointsPointerPair;
  liqTokenPointer normalsPointerPair;
  liqTokenPointer pFaceVertexSPointer;
  liqTokenPointer pFaceVertexTPointer;
  
  // Allocate memory and tokens
  nverts = shared_array< RtInt >( new RtInt[ numFaces ] );
  verts = shared_array< RtInt >( new RtInt[ numFaceVertices ] );

  pointsPointerPair.set( "P", rPoint, numPoints );
  pointsPointerPair.setDetailType( rVertex );

  if ( useNormals )
  {
    if ( numNormals == numPoints ) 
    {
      normalsPointerPair.set( "N", rNormal, numPoints );
      normalsPointerPair.setDetailType( rVertex );
    } 
    else 
    {
      normalsPointerPair.set( "N", rNormal, numFaceVertices );
      normalsPointerPair.setDetailType( rFaceVarying );
    }
  }
  // uv
  std::vector<liqTokenPointer> UVSetsArray;
  UVSetsArray.reserve( 1 + extraUVSetNames.length() );
	liqTokenPointer currentUVSetUPtr;
	liqTokenPointer currentUVSetVPtr;
	liqTokenPointer currentUVSetNamePtr;
	liqTokenPointer extraUVSetsUPtr;
	liqTokenPointer extraUVSetsVPtr;
	liqTokenPointer extraUVSetsNamePtr;
	
	if ( liqglo_outputMeshAsRMSArrays )
	{
		currentUVSetUPtr.set( "s", rFloat, numFaceVertices );
		currentUVSetUPtr.setDetailType( rFaceVarying );

		currentUVSetVPtr.set( "t", rFloat, numFaceVertices );
		currentUVSetVPtr.setDetailType( rFaceVarying );

		currentUVSetNamePtr.set( "currentUVSet", rString, 1 );
		currentUVSetNamePtr.setDetailType( rConstant );
		
		if ( numUVSets > 1 )
		{
			extraUVSetsUPtr.set( "u_uvSet", rFloat, numFaceVertices, numUVSets-1 );
			extraUVSetsUPtr.setDetailType( rFaceVarying );

			extraUVSetsVPtr.set( "v_uvSet", rFloat, numFaceVertices, numUVSets-1 );
			extraUVSetsVPtr.setDetailType( rFaceVarying );

			extraUVSetsNamePtr.set( "extraUVSets", rString, numUVSets-1 );
			extraUVSetsNamePtr.setDetailType( rConstant );
		}
	}
  else
	{
		if ( numUVSets > 0 )
  	{
   	 	liqTokenPointer pFaceVertexPointerPair;

    	pFaceVertexPointerPair.set( "st", rFloat, numFaceVertices, 2 );
    	pFaceVertexPointerPair.setDetailType( rFaceVarying );

    	UVSetsArray.push_back( pFaceVertexPointerPair );

    	for ( unsigned j( 0 ); j < extraUVSetNames.length() ; j++ ) 
    	{
      	liqTokenPointer pFaceVertexPointerPair;

      	pFaceVertexPointerPair.set( extraUVSetNames[j].asChar(), rFloat, numFaceVertices, 2 );
      	pFaceVertexPointerPair.setDetailType( rFaceVarying );

      	UVSetsArray.push_back( pFaceVertexPointerPair );
    	}

    	if ( liqglo_outputMeshUVs ) 
    	{
      	// Match MTOR, which also outputs face-varying STs as well for some reason - Paul
      	// not anymore - Philippe
      	pFaceVertexSPointer.set( "u", rFloat, numFaceVertices );
      	pFaceVertexSPointer.setDetailType( rFaceVarying );

      	pFaceVertexTPointer.set( "v", rFloat, numFaceVertices );
      	pFaceVertexTPointer.setDetailType( rFaceVarying );
    	}
		}
  }
  vertexParam = pointsPointerPair.getTokenFloatArray();
  MFloatVectorArray normals;

  // Read the mesh normals from Maya
  if ( useNormals ) 
  { 
    normalParam = normalsPointerPair.getTokenFloatArray();
    fnMesh.getNormals( normals );
  }
  for ( MItMeshPolygon polyIt ( mesh ); polyIt.isDone() == false ; polyIt.next() ) 
  {
    count = polyIt.polygonVertexCount();
    nverts[face] = count;
    unsigned j, i = count;
	  
    // printf("poly count = %d\n", count );
    
    while ( i )
    {
      --i;
      vertex = polyIt.vertexIndex( i );
      verts[faceVertex] = vertex;
      point = polyIt.point( i, MSpace::kObject );
      pointsPointerPair.setTokenFloat( vertex, point.x, point.y, point.z );
      
      if ( useNormals )
      {
        normal = polyIt.normalIndex( i );
        if ( numNormals == numPoints ) 
          normalsPointerPair.setTokenFloat( vertex, normals[normal].x, normals[normal].y, normals[normal].z );
        else 
          normalsPointerPair.setTokenFloat( faceVertex, normals[normal].x, normals[normal].y, normals[normal].z );
      }
      
      if ( liqglo_outputMeshAsRMSArrays )
			{
				for ( j = 0 ; j < numUVSets ; j++ )
				{
					if ( j == 0)
					{
						MString uvSetName = currentUVSetName;
						// set uvSet name
						currentUVSetNamePtr.setTokenString( 0, currentUVSetName.asChar() );
						// set uv values
						fnMesh.getPolygonUV( face, i, S, T, &uvSetName );

						currentUVSetUPtr.setTokenFloat( faceVertex, S );
						currentUVSetVPtr.setTokenFloat( faceVertex, 1-T );
					}
					else
					{
						MString uvSetName = extraUVSetNames[j-1];
						// set uvSet name
						extraUVSetsNamePtr.setTokenString( j-1, extraUVSetNames[j-1].asChar() );
						// set uv values
						fnMesh.getPolygonUV( face, i, S, T, &uvSetName );
						extraUVSetsUPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, S );
						extraUVSetsVPtr.setTokenFloat( (numFaceVertices*(j-1)) + faceVertex, 1-T );
					}
				}
			}
			else
			{
				if ( numUVSets  )
				{
					for( j = 0; j < numUVSets; j++ )
					{
						MString uvSetName = ( j == 0 )? currentUVSetName: extraUVSetNames[ j - 1 ] ;

						fnMesh.getPolygonUV( face, i, S, T, &uvSetName );
						UVSetsArray[j].setTokenFloat( faceVertex, 0, S );
						UVSetsArray[j].setTokenFloat( faceVertex, 1, 1 - T );
						//printf("V%d  %s : %f %f  =>  %f %f \n", i, uvSetName.asChar(), S, T, S, 1-T);

						if ( liqglo_outputMeshUVs && j==0)
						{
							// Match MTOR, which always outputs face-varying STs as well for some reason - Paul
							pFaceVertexSPointer.setTokenFloat( faceVertex, S );
							pFaceVertexTPointer.setTokenFloat( faceVertex, 1 - T );
						}
					}
				}
			}
			++faceVertex;
		}
		++face;
	}
  // Add tokens to array and clean up after
  tokenPointerArray.push_back( pointsPointerPair );
  if ( useNormals ) 
    tokenPointerArray.push_back( normalsPointerPair );
	
	if ( liqglo_outputMeshAsRMSArrays )
	{
		tokenPointerArray.push_back( currentUVSetNamePtr );
		tokenPointerArray.push_back( currentUVSetUPtr );
		tokenPointerArray.push_back( currentUVSetVPtr );
		if ( numUVSets > 1 )
		{
			tokenPointerArray.push_back( extraUVSetsNamePtr );
			tokenPointerArray.push_back( extraUVSetsUPtr );
			tokenPointerArray.push_back( extraUVSetsVPtr );
		}
	}
	else
	{
  	if ( UVSetsArray.size() ) 
    	tokenPointerArray.insert( tokenPointerArray.end(), UVSetsArray.begin(), UVSetsArray.end() );
  
  	if ( liqglo_outputMeshUVs ) 
  	{
    	tokenPointerArray.push_back( pFaceVertexSPointer );
    	tokenPointerArray.push_back( pFaceVertexTPointer );
  	}
	}
  return ret;  
}
/*
	Utility method to update shader parameters based on available
	lighting information.
*/
static void updateLightShader( MHWRender::MShaderInstance *shaderInstance,
						const MHWRender::MDrawContext & context,
						const MSelectionList * lightList )
{
	if (!shaderInstance)
		return;

	// Check pass context information to see if we are in a shadow 
	// map update pass. If so do nothing.
	//
	const MHWRender::MPassContext & passCtx = context.getPassContext();
	const MStringArray & passSem = passCtx.passSemantics();
	bool handlePass = true;
	for (unsigned int i=0; i<passSem.length() && handlePass; i++)
	{
		// Handle special pass drawing.
		//
		if (passSem[i] == MHWRender::MPassContext::kShadowPassSemantic)
		{
			handlePass = false;
		}
	}
	if (!handlePass) return;

	//
	// Perform light shader update with lighting information
	// If the light list is not empty then use that light's information.
	// Otherwise choose the first appropriate light which can cast shadows.
	//

	// Defaults in case there are no lights
	//
	bool globalShadowsOn = false;
	bool localShadowsOn = false;
	bool shadowDirty = false;
	MFloatVector direction(0.0f, 0.0f, 1.0f);
	float lightIntensity = 0.0f; // If no lights then black out the light
	float lightColor[3] = { 0.0f, 0.0f, 0.0f };

	MStatus status;

	// Scan to find the first N lights that has a direction component in it
	// It's possible we find no lights.
	//
	MHWRender::MDrawContext::LightFilter considerAllSceneLights = MHWRender::MDrawContext::kFilteredIgnoreLightLimit;
	unsigned int lightCount = context.numberOfActiveLights(considerAllSceneLights);
	if (lightCount)
	{
		MFloatArray floatVals;
		MIntArray intVals;
		MHWRender::MTextureAssignment shadowResource;
		shadowResource.texture = NULL;
		MHWRender::MSamplerStateDesc samplerDesc;
		MMatrix shadowViewProj;
		float shadowColor[3] = { 0.0f, 0.0f, 0.0f };

		unsigned int i=0;
		bool foundDirectional = false;
		for (i=0; i<lightCount && !foundDirectional ; i++)
		{
			MHWRender::MLightParameterInformation *lightParam = context.getLightParameterInformation( i, considerAllSceneLights );
			if (lightParam)
			{
				// Prune against light list if any.
				if (lightList && lightList->length())
				{
					if (!lightList->hasItem(lightParam->lightPath()))
						continue;
				}

				MStringArray params;
				lightParam->parameterList(params);
				for (unsigned int p=0; p<params.length(); p++)
				{
					MString pname = params[p];

					MHWRender::MLightParameterInformation::StockParameterSemantic semantic = lightParam->parameterSemantic( pname );
					switch (semantic)
					{
						// Pick a few light parameters to pick up as an example
					case MHWRender::MLightParameterInformation::kWorldDirection:
						lightParam->getParameter( pname, floatVals );
						direction = MFloatVector( floatVals[0], floatVals[1], floatVals[2] );
						foundDirectional = true;
						break;
					case MHWRender::MLightParameterInformation::kIntensity:
						lightParam->getParameter( pname, floatVals );
						lightIntensity = floatVals[0];
						break;
					case MHWRender::MLightParameterInformation::kColor:
						lightParam->getParameter( pname, floatVals );
						lightColor[0] = floatVals[0];
						lightColor[1] = floatVals[1];
						lightColor[2] = floatVals[2];
						break;

						// Pick up shadowing parameters
					case MHWRender::MLightParameterInformation::kGlobalShadowOn:
						lightParam->getParameter( pname, intVals );
						if (intVals.length())
							globalShadowsOn = (intVals[0] != 0) ? true : false;
						break;
					case MHWRender::MLightParameterInformation::kShadowOn:
						lightParam->getParameter( pname, intVals );
						if (intVals.length())
							localShadowsOn = (intVals[0] != 0) ? true : false;
						break;
					case MHWRender::MLightParameterInformation::kShadowViewProj:
						lightParam->getParameter( pname, shadowViewProj);
						break;
					case MHWRender::MLightParameterInformation::kShadowMap:
						lightParam->getParameter( pname, shadowResource );
						break;
					case MHWRender::MLightParameterInformation::kShadowDirty:
						if (intVals.length())
							shadowDirty = (intVals[0] != 0) ? true : false;
						break;
					case MHWRender::MLightParameterInformation::kShadowSamp:
						lightParam->getParameter( pname, samplerDesc );
						break;
					case MHWRender::MLightParameterInformation::kShadowColor:
						lightParam->getParameter( pname, floatVals );
						shadowColor[0] = floatVals[0];
						shadowColor[1] = floatVals[1];
						shadowColor[2] = floatVals[2];
						break;
					default:
						break;
					}
				} /* for params */
			}

			if (foundDirectional && globalShadowsOn && localShadowsOn && shadowResource.texture)
			{
				void *resourceHandle = shadowResource.texture->resourceHandle();
				if (resourceHandle)
				{
					static bool debugShadowBindings = false;
					status  = shaderInstance->setParameter("mayaShadowPCF1_shadowMap", shadowResource );
					if (status == MStatus::kSuccess && debugShadowBindings)
						fprintf(stderr, "Bound shadow map to shader param mayaShadowPCF1_shadowMap\n");
					status  = shaderInstance->setParameter("mayaShadowPCF1_shadowViewProj", shadowViewProj );
					if (status == MStatus::kSuccess && debugShadowBindings)
						fprintf(stderr, "Bound shadow map transform to shader param mayaShadowPCF1_shadowViewProj\n");
					status  = shaderInstance->setParameter("mayaShadowPCF1_shadowColor", &shadowColor[0] );
					if (status == MStatus::kSuccess && debugShadowBindings)
						fprintf(stderr, "Bound shadow map color to shader param mayaShadowPCF1_shadowColor\n");
				}

				MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer();
				if (renderer)
				{
					MHWRender::MTextureManager* textureManager = renderer->getTextureManager();
					if (textureManager)
					{
						textureManager->releaseTexture(shadowResource.texture);
					}
				}
				shadowResource.texture = NULL;
			}
		}
	}

	// Set up parameters which should be set regardless of light existence.
	status = shaderInstance->setParameter("mayaDirectionalLight_direction", &( direction[0] ));
	status = shaderInstance->setParameter("mayaDirectionalLight_intensity", lightIntensity );
	status = shaderInstance->setParameter("mayaDirectionalLight_color", &( lightColor[0] ));
	status = shaderInstance->setParameter("mayaShadowPCF1_mayaGlobalShadowOn", globalShadowsOn);
	status = shaderInstance->setParameter("mayaShadowPCF1_mayaShadowOn", localShadowsOn);
}
예제 #16
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;
}
예제 #17
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;
}
예제 #18
0
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;
}
예제 #19
0
파일: translatorMesh.cpp 프로젝트: JT-a/USD
PXR_NAMESPACE_OPEN_SCOPE



/* static */
bool 
PxrUsdMayaTranslatorMesh::Create(
        const UsdGeomMesh& mesh,
        MObject parentNode,
        const PxrUsdMayaPrimReaderArgs& args,
        PxrUsdMayaPrimReaderContext* context)
{
    if (!mesh) {
        return false;
    }

    const UsdPrim& prim = mesh.GetPrim();

    MStatus status;

    // Create node (transform)
    MObject mayaNodeTransformObj;
    if (!PxrUsdMayaTranslatorUtil::CreateTransformNode(prim,
                                                          parentNode,
                                                          args,
                                                          context,
                                                          &status,
                                                          &mayaNodeTransformObj)) {
        return false;
    }

    VtArray<GfVec3f> points;
    VtArray<GfVec3f> normals;
    VtArray<int>     faceVertexCounts;
    VtArray<int>     faceVertexIndices;
    
    UsdAttribute fvc = mesh.GetFaceVertexCountsAttr();
    if (fvc.ValueMightBeTimeVarying()){
        // at some point, it would be great, instead of failing, to create a usd/hydra proxy node
        // for the mesh, perhaps?  For now, better to give a more specific error
        MGlobal::displayError(
            TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexCounts). Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false;
    } else {
        // for any non-topo-varying mesh, sampling at zero will get us the right answer
        fvc.Get(&faceVertexCounts, 0);
    }

    UsdAttribute fvi = mesh.GetFaceVertexIndicesAttr();
    if (fvi.ValueMightBeTimeVarying()){
        // at some point, it would be great, instead of failing, to create a usd/hydra proxy node
        // for the mesh, perhaps?  For now, better to give a more specific error
        MGlobal::displayError(
            TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexIndices). Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false;
    } else {
        // for any non-topo-varying mesh, sampling at zero will get us the right answer
        fvi.Get(&faceVertexIndices, 0);
    }
        
    // Sanity Checks. If the vertex arrays are empty, skip this mesh
    if (faceVertexCounts.size() == 0 || faceVertexIndices.size() == 0) {
        MGlobal::displayError(
            TfStringPrintf("FaceVertex arrays are empty [Count:%zu Indices:%zu] on Mesh <%s>. Skipping...", 
                faceVertexCounts.size(), faceVertexIndices.size(), 
                prim.GetPath().GetText()).c_str());
        return false; // invalid mesh, so exit
    }

    // Gather points and normals
    // If args.GetReadAnimData() is TRUE,
    // pick the first avaiable sample or default
    UsdTimeCode pointsTimeSample=UsdTimeCode::EarliestTime();
    UsdTimeCode normalsTimeSample=UsdTimeCode::EarliestTime();
    std::vector<double> pointsTimeSamples;
    size_t pointsNumTimeSamples = 0;
    if (args.GetReadAnimData()) {
        PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetPointsAttr(), args,
                &pointsTimeSamples);
        pointsNumTimeSamples = pointsTimeSamples.size();
        if (pointsNumTimeSamples>0) {
            pointsTimeSample = pointsTimeSamples[0];
        }
    	std::vector<double> normalsTimeSamples;
        PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetNormalsAttr(), args,
                &normalsTimeSamples);
        if (normalsTimeSamples.size()) {
            normalsTimeSample = normalsTimeSamples[0];
        }
    }
    mesh.GetPointsAttr().Get(&points, pointsTimeSample);
    mesh.GetNormalsAttr().Get(&normals, normalsTimeSample);
    
    if (points.size() == 0) {
        MGlobal::displayError(
            TfStringPrintf("Points arrays is empty on Mesh <%s>. Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false; // invalid mesh, so exit
    }


    // == Convert data
    size_t mayaNumVertices = points.size();
    MPointArray mayaPoints(mayaNumVertices);
    for (size_t i=0; i < mayaNumVertices; i++) {
        mayaPoints.set( i, points[i][0], points[i][1], points[i][2] );
    }

    MIntArray polygonCounts( faceVertexCounts.cdata(),  faceVertexCounts.size() );
    MIntArray polygonConnects( faceVertexIndices.cdata(), faceVertexIndices.size() );

    // == Create Mesh Shape Node
    MFnMesh meshFn;
    MObject meshObj = meshFn.create(mayaPoints.length(), 
                           polygonCounts.length(), 
                           mayaPoints, 
                           polygonCounts, 
                           polygonConnects,
                           mayaNodeTransformObj,
                           &status
                           );
                           
    if (status != MS::kSuccess) {
        return false;
    }

    // Since we are "decollapsing", we will create a xform and a shape node for each USD prim
    std::string usdPrimName(prim.GetName().GetText());
    std::string shapeName(usdPrimName); shapeName += "Shape";
    // Set mesh name and register
    meshFn.setName(MString(shapeName.c_str()), false, &status);
    if (context) {
        std::string usdPrimPath(prim.GetPath().GetText());
        std::string shapePath(usdPrimPath);
        shapePath += "/";
        shapePath += shapeName;
        context->RegisterNewMayaNode( shapePath, meshObj ); // used for undo/redo
    }

    // If a material is bound, create (or reuse if already present) and assign it
    // If no binding is present, assign the mesh to the default shader    
    const TfToken& shadingMode = args.GetShadingMode();
    PxrUsdMayaTranslatorMaterial::AssignMaterial(shadingMode, mesh, meshObj,
            context);
    
    // Mesh is a shape, so read Gprim properties
    PxrUsdMayaTranslatorGprim::Read(mesh, meshObj, context);

    // Set normals if supplied
    MIntArray normalsFaceIds;
    if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) {

        for (size_t i=0; i < polygonCounts.length(); i++) {
            for (int j=0; j < polygonCounts[i]; j++) {
                normalsFaceIds.append(i);
            }
        }
        if (normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) {
            MVectorArray mayaNormals(normals.size());
            for (size_t i=0; i < normals.size(); i++) {
                mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i);
            }
            if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) {
            }
        }
     }

    // Determine if PolyMesh or SubdivMesh
    TfToken subdScheme = PxrUsdMayaMeshUtil::setSubdivScheme(mesh, meshFn, args.GetDefaultMeshScheme());

    // If we are dealing with polys, check if there are normals
    // If we are dealing with SubdivMesh, read additional attributes and SubdivMesh properties
    if (subdScheme == UsdGeomTokens->none) {
        if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) {
            PxrUsdMayaMeshUtil::setEmitNormals(mesh, meshFn, UsdGeomTokens->none);
        }
    } else {
        PxrUsdMayaMeshUtil::setSubdivInterpBoundary(mesh, meshFn, UsdGeomTokens->edgeAndCorner);
        PxrUsdMayaMeshUtil::setSubdivFVLinearInterpolation(mesh, meshFn);
        _AssignSubDivTagsToMesh(mesh, meshObj, meshFn);
    }
 
    // Set Holes
    VtArray<int> holeIndices;
    mesh.GetHoleIndicesAttr().Get(&holeIndices);   // not animatable
    if ( holeIndices.size() != 0 ) {
        MUintArray mayaHoleIndices;
        mayaHoleIndices.setLength( holeIndices.size() );
        for (size_t i=0; i < holeIndices.size(); i++) {
            mayaHoleIndices[i] = holeIndices[i];
        }
        if (meshFn.setInvisibleFaces(mayaHoleIndices) == MS::kFailure) {
            MGlobal::displayError(TfStringPrintf("Unable to set Invisible Faces on <%s>", 
                            meshFn.fullPathName().asChar()).c_str());
        }
    }

    // GETTING PRIMVARS
    std::vector<UsdGeomPrimvar> primvars = mesh.GetPrimvars();
    TF_FOR_ALL(iter, primvars) {
        const UsdGeomPrimvar& primvar = *iter;
        const TfToken& name = primvar.GetBaseName();
        const SdfValueTypeName& typeName = primvar.GetTypeName();

        // If the primvar is called either displayColor or displayOpacity check
        // if it was really authored from the user.  It may not have been
        // authored by the user, for example if it was generated by shader
        // values and not an authored colorset/entity.
        // If it was not really authored, we skip the primvar.
        if (name == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName || 
                name == PxrUsdMayaMeshColorSetTokens->DisplayOpacityColorSetName) {
            if (!PxrUsdMayaRoundTripUtil::IsAttributeUserAuthored(primvar)) {
                continue;
            }
        }

        // XXX: Maya stores UVs in MFloatArrays and color set data in MColors
        // which store floats, so we currently only import primvars holding
        // float-typed arrays. Should we still consider other precisions
        // (double, half, ...) and/or numeric types (int)?
        if (typeName == SdfValueTypeNames->Float2Array) {
            // We assume that Float2Array primvars are UV sets.
            if (!_AssignUVSetPrimvarToMesh(primvar, meshFn)) {
                MGlobal::displayWarning(
                    TfStringPrintf("Unable to retrieve and assign data for UV set <%s> on mesh <%s>", 
                                   name.GetText(),
                                   mesh.GetPrim().GetPath().GetText()).c_str());
            }
        } else if (typeName == SdfValueTypeNames->FloatArray   || 
                   typeName == SdfValueTypeNames->Float3Array  || 
                   typeName == SdfValueTypeNames->Color3fArray ||
                   typeName == SdfValueTypeNames->Float4Array  || 
                   typeName == SdfValueTypeNames->Color4fArray) {
            if (!_AssignColorSetPrimvarToMesh(mesh, primvar, meshFn)) {
                MGlobal::displayWarning(
                    TfStringPrintf("Unable to retrieve and assign data for color set <%s> on mesh <%s>",
                                   name.GetText(),
                                   mesh.GetPrim().GetPath().GetText()).c_str());
            }
        }
    }

    // We only vizualize the colorset by default if it is "displayColor".  
    MStringArray colorSetNames;
    if (meshFn.getColorSetNames(colorSetNames)==MS::kSuccess) {
        for (unsigned int i=0; i < colorSetNames.length(); i++) {
            const MString colorSetName = colorSetNames[i];
            if (std::string(colorSetName.asChar()) 
                    == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName.GetString()) {
                MFnMesh::MColorRepresentation csRep=
                    meshFn.getColorRepresentation(colorSetName);
                if (csRep==MFnMesh::kRGB || csRep==MFnMesh::kRGBA) {

                    // both of these are needed to show the colorset.
                    MPlug plg=meshFn.findPlug("displayColors");
                    if ( !plg.isNull() ) {
                        plg.setBool(true);
                    }
                    meshFn.setCurrentColorSetName(colorSetName);
                }
                break;
            }
        }
    }
    
    // == Animate points ==
    //   Use blendShapeDeformer so that all the points for a frame are contained in a single node
    //
    if (pointsNumTimeSamples > 0) {
        MPointArray mayaPoints(mayaNumVertices);
        MObject meshAnimObj;

        MFnBlendShapeDeformer blendFn;
        MObject blendObj = blendFn.create(meshObj);
        if (context) {
            context->RegisterNewMayaNode( blendFn.name().asChar(), blendObj ); // used for undo/redo
        }

        for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
             mesh.GetPointsAttr().Get(&points, pointsTimeSamples[ti]);

            for (unsigned int i=0; i < mayaNumVertices; i++) {
                mayaPoints.set( i, points[i][0], points[i][1], points[i][2] );
            }

            // == Create Mesh Shape Node
            MFnMesh meshFn;
            if ( meshAnimObj.isNull() ) {
                meshAnimObj = meshFn.create(mayaPoints.length(), 
                                       polygonCounts.length(), 
                                       mayaPoints, 
                                       polygonCounts, 
                                       polygonConnects,
                                       mayaNodeTransformObj,
                                       &status
                                       );
                if (status != MS::kSuccess) {
                    continue;
                }
            }
            else {
                // Reuse the already created mesh by copying it and then setting the points
                meshAnimObj = meshFn.copy(meshAnimObj, mayaNodeTransformObj, &status);
                meshFn.setPoints(mayaPoints);
            }

            // Set normals if supplied
            //
            // NOTE: This normal information is not propagated through the blendShapes, only the controlPoints.
            //
             mesh.GetNormalsAttr().Get(&normals, pointsTimeSamples[ti]);
             if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices()) &&
                normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) {

                MVectorArray mayaNormals(normals.size());
                for (size_t i=0; i < normals.size(); i++) {
                    mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i);
                }
                if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) {
                }
             }

            // Add as target and set as an intermediate object
            blendFn.addTarget(meshObj, ti, meshAnimObj, 1.0);
            meshFn.setIntermediateObject(true);
            if (context) {
                context->RegisterNewMayaNode( meshFn.fullPathName().asChar(), meshAnimObj ); // used for undo/redo
            }
        }

        // Animate the weights so that mesh0 has a weight of 1 at frame 0, etc.
        MFnAnimCurve animFn;

        // Construct the time array to be used for all the keys
        MTimeArray timeArray;
        timeArray.setLength(pointsNumTimeSamples);
        for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
            timeArray.set( MTime(pointsTimeSamples[ti]), ti);
        }

        // Key/Animate the weights
        MPlug plgAry = blendFn.findPlug( "weight" );
        if ( !plgAry.isNull() && plgAry.isArray() ) {
            for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
                MPlug plg = plgAry.elementByLogicalIndex(ti, &status);
                MDoubleArray valueArray(pointsNumTimeSamples, 0.0);
                valueArray[ti] = 1.0; // Set the time value where this mesh's weight should be 1.0
                MObject animObj = animFn.create(plg, NULL, &status);
                animFn.addKeys(&timeArray, &valueArray);
                if (context) {
                    context->RegisterNewMayaNode(animFn.name().asChar(), animObj ); // used for undo/redo
                }
            }
        }
    }

    return true;
}
예제 #20
0
//! Caller is expected to delete the returned value
static OpenSubdiv::Far::TopologyRefiner *
gatherTopology( MFnMesh & inMeshFn,
                MItMeshPolygon & inMeshItPolygon,
                OpenSubdiv::Sdc::SchemeType type,
                OpenSubdiv::Sdc::Options options,
                bool * hasUVs, bool * hasColors,
                std::vector<MFloatArray> & uvSet_uCoords,
                std::vector<MFloatArray> & uvSet_vCoords,
                std::vector<MColorArray> & colorSet_colors,
                float * maxCreaseSharpness=0 ) {

    MStatus returnStatus;

    // Gather FVarData
    MStringArray uvSetNames;
    MStringArray colorSetNames;
    std::vector<int> colorSetChannels;
    std::vector<MFnMesh::MColorRepresentation> colorSetReps;
    int totalColorSetChannels = 0;
    returnStatus = getMayaFvarFieldParams(inMeshFn, uvSetNames, colorSetNames, 
                        colorSetChannels, colorSetReps, totalColorSetChannels);
    MWARNERR(returnStatus, "Failed to retrieve Maya face-varying parameters");

    // Storage for UVs and ColorSets for face-vertex
    MIntArray fvArray; // face vertex array
    uvSet_uCoords.clear();  uvSet_uCoords.resize(uvSetNames.length());
    uvSet_vCoords.clear();  uvSet_vCoords.resize(uvSetNames.length());
    colorSet_colors.clear();colorSet_colors.resize(colorSetNames.length());

    // Put the data in the format needed for OSD
    Descriptor desc;
    
    int numFaceVertices = inMeshFn.numFaceVertices();

    desc.numVertices = inMeshFn.numVertices();
    desc.numFaces = inMeshItPolygon.count();

    int * vertsPerFace = new int[desc.numFaces],
        * vertIndices = new int[numFaceVertices];

    desc.numVertsPerFace = vertsPerFace;
    desc.vertIndicesPerFace = vertIndices;

    // Create Topology
    for (inMeshItPolygon.reset(); !inMeshItPolygon.isDone(); inMeshItPolygon.next()) {

        inMeshItPolygon.getVertices(fvArray);
        int nverts = fvArray.length();

        vertsPerFace[inMeshItPolygon.index()] = nverts;

        for (int i=0; i<nverts; ++i) {
            *vertIndices++ = fvArray[i];
        }
    }

    // Add Face-Varying data to the descriptor
    Descriptor::FVarChannel * channels = NULL;
    *hasUVs = uvSet_uCoords.size() > 0 && uvSet_vCoords.size() > 0;
    *hasColors = colorSet_colors.size() > 0;

    // Note : Only supports 1 channel of UVs and 1 channel of color
    if (*hasUVs || *hasColors) {

        // Create 2 face-varying channel descriptor that will hold UVs and color
        desc.numFVarChannels = 2;
        channels = new Descriptor::FVarChannel[desc.numFVarChannels];
        desc.fvarChannels = channels;

        int * uvIndices = new int[numFaceVertices];
        channels[CHANNELUV].valueIndices = uvIndices;
        channels[CHANNELUV].numValues = 0;

        int * colorIndices = new int[numFaceVertices];
        channels[CHANNELCOLOR].valueIndices = colorIndices;
        channels[CHANNELCOLOR].numValues = 0;

        // Obtain UV information
        if (*hasUVs) {
            inMeshFn.getUVs(uvSet_uCoords[0], uvSet_vCoords[0], &uvSetNames[0]);
            assert( uvSet_uCoords[0].length() == uvSet_vCoords[0].length() );

            int uvId = 0, nUVs = 0;
            for (int faceIndex = 0; faceIndex < inMeshFn.numPolygons(); ++faceIndex)
            {
                int numVertices = inMeshFn.polygonVertexCount(faceIndex);
                for (int v = 0; v < numVertices; v++)
                {
                    inMeshFn.getPolygonUVid(faceIndex, v, uvId, &uvSetNames[0]);
                    uvIndices[nUVs++] = uvId;
                }
            }

            channels[CHANNELUV].numValues = uvSet_uCoords[0].length();
        }

        // Obtain color information
        if (*hasColors) {  
            inMeshFn.getColors(colorSet_colors[0], &colorSetNames[0]);

            int colorId = 0, nColors = 0;
            bool addDefaultColor = true;
            for (int faceIndex = 0; faceIndex < inMeshFn.numPolygons(); ++faceIndex)
            {
                int numVertices = inMeshFn.polygonVertexCount(faceIndex);
                for ( int v = 0 ; v < numVertices; v++ )
                {
                    inMeshFn.getColorIndex(faceIndex, v, colorId, &colorSetNames[0]);
                    if (colorId == -1)
                    {
                        if (addDefaultColor)
                        {
                            addDefaultColor = false;
                            colorSet_colors[0].append(MColor(1.0, 1.0, 1.0, 1.0));
                        }
                        colorId = colorSet_colors[0].length() - 1;
                    }
                    colorIndices[nColors ++] = colorId;
                }
            }
            
            channels[CHANNELCOLOR].numValues = colorSet_colors[0].length();
        }
    }

    // Apply Creases
    float maxEdgeCrease = getCreaseEdges( inMeshFn, desc );
    float maxVertexCrease = getCreaseVertices( inMeshFn, desc );

    OpenSubdiv::Far::TopologyRefiner * refiner =
        OpenSubdiv::Far::TopologyRefinerFactory<Descriptor>::Create(desc,
            OpenSubdiv::Far::TopologyRefinerFactory<Descriptor>::Options(type, options));

    delete [] desc.numVertsPerFace;
    delete [] desc.vertIndicesPerFace;
    delete [] desc.creaseVertexIndexPairs;
    delete [] desc.creaseWeights;
    delete [] desc.cornerVertexIndices;
    delete [] desc.cornerWeights;

    if (*hasUVs || *hasColors) {
        for(int i = 0 ; i < desc.numFVarChannels ; i ++) {
            delete [] channels[i].valueIndices;
        }
        delete [] channels;
    }

    if (maxCreaseSharpness) {
        *maxCreaseSharpness = std::max(maxEdgeCrease, maxVertexCrease);
    }

    return refiner;
}
void OutputTextures(MSelectionList selected){
	
	
MString temp;
MString affich;
	

	
int MatExists=0;
	for(int i=0;i<selected.length();i++){
	

	MDagPath path;
	MObject obj;

	selected.getDagPath(i,path);

	
	obj=path.child(0);

	

	MFnMesh fn(path);
	obj=fn.parent(0);
	path.getAPathTo(fn.parent(0));
	MFnMesh fna(path);
	
	
	unsigned int instancenumbers;
	MObjectArray shaders;
	MIntArray indices;

	fna.getConnectedShaders(instancenumbers,shaders,indices);

	

switch(shaders.length()) {

		// if no shader applied to the mesh instance
		case 0:
			{
				//***************Affich("pas de matériaux");
			}
			break;

		// if all faces use the same material
	
		// if more than one material is used, write out the face indices the materials
		// are applied to.
		default:
			{
				//************************Affich("trouvé plusieurs matériaux");

				
				//write_int(shaders.length());

				// now write each material and the face indices that use them
				
				for(int j=0;j < shaders.length();++j)
				{						
					for(int matest=0;matest<Matid.length();matest++){
						//**************************Affich(Matid[matest].asChar());
						//*****************************Affich(GetShaderName( shaders[j] ).asChar());
						if(Matid[matest]== GetShaderName( shaders[j] )){
						MatExists = 1;
						
						}//fin if matid
						
						}// fin for matest
					if(MatExists != 1){
					//*****************************Affich("matériau absent de la liste, enregistrement");
					Matid.append(GetShaderName( shaders[j] ).asChar());
					nb_Tex_by_Brush.append(0);
						writeTexture(shaders[j],"color");

					//Affich(temp);
					}else {
					//*************************************	Affich("matériau existe dans la liste");
					}// fin if matexists
					
					MatExists = 0;
						

				}//fin for j shaders
			}// fin case default
			break;
		}//fin switches

	}//fin for selected
		

	Matid.clear();
}// fin output textures
bool Outputtexture(MFnDependencyNode& fn,const char* name)
{
  	MPlug p;

MString r = name;
r += "R";
MString g = name;
g += "G";
MString b = name;
b += "B";
MString a = name;
a += "A";

// get the color value
MColor color;

// get a plug to the attribute
p = fn.findPlug(r);
p.getValue(color.r);
p = fn.findPlug(g.asChar());
p.getValue(color.g);
p = fn.findPlug(b.asChar());
p.getValue(color.b);
p = fn.findPlug(a.asChar());
p.getValue(color.a);
p = fn.findPlug(name);

// will hold the txture node name
MString texname;

// get plugs connected to colour attribute
MPlugArray plugs;
p.connectedTo(plugs,true,false);

// see if any file textures are present
	for(int i=0;i!=plugs.length();++i)
		{
  			// if file texture found
			if(plugs[i].node().apiType() == MFn::kFileTexture)
				{
  					// bind a function set to it ....
					MFnDependencyNode fnDep(plugs[i].node());

					// to get the node name
					texname = fnDep.name();
					

					int TexExists=0;
						for(int i=0;i<Texid.length();i++)
							{
								if(texname==Texid[i]) TexExists=1;
							}
							if(TexExists==0){
							// écrire la texture car absente
								Texid.append(texname);
								Affich(texname);
							
								
								//write_int(Matid.length());//id Brush
								//write_int(1);//textures per brush
								//::output << GetShaderName( shaders[j] ).asChar();
								
								
								
								// get the attribute for the full texture path
MPlug ftn = fnDep.findPlug("ftn");

// get the filename from the attribute
MString filename;
ftn.getValue(filename);

// write the file name
								


nb_Tex_by_Brush[Matid.length()-1]++;// une nouvelle texture dans la brush courante
Texids_by_brush.append(Texid.length()-1);
								::output << filename;
								
								
								
								::output << char(0x00);
								//write flags, blend default 1, 2
								write_int(1);
								write_int(2);
								// write position default O, O
								write_float(0);
								write_float(0);
								//write scale default 1, 1
								write_float(1);
								write_float(1);
								//rotation in radian default= 0
								write_float(0);

								//OutputColors(shaders[j],"color");

								//EndChunck();
							}else {
		nb_Tex_by_Brush[Matid.length()-1]=0;
		//Texids_by_brush.append(0);
				Texids_by_brush.append(0);
			}
					// stop looping
					//TexExists=0;

				}

			
		}



return true;

} 
예제 #23
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 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 );
}
예제 #25
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]);
			}
		}
	}
}
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;
}
예제 #27
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;
}
예제 #28
0
MStatus AlembicExportCommand::doIt(const MArgList &args)
{
  ESS_PROFILE_SCOPE("AlembicExportCommand::doIt");

  MStatus status = MS::kFailure;

  MTime currentAnimStartTime = MAnimControl::animationStartTime(),
        currentAnimEndTime = MAnimControl::animationEndTime(),
        oldCurTime = MAnimControl::currentTime(),
        curMinTime = MAnimControl::minTime(),
        curMaxTime = MAnimControl::maxTime();
  MArgParser argData(syntax(), args, &status);

  if (argData.isFlagSet("help")) {
    // TODO: implement help for this command
    // MGlobal::displayInfo(util::getHelpText());
    return MS::kSuccess;
  }

  unsigned int jobCount = argData.numberOfFlagUses("jobArg");
  MStringArray jobStrings;
  if (jobCount == 0) {
    // TODO: display dialog
    MGlobal::displayError("[ExocortexAlembic] No jobs specified.");
    MPxCommand::setResult(
        "Error caught in AlembicExportCommand::doIt: no job specified");
    return status;
  }
  else {
    // get all of the jobstrings
    for (unsigned int i = 0; i < jobCount; i++) {
      MArgList jobArgList;
      argData.getFlagArgumentList("jobArg", i, jobArgList);
      jobStrings.append(jobArgList.asString(0));
    }
  }

  // create a vector to store the jobs
  std::vector<AlembicWriteJob *> jobPtrs;
  double minFrame = 1000000.0;
  double maxFrame = -1000000.0;
  double maxSteps = 1;
  double maxSubsteps = 1;

  // init the curve accumulators
  AlembicCurveAccumulator::Initialize();

  try {
    // for each job, check the arguments
    bool failure = false;
    for (unsigned int i = 0; i < jobStrings.length(); ++i) {
      double frameIn = 1.0;
      double frameOut = 1.0;
      double frameSteps = 1.0;
      double frameSubSteps = 1.0;
      MString filename;
      bool purepointcache = false;
      bool normals = true;
      bool uvs = true;
      bool facesets = true;
      bool bindpose = true;
      bool dynamictopology = false;
      bool globalspace = false;
      bool withouthierarchy = false;
      bool transformcache = false;
      bool useInitShadGrp = false;
      bool useOgawa = false;  // Later, will need to be changed!

      MStringArray objectStrings;
      std::vector<std::string> prefixFilters;
      std::set<std::string> attributes;
      std::vector<std::string> userPrefixFilters;
      std::set<std::string> userAttributes;
      MObjectArray objects;
      std::string search_str, replace_str;

      // process all tokens of the job
      MStringArray tokens;
      jobStrings[i].split(';', tokens);
      for (unsigned int j = 0; j < tokens.length(); j++) {
        MStringArray valuePair;
        tokens[j].split('=', valuePair);
        if (valuePair.length() != 2) {
          MGlobal::displayWarning(
              "[ExocortexAlembic] Skipping invalid token: " + tokens[j]);
          continue;
        }

        const MString &lowerValue = valuePair[0].toLowerCase();
        if (lowerValue == "in") {
          frameIn = valuePair[1].asDouble();
        }
        else if (lowerValue == "out") {
          frameOut = valuePair[1].asDouble();
        }
        else if (lowerValue == "step") {
          frameSteps = valuePair[1].asDouble();
        }
        else if (lowerValue == "substep") {
          frameSubSteps = valuePair[1].asDouble();
        }
        else if (lowerValue == "normals") {
          normals = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "uvs") {
          uvs = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "facesets") {
          facesets = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "bindpose") {
          bindpose = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "purepointcache") {
          purepointcache = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "dynamictopology") {
          dynamictopology = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "globalspace") {
          globalspace = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "withouthierarchy") {
          withouthierarchy = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "transformcache") {
          transformcache = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "filename") {
          filename = valuePair[1];
        }
        else if (lowerValue == "objects") {
          // try to find each object
          valuePair[1].split(',', objectStrings);
        }
        else if (lowerValue == "useinitshadgrp") {
          useInitShadGrp = valuePair[1].asInt() != 0;
        }

        // search/replace
        else if (lowerValue == "search") {
          search_str = valuePair[1].asChar();
        }
        else if (lowerValue == "replace") {
          replace_str = valuePair[1].asChar();
        }
        else if (lowerValue == "ogawa") {
          useOgawa = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "attrprefixes") {
          splitListArg(valuePair[1], prefixFilters);
        }
        else if (lowerValue == "attrs") {
          splitListArg(valuePair[1], attributes);
        }
        else if (lowerValue == "userattrprefixes") {
          splitListArg(valuePair[1], userPrefixFilters);
        }
        else if (lowerValue == "userattrs") {
          splitListArg(valuePair[1], userAttributes);
        }
        else {
          MGlobal::displayWarning(
              "[ExocortexAlembic] Skipping invalid token: " + tokens[j]);
          continue;
        }
      }

      // now check the object strings
      for (unsigned int k = 0; k < objectStrings.length(); k++) {
        MSelectionList sl;
        MString objectString = objectStrings[k];
        sl.add(objectString);
        MDagPath dag;
        for (unsigned int l = 0; l < sl.length(); l++) {
          sl.getDagPath(l, dag);
          MObject objRef = dag.node();
          if (objRef.isNull()) {
            MGlobal::displayWarning("[ExocortexAlembic] Skipping object '" +
                                    objectStrings[k] + "', not found.");
            break;
          }

          // get all parents
          MObjectArray parents;

          // check if this is a camera
          bool isCamera = false;
          for (unsigned int m = 0; m < dag.childCount(); ++m) {
            MFnDagNode child(dag.child(m));
            MFn::Type ctype = child.object().apiType();
            if (ctype == MFn::kCamera) {
              isCamera = true;
              break;
            }
          }

          if (dag.node().apiType() == MFn::kTransform && !isCamera &&
              !globalspace && !withouthierarchy) {
            MDagPath ppath = dag;
            while (!ppath.node().isNull() && ppath.length() > 0 &&
                   ppath.isValid()) {
              parents.append(ppath.node());
              if (ppath.pop() != MStatus::kSuccess) {
                break;
              }
            }
          }
          else {
            parents.append(dag.node());
          }

          // push all parents in
          while (parents.length() > 0) {
            bool found = false;
            for (unsigned int m = 0; m < objects.length(); m++) {
              if (objects[m] == parents[parents.length() - 1]) {
                found = true;
                break;
              }
            }
            if (!found) {
              objects.append(parents[parents.length() - 1]);
            }
            parents.remove(parents.length() - 1);
          }

          // check all of the shapes below
          if (!transformcache) {
            sl.getDagPath(l, dag);
            for (unsigned int m = 0; m < dag.childCount(); m++) {
              MFnDagNode child(dag.child(m));
              if (child.isIntermediateObject()) {
                continue;
              }
              objects.append(child.object());
            }
          }
        }
      }

      // check if we have incompatible subframes
      if (maxSubsteps > 1.0 && frameSubSteps > 1.0) {
        const double part = (frameSubSteps > maxSubsteps)
                                ? (frameSubSteps / maxSubsteps)
                                : (maxSubsteps / frameSubSteps);
        if (abs(part - floor(part)) > 0.001) {
          MString frameSubStepsStr, maxSubstepsStr;
          frameSubStepsStr.set(frameSubSteps);
          maxSubstepsStr.set(maxSubsteps);
          MGlobal::displayError(
              "[ExocortexAlembic] You cannot combine substeps " +
              frameSubStepsStr + " and " + maxSubstepsStr +
              " in one export. Aborting.");
          return MStatus::kInvalidParameter;
        }
      }

      // remember the min and max values for the frames
      if (frameIn < minFrame) {
        minFrame = frameIn;
      }
      if (frameOut > maxFrame) {
        maxFrame = frameOut;
      }
      if (frameSteps > maxSteps) {
        maxSteps = frameSteps;
      }
      if (frameSteps > 1.0) {
        frameSubSteps = 1.0;
      }
      if (frameSubSteps > maxSubsteps) {
        maxSubsteps = frameSubSteps;
      }

      // check if we have a filename
      if (filename.length() == 0) {
        MGlobal::displayError("[ExocortexAlembic] No filename specified.");
        for (size_t k = 0; k < jobPtrs.size(); k++) {
          delete (jobPtrs[k]);
        }
        MPxCommand::setResult(
            "Error caught in AlembicExportCommand::doIt: no filename "
            "specified");
        return MStatus::kFailure;
      }

      // construct the frames
      MDoubleArray frames;
      {
        const double frameIncr = frameSteps / frameSubSteps;
        for (double frame = frameIn; frame <= frameOut; frame += frameIncr) {
          frames.append(frame);
        }
      }

      AlembicWriteJob *job =
          new AlembicWriteJob(filename, objects, frames, useOgawa,
              prefixFilters, attributes, userPrefixFilters, userAttributes);
      job->SetOption("exportNormals", normals ? "1" : "0");
      job->SetOption("exportUVs", uvs ? "1" : "0");
      job->SetOption("exportFaceSets", facesets ? "1" : "0");
      job->SetOption("exportInitShadGrp", useInitShadGrp ? "1" : "0");
      job->SetOption("exportBindPose", bindpose ? "1" : "0");
      job->SetOption("exportPurePointCache", purepointcache ? "1" : "0");
      job->SetOption("exportDynamicTopology", dynamictopology ? "1" : "0");
      job->SetOption("indexedNormals", "1");
      job->SetOption("indexedUVs", "1");
      job->SetOption("exportInGlobalSpace", globalspace ? "1" : "0");
      job->SetOption("flattenHierarchy", withouthierarchy ? "1" : "0");
      job->SetOption("transformCache", transformcache ? "1" : "0");

      // check if the search/replace strings are valid!
      if (search_str.length() ? !replace_str.length()
                              : replace_str.length())  // either search or
                                                       // replace string is
                                                       // missing or empty!
      {
        ESS_LOG_WARNING(
            "Missing search or replace parameter. No strings will be "
            "replaced.");
        job->replacer = SearchReplace::createReplacer();
      }
      else {
        job->replacer = SearchReplace::createReplacer(search_str, replace_str);
      }

      // check if the job is satifsied
      if (job->PreProcess() != MStatus::kSuccess) {
        MGlobal::displayError("[ExocortexAlembic] Job skipped. Not satisfied.");
        delete (job);
        failure = true;
        break;
      }

      // push the job to our registry
      MGlobal::displayInfo("[ExocortexAlembic] Using WriteJob:" +
                           jobStrings[i]);
      jobPtrs.push_back(job);
    }

    if (failure) {
      for (size_t k = 0; k < jobPtrs.size(); k++) {
        delete (jobPtrs[k]);
      }
      return MS::kFailure;
    }

    // compute the job count
    unsigned int jobFrameCount = 0;
    for (size_t i = 0; i < jobPtrs.size(); i++)
      jobFrameCount += (unsigned int)jobPtrs[i]->GetNbObjects() *
                       (unsigned int)jobPtrs[i]->GetFrames().size();

    // now, let's run through all frames, and process the jobs
    const double frameRate = MTime(1.0, MTime::kSeconds).as(MTime::uiUnit());
    const double incrSteps = maxSteps / maxSubsteps;
    double nextFrame = minFrame + incrSteps;

    for (double frame = minFrame; frame <= maxFrame;
         frame += incrSteps, nextFrame += incrSteps) {
      MAnimControl::setCurrentTime(MTime(frame / frameRate, MTime::kSeconds));
      MAnimControl::setAnimationEndTime(
          MTime(nextFrame / frameRate, MTime::kSeconds));
      MAnimControl::playForward();  // this way, it forces Maya to play exactly
      // one frame! and particles are updated!

      AlembicCurveAccumulator::StartRecordingFrame();
      for (size_t i = 0; i < jobPtrs.size(); i++) {
        MStatus status = jobPtrs[i]->Process(frame);
        if (status != MStatus::kSuccess) {
          MGlobal::displayError("[ExocortexAlembic] Job aborted :" +
                                jobPtrs[i]->GetFileName());
          for (size_t k = 0; k < jobPtrs.size(); k++) {
            delete (jobPtrs[k]);
          }
          restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                         curMinTime, curMaxTime);
          return status;
        }
      }
      AlembicCurveAccumulator::StopRecordingFrame();
    }
  }
  catch (...) {
    MGlobal::displayError(
        "[ExocortexAlembic] Jobs aborted, force closing all archives!");
    for (std::vector<AlembicWriteJob *>::iterator beg = jobPtrs.begin();
         beg != jobPtrs.end(); ++beg) {
      (*beg)->forceCloseArchive();
    }
    restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                   curMinTime, curMaxTime);
    MPxCommand::setResult("Error caught in AlembicExportCommand::doIt");
    status = MS::kFailure;
  }
  MAnimControl::stop();
  AlembicCurveAccumulator::Destroy();

  // restore the animation start/end time and the current time!
  restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                 curMinTime, curMaxTime);

  // delete all jobs
  for (size_t k = 0; k < jobPtrs.size(); k++) {
    delete (jobPtrs[k]);
  }

  // remove all known archives
  deleteAllArchives();
  return status;
}
예제 #29
0
IECore::DataPtr convert( const MCommandResult &result )
{
	MStatus s;
	switch (result.resultType())
	{
		case MCommandResult::kInvalid:
		{
			// No result
			return 0;
		}
		case MCommandResult::kInt:
		{
			int i;
			s = result.getResult(i);
			assert(s);

			IECore::IntDataPtr data = new IECore::IntData();
			data->writable() = i;

			return data;
		}
		case MCommandResult::kIntArray:
		{
			MIntArray v;
			s = result.getResult(v);
			assert(s);
			unsigned sz = v.length();
			IECore::IntVectorDataPtr data = new IECore::IntVectorData();
			data->writable().resize(sz);
			for (unsigned i = 0; i < sz; i++)
			{
				(data->writable())[i] = v[i];
			}

			return data;
		}
		case MCommandResult::kDouble:
		{
			double d;
			s = result.getResult(d);
			assert(s);

			IECore::FloatDataPtr data = new IECore::FloatData();
			data->writable() = static_cast<float>(d);

			return data;
		}
		case MCommandResult::kDoubleArray:
		{
			MDoubleArray v;
			s = result.getResult(v);
			assert(s);
			unsigned sz = v.length();
			IECore::DoubleVectorDataPtr data = new IECore::DoubleVectorData();
			data->writable().resize(sz);
			for (unsigned i = 0; i < sz; i++)
			{
				data->writable()[i] = v[i];
			}

			return data;
		}
		case MCommandResult::kString:
		{
			MString str;
			s = result.getResult(str);
			assert(s);

			IECore::StringDataPtr data = new IECore::StringData();
			data->writable() = std::string(str.asChar());

			return data;
		}
		case MCommandResult::kStringArray:
		{
			MStringArray v;
			s = result.getResult(v);
			assert(s);
			unsigned sz = v.length();
			IECore::StringVectorDataPtr data = new IECore::StringVectorData();
			data->writable().resize(sz);
			for (unsigned i = 0; i < sz; i++)
			{
				data->writable()[i] = std::string(v[i].asChar());
			}

			return data;
		}
		case MCommandResult::kVector:
		{
			MVector v;
			s = result.getResult(v);
			assert(s);

			IECore::V3fDataPtr data = new IECore::V3fData();
			data->writable() = Imath::V3f(v.x, v.y, v.z);

			return data;
		}
		case MCommandResult::kVectorArray:
		{
			MVectorArray v;
			s = result.getResult(v);
			assert(s);
			unsigned sz = v.length();
			IECore::V3fVectorDataPtr data = new IECore::V3fVectorData();
			data->writable().resize(sz);
			for (unsigned i = 0; i < sz; i++)
			{
				data->writable()[i] = Imath::V3f(v[i].x, v[i].y, v[i].z);
			}

			return data;
		}
		case MCommandResult::kMatrix:
		{
			MDoubleArray v;
			int numRows, numColumns;

			s = result.getResult(v, numRows, numColumns);
			assert(s);

			if (numRows > 4 || numColumns > 4)
			{
				throw IECoreMaya::StatusException( MS::kFailure );
			}

			IECore::M44fDataPtr data = new IECore::M44fData();

			for (int i = 0; i < numColumns; i++)
			{
				for (int j = 0; j < numRows; j++)
				{
					(data->writable())[i][j] = v[i*numRows+j];
				}
			}

			return data;
		}
		case MCommandResult::kMatrixArray:
		{
			return 0;
		}
		default:

			assert( false );
			return 0;
	}
}
예제 #30
0
size_t GetFileList(const std::string &filePattern, std::vector<std::string> &files, int *start=0, int *end=0)
{
  size_t p0 = filePattern.find_last_of("\\/");
  
  std::string dirname = (p0 == std::string::npos ? "." : filePattern.substr(0, p0));
  std::string basename = (p0 == std::string::npos ? filePattern : filePattern.substr(p0 + 1));
  
  files.clear();
  
  p0 = basename.find('%');
  
  size_t p1 = std::string::npos;
  
  if (p0 != std::string::npos)
  {
    p1 = basename.find('d', p0);
    
    if (p1 != std::string::npos)
    {
      for (size_t p=p0+1; p<p1; ++p)
      {
        char c = basename[p];
        
        if (c < '0' || c > '9')
        {
          p1 = std::string::npos;
          break;
        }
      }
    }
  }
  
  if (p1 == std::string::npos)
  {
    // no frame pattern
    
    files.push_back(filePattern);
    
    if (start)
    {
      *start = -1;
    }
    if (end)
    {
      *end = -1;
    }
  }
  else
  {
    // Build maya filespec string for using with getFileList
    MString mayaSpec;
    
    mayaSpec += basename.substr(0, p0).c_str();
    mayaSpec += "*";
    mayaSpec += basename.substr(p1 + 1).c_str();
    
    p0 = dirname.find('\\');
    while (p0 != std::string::npos)
    {
      dirname[p0] = '/';
      p0 = dirname.find('\\', p0+1);
    }
    
    if (dirname[dirname.length()-1] != '/')
    {
      dirname += "/";
    }
    
    MStringArray allFiles;
    std::map<int, std::string> frameFiles;
    
    MGlobal::executeCommand("getFileList -filespec \"" + mayaSpec + "\" -folder \"" + MString(dirname.c_str()) + "\"", allFiles);
    
    int frame = -1;
    int sframe = 999999;
    int eframe = -999999;
    
    for (unsigned int i=0; i<allFiles.length(); ++i)
    {
      if (sscanf(allFiles[i].asChar(), basename.c_str(), &frame) != 1)
      {
        MGlobal::displayWarning("queryF3d: File \"" + allFiles[i] + "\" doesn't match frame pattern");
      }
      else
      {
        if (frame < sframe)
        {
          sframe = frame;
        }
        else if (frame > eframe)
        {
          eframe = frame;
        }
        frameFiles[frame] = dirname + allFiles[i].asChar();
      }
    }
    
    if (frameFiles.size() > 0)
    {
      files.resize(frameFiles.size());
      
      size_t i = 0;
      
      for (std::map<int, std::string>::iterator it = frameFiles.begin(); it != frameFiles.end(); ++it, ++i)
      {
        files[i] = it->second;
      }
    }
    else
    {
      sframe = -1;
      eframe = -1;
    }
    
    if (start)
    {
      *start = sframe;
    }
    
    if (end)
    {
      *end = eframe;
    }
  }
  
  return files.size();
}