//------------------------------------------------------
    void MaterialExporter::exportMaterialsByShaderPlug()
    {
        // Get all shaders, which are in the default shader list.
        MObject defaultShaderList = DagHelper::getNode ( ATTR_DEFAULT_SHADER_LIST1 );
        MPlug defaultShadersPlug = MFnDependencyNode ( defaultShaderList ).findPlug ( ATTR_SHADERS );

        uint shaderCount = defaultShadersPlug.evaluateNumElements();
        for ( uint i = 0; i < shaderCount; ++i )
        {
            MObject shader = DagHelper::getNodeConnectedTo ( defaultShadersPlug.elementByPhysicalIndex ( i ) );
            MFnDependencyNode shadingEngineFn ( shader );

            // Get the name of the current material (this is the maya material id)
            String mayaMaterialId = DocumentExporter::mayaNameToColladaName ( shadingEngineFn.name(), true );

            bool doExportMaterial = true;
            bool isFromReferencedFile = shadingEngineFn.isFromReferencedFile();
//            bool isDefaulNode = shadingEngineFn.isDefaultNode();
//             if ( isDefaulNode ) 
//             {
//                 doExportMaterial = false;
//             }
//             else if ( isFromReferencedFile )
            if ( isFromReferencedFile )
            {
                if ( ExportOptions::exportXRefs() && ExportOptions::dereferenceXRefs() ) doExportMaterial = true;
                else doExportMaterial = false;
            }

            if ( doExportMaterial )
            {
                MObject shadingEngine = ShaderHelper::getShadingEngine ( shader );
                exportMaterial ( shadingEngine );
            }
        }
    }
MStatus findTexturesPerPolygon::doIt( const MArgList& )
//
//  Description:
//      Find the texture files that apply to the color of each polygon of
//      a selected shape if the shape has its polygons organized into sets.
//
{
    // Get the selection and choose the first path on the selection list.
    //
	MStatus status;
	MDagPath path;
	MObject cmp;
	MSelectionList slist;
	MGlobal::getActiveSelectionList(slist);
	slist.getDagPath(0, path, cmp);

	// Have to make the path include the shape below it so that
	// we can determine if the underlying shape node is instanced.
	// By default, dag paths only include transform nodes.
	//
	path.extendToShape();

	// If the shape is instanced then we need to determine which
	// instance this path refers to.
	//
	int instanceNum = 0;
	if (path.isInstanced())
		instanceNum = path.instanceNumber();

    // Get a list of all sets pertaining to the selected shape and the
    // members of those sets.
    //
	MFnMesh fnMesh(path);
	MObjectArray sets;
	MObjectArray comps;
	if (!fnMesh.getConnectedSetsAndMembers(instanceNum, sets, comps, true))
		cerr << "ERROR: MFnMesh::getConnectedSetsAndMembers\n";

	// Loop through all the sets.  If the set is a polygonal set, find the
    // shader attached to the and print out the texture file name for the
    // set along with the polygons in the set.
	//
	for ( unsigned i=0; i<sets.length(); i++ ) {
		MObject set = sets[i];
		MObject comp = comps[i];

		MFnSet fnSet( set, &status );
		if (status == MS::kFailure) {
            cerr << "ERROR: MFnSet::MFnSet\n";
            continue;
        }

        // Make sure the set is a polygonal set.  If not, continue.
		MItMeshPolygon piter(path, comp, &status);
		if ((status == MS::kFailure) || comp.isNull())
            continue;

		// Find the texture that is applied to this set.  First, get the
		// shading node connected to the set.  Then, if there is an input
		// attribute called "color", search upstream from it for a texture
		// file node.
        //
		MObject shaderNode = findShader(set);
		if (shaderNode == MObject::kNullObj)
			continue;

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

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

		if (status == MS::kFailure)
			continue;
		
		dgIt.disablePruningOnFilter();

        // If no texture file node was found, just continue.
        //
		if (dgIt.isDone())
			continue;
		  
        // Print out the texture node name and texture file that it references.
        //
		MObject textureNode = dgIt.thisNode();
        MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
        MString textureName;
        filenamePlug.getValue(textureName);
		cerr << "Set: " << fnSet.name() << endl;
        cerr << "Texture Node Name: " << MFnDependencyNode(textureNode).name() << endl;
		cerr << "Texture File Name: " << textureName.asChar() << endl;
        
        // Print out the set of polygons that are contained in the current set.
        //
		for ( ; !piter.isDone(); piter.next() )
			cerr << "    poly component: " << piter.index() << endl;
	}

	return MS::kSuccess;
}
    // --------------------------------------
    void ReferenceManager::processReference ( const MObject& referenceNode )
    {
        MStatus status;
        MFnDependencyNode referenceNodeFn ( referenceNode, &status );
        if (status != MStatus::kSuccess) return;

#if MAYA_API_VERSION >= 600
        MString referenceNodeName = MFnDependencyNode( referenceNode ).name();

        Reference* reference = new Reference();
        reference->referenceNode = referenceNode;
        mReferences.push_back ( reference );

        // Get the paths of the root transforms included in this reference
        MObjectArray subReferences;
        getRootObjects ( referenceNode, reference->paths, subReferences );
        uint pathCount = reference->paths.length();

        // Process the sub-references first
        uint subReferenceCount = subReferences.length();
        for (uint i = 0; i < subReferenceCount; ++i)
        {
            MObject& subReference = subReferences[i];
            if ( subReference != MObject::kNullObj ) processReference ( subReference );
        }

        // Retrieve the reference node's filename
        MString command = MString("reference -rfn \"") + referenceNodeFn.name() + MString("\" -q -filename;");
        MString filename;
        status = MGlobal::executeCommand ( command, filename );
        if (status != MStatus::kSuccess || filename.length() == 0) return;

        // Strip the filename of the multiple file token
        int stripIndex = filename.index('{');
        if (stripIndex != -1) filename = filename.substring(0, stripIndex - 1);

        // Avoid transform look-ups on COLLADA references.
        int extLocation = filename.rindex('.');
        if (extLocation > 0)
        {
            MString ext = filename.substring(extLocation + 1, filename.length() - 1).toLowerCase();
            if (ext == "dae" || ext == "xml") return;
        }

        // Check for already existing file information
        // Otherwise create a new file information sheet with current node names
        for ( ReferenceFileList::iterator it = mFiles.begin(); it != mFiles.end(); ++it )
        {
            if ((*it)->filename == filename) 
            { 
                reference->file = (*it); 
                break; 
            }
        }

        if ( reference->file == NULL ) reference->file = processReferenceFile(filename);

        // Get the list of the root transform's first child's unreferenced parents.
        // This is a list of the imported nodes!
        for (uint j = 0; j < pathCount; ++j)
        {
            MDagPath path = reference->paths[j];
            if (path.childCount() > 0)
            {
                path.push ( path.child(0) );
                MFnDagNode childNode ( path );
                if (!childNode.object().hasFn(MFn::kTransform)) continue;

                uint parentCount = childNode.parentCount();
                for (uint k = 0; k < parentCount; ++k)
                {
                    MFnDagNode parentNode(childNode.parent(k));
                    if (parentNode.object() == MObject::kNullObj || parentNode.isFromReferencedFile()) continue;

                    MDagPath parentPath = MDagPath::getAPathTo(parentNode.object());
                    if (parentPath.length() > 0)
                    {
                        ReferenceRootList::iterator it = 
                            reference->reroots.insert( reference->reroots.end(), ReferenceRoot() );
                        (*it).index = j;
                        (*it).reroot = parentPath;
                    }
                }
            }
        }
#endif
    }
	MStatus ReferenceManager::getReferenceFilename(const MObject & referenceNode, MString & referenceFilename)
	{
		MString command = MString("referenceQuery -filename ") + MFnDependencyNode(referenceNode).name();
		return MGlobal::executeCommand(command, referenceFilename);
	}
//-----------------------------------------------------------------------------
// Creates a vstAttachment Locator
//-----------------------------------------------------------------------------
MStatus CVstAttachmentCmd::DoCreate()
{
	MDagModifier *mDagModifier( new MDagModifier );

	if ( !mDagModifier )
	{
		merr << "Can't create new MDagModifier" << std::endl;
		return MS::kFailure;
	}

	MString optName( "vstAttachment" );
	if ( m_mArgDatabase->isFlagSet( kOptName ) )
	{
		m_mArgDatabase->getFlagArgument( kOptName, 0, optName );
	}

	// Create the helper bone locator's transform
	MObject xObj = mDagModifier->createNode( "transform" );
	mDagModifier->doIt();

	if ( xObj.isNull() )
	{
		merr << "Can't create new transform node" << std::endl;
		return MS::kFailure;
	}

	// name the shape & the transform the same thing
	mDagModifier->renameNode( xObj, optName );
	mDagModifier->doIt();

	MObject vstAttachmentObj = mDagModifier->createNode( "vstAttachment", xObj );

	if ( vstAttachmentObj.isNull() )
	{
		merr << "Can't create new vstAttachment node" << std::endl;
		mDagModifier->undoIt();
		return MS::kFailure;
	}

	// name the shape & the transform the same thing
	mDagModifier->renameNode( vstAttachmentObj, MFnDependencyNode( xObj ).name() );
	mDagModifier->doIt();

	m_undoable = true;
	m_mDagModifier = mDagModifier;

	if ( m_mArgDatabase->isFlagSet( kOptParent ) )
	{
		MSelectionList mSelectionList;
		m_mArgDatabase->getObjects( mSelectionList );
		for ( MItSelectionList sIt( mSelectionList, MFn::kDagNode ); !sIt.isDone(); sIt.next() )
		{
			MDagPath mDagPath;
			if ( sIt.getDagPath( mDagPath ) )
			{
				m_mDagModifier->reparentNode( xObj, mDagPath.node() );
				m_mDagModifier->doIt();
				break;
			}
		}
	}

	// Save the current selection just in case we want to undo stuff
	MGlobal::getActiveSelectionList( m_mSelectionList );

	MDagPath xDagPath;
	MDagPath::getAPathTo( xObj, xDagPath );
	MGlobal::select( xDagPath, MObject::kNullObj, MGlobal::kReplaceList );
	setResult( xDagPath.partialPathName() );

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

        try
        {
            // Save current selection
            MSelectionList selection;
            MGlobal::getActiveSelectionList(selection);

            // Extract the filename
#if defined (OSMac_)
            char nameBuffer[MAXPATHLEN];
            strcpy ( nameBuffer, file.fullName().asChar() );
            const MString fileName ( nameBuffer );
#else
            const MString fileName = file.fullName();
#endif // OSMac

            // TODO Export the referenced files!
            // Maya forces the write of all the references, on export.
            // Intentionally skip known reference file paths.
            for ( MItDependencyNodes it ( MFn::kReference ); !it.isDone(); it.next() )
            {
                MObject refNode = it.item();
                MString refNodeName = MFnDependencyNode ( refNode ).name();

                MString refNodeFilename;
                MGlobal::executeCommand ( MString ( "reference -rfn \"" ) + refNodeName + MString ( "\" -q -filename" ),
                                          refNodeFilename );

                if ( refNodeFilename == fileName ) return MStatus::kSuccess;

                if ( ExportOptions::exportXRefs() )
                {
                    // TODO Open file export dialog ( !? HOW ?! ) to get a DAE filename 
                    // to export the referenced file.
                    
                }
            }

            // Parse the export options
            ExportOptions::set ( options );

            // Check, if we should just export the selected Objects
            exportSelection = mode == MPxFileTranslator::kExportActiveAccessMode;

            // Do the actual export now
            status = exportIntoFile ( fileName, exportSelection );

            // Restore selection
            MGlobal::setActiveSelectionList(selection);
        }
        catch ( COLLADASW::StreamWriterException* swException  )
        {
            String message = "StreamWriterException: " + swException->getMessage();
            MGlobal::displayWarning ( message.c_str() );
        }
        catch ( ... )
        {
            MGlobal::displayWarning ( "ColladaMaya has thrown an exception!" );
        }

        return status;
    }
//-----------------------------------------------------------------------------
// Figures out the material path name from the maya shading group
//-----------------------------------------------------------------------------
MString ValveMaya::GetMaterialPath(
	const MObject &shadingGroupObj,
	MObject *pFileObj,
	MObject *pPlace2dTextureObj,
	MObject *pVmtObj,
	bool *pbTransparent,
	MString *pDebugWhy )
{
	MString materialPath( "debug/debugEmpty" );

	const MObject surfaceShaderObj( FindInputNode( shadingGroupObj, "surfaceShader" ) );
	if ( surfaceShaderObj.isNull() )
	{
		if ( pDebugWhy )
		{
			*pDebugWhy = MString( "Can't find surfaceShader node from shadingGroup: No input to " ) +
				MFnDependencyNode( shadingGroupObj ).name() + ".surfaceShader";
		}

		return materialPath;
	}

	if ( MFnDependencyNode( surfaceShaderObj ).typeName() == "vsVmt" )
	{
		MPlug vmtP = MFnDependencyNode( surfaceShaderObj ).findPlug( "vmtPath" );
		if ( !vmtP.isNull() )
		{
			vmtP.getValue( materialPath );
			return materialPath;
		}
	}


	const MObject fileObj( FindInputNodeOfType( surfaceShaderObj, "file", "color" ) );
	if ( fileObj.isNull() )
	{
		if ( pDebugWhy )
		{
			*pDebugWhy = MString( "Can't find file texture node from surfaceShader: No input to " ) +
				MFnDependencyNode( surfaceShaderObj ).name() + ".color";
		}

		return materialPath;
	}

	if ( pFileObj )
	{
		*pFileObj = fileObj;
	}

	if ( pbTransparent )
	{
		const MObject transObj( FindInputNodeOfType( surfaceShaderObj, "file", "transparency" ) );
		if ( fileObj == transObj )
		{
			*pbTransparent = true;
		}
	}

	if ( pPlace2dTextureObj )
	{
		MObject place2dTextureObj( FindInputNodeOfType( fileObj, "place2dTexture", "uvCoord" ) );
		if ( !place2dTextureObj.isNull() )
		{
			const MPlug uvCoordP( MFnDependencyNode( place2dTextureObj ).findPlug( "uvCoord" ) );
			if ( !( uvCoordP.isNull() || uvCoordP.isConnected() || uvCoordP.isLocked() ) )
			{
				*pPlace2dTextureObj = place2dTextureObj;
			}
		}
	}

	// Check to see if a vsVmtToTex node is driving the filename
	const MObject vsVmtToTexObj = FindInputNodeOfType( fileObj, "vsVmtToTex" );
	if ( !vsVmtToTexObj.isNull() )
	{
		if ( pVmtObj )
		{
			*pVmtObj = vsVmtToTexObj;
		}

		const MPlug materialPathP = MFnDependencyNode( vsVmtToTexObj ).findPlug( "materialPath" );
		if ( !materialPathP.isNull() )
		{
			materialPathP.getValue( materialPath );
			if ( materialPath.length() )
			{
				return materialPath;
			}
		}
	}

	// Otherwise do path munging to figure out 
	MString fileTexture;
	int fLen( 0 );

	const MFnDependencyNode fileFn( fileObj );
	const MPlug fileP( fileFn.findPlug( "fileTextureName" ) );
	fileP.getValue( fileTexture );
	fLen = fileTexture.length();
	if ( fLen == 0 )
	{
		if ( pDebugWhy )
		{
			*pDebugWhy = MString( "No texture filename specified on file texture node: " ) +
				MFnDependencyNode( fileObj ).name() + ".fileTextureName is empty";
		}

		return materialPath;
	}

	MStringArray path;
	const uint pLen( SplitPath( StripExtension( fileTexture ), path ) );

	if ( pLen == 0 )
		return fileTexture.asChar();

	materialPath = path[ pLen - 1 ];
	// Make the path into a relative path
	for ( int i = pLen - 2; i >= 0; --i )
	{
		if ( i > 1 && ( !stricmp( path[ i - 1 ].asChar(), "game" ) || !stricmp( path[ i - 1 ].asChar(), "content" ) ) )
			break;

		if ( !stricmp( path[ i ].asChar(), "materials" ) || !stricmp( path[ i ].asChar(), "materialsrc" ) )
			break;

		materialPath = path[ i ] + "/" + materialPath;
	}

	return materialPath;
}
//-----------------------------------------------------------------------------
//
// Purpose: Create a Maya Dag node named properly
//
//-----------------------------------------------------------------------------
MStatus ValveMaya::CreateDagNode(
	const char *const i_nodeType,
	const char *const i_transformName,
	const MObject &i_parentObj,
	MObject *o_pTransformObj,
	MObject *o_pShapeObj,
	MDagModifier *i_mDagModifier)
{
	MStatus retVal;

	// If the user didn't supply an MDagModifier make a temporary one
	MDagModifier tmpDagModifier;
	MDagModifier &mDagModifier( i_mDagModifier ? *i_mDagModifier : tmpDagModifier );

	// Try and create the node
	const MObject tObj( mDagModifier.createNode( i_nodeType, i_parentObj, &retVal ) );
	if ( !retVal )
		return retVal;

	mDagModifier.doIt();

	// Failed... undo the Dag modifier and return failure
	if ( tObj.isNull() )
	{
		mDagModifier.undoIt();
        return MS::kFailure;
	}

	// If the caller wants a copy of the created Transform MObject save it
	if ( o_pTransformObj )
		*o_pTransformObj = tObj;

	// The name the shape will be called
	MString sName;

	// Set the name of the transform, it's either the name of the node type or the called specified name
	if ( i_transformName )
	{
		retVal = mDagModifier.renameNode( tObj, i_transformName );
		sName = i_transformName;
    }
	else
	{
		retVal = mDagModifier.renameNode( tObj, i_nodeType );
		sName = i_nodeType;
	}

	// If the rename failed, undo the dag modifier and quit
	if ( !retVal )
	{
		mDagModifier.undoIt();
		return retVal;
	}

	mDagModifier.doIt();

	// Search for the shape node that was created, normally there will be only 1 shape but there are pathological
	// cases, some might not quite be handled here but most will be
	MDagPath tDagPath( MDagPath::getAPathTo( tObj ) );
	unsigned sEnd( 0 );
	tDagPath.numberOfShapesDirectlyBelow( sEnd );

	for ( unsigned si( 0 ); si != sEnd; ++si )
	{
		MDagPath sDagPath( tDagPath );
		sDagPath.extendToShapeDirectlyBelow( si );

		if ( MFnDagNode( sDagPath ).typeName() == i_nodeType )
		{
			// Add the %d suffix so sscanf can be used to check if Maya added a numeric suffix to the transform name
			const MString tScanfName( sName + "%d" );

			// Add the 'Shape' Suffix to the shape name
			sName += "Shape";

			// Get the actual name Maya assigned the node so it can be scanned for a Maya added numeric suffix
			const MString tName( MFnDependencyNode( tObj ).name() );
			int numericSuffix( 0 );

			switch ( sscanf( tName.asChar(), tScanfName.asChar(), &numericSuffix ) )
			{
			case 0:
			default:
				// There was no numeric suffix added by Maya, so nothing extra to add
				break;
			case 1:
				// Maya added a numeric suffix, add it to the shape name
				sName += numericSuffix;
				break;
			}

			// Rename the shape node so it now matches the transform, this operation can't really fail
			const MObject sObj( sDagPath.node() );

			// If the caller wants a copy of the created Transform MObject save it
			if ( o_pShapeObj )
				*o_pShapeObj = sObj;

			mDagModifier.renameNode( sObj, sName );
			mDagModifier.doIt();

			// Just do the first shape of the appropriate type found
			break;
		}
	}
			
	return retVal;
}
Beispiel #9
0
MStatus ScbWriter::dumpData()
{
    MStatus status;
    MDagPath dag_path;
    MDagPath mesh_dag_path;
    MFnSkinCluster fn_skin_cluster;

    MSelectionList selection_list;
    if (MStatus::kSuccess != MGlobal::getActiveSelectionList(selection_list))
        FAILURE("ScbWriter: MGlobal::getActiveSelectionList()");

    MItSelectionList it_selection_list(selection_list, MFn::kMesh, &status);    
    if (status != MStatus::kSuccess)
        FAILURE("ScbWriter: it_selection_list()");

    if (it_selection_list.isDone())
        FAILURE("ScbWriter: no mesh selected!");

    it_selection_list.getDagPath(mesh_dag_path);
    it_selection_list.next();

    if (!it_selection_list.isDone())
        FAILURE("ScbWriter: more than one mesh selected!");

    MFnMesh mesh(mesh_dag_path);

    strcpy_s(data_.name, ScbData::kNameLen, mesh.name().asChar());

    // get shaders
    int instance_num = 0;
    if (mesh_dag_path.isInstanced())
        instance_num = mesh_dag_path.instanceNumber();

    MObjectArray shaders;
    MIntArray shader_indices;
    mesh.getConnectedShaders(instance_num, shaders, shader_indices);
    int shader_count = shaders.length();

    MGlobal::displayInfo(MString("shaders for this mesh : ") + shader_count);

    // check for holes
    MIntArray hole_info_array;
    MIntArray hole_vertex_array;
    mesh.getHoles(hole_info_array, hole_vertex_array);
    if (hole_info_array.length() != 0)
        FAILURE("ScbWriter: mesh contains holes");

    // check for triangulation
    MItMeshPolygon mesh_polygon_iter(mesh_dag_path);
    for (mesh_polygon_iter.reset(); !mesh_polygon_iter.isDone(); mesh_polygon_iter.next())
    {
        if (!mesh_polygon_iter.hasValidTriangulation())
            FAILURE("ScbWriter: a poly has no valid triangulation");
    }

    // get transform
    MFnTransform transform_node(mesh.parent(0));
    MVector pos = transform_node.getTranslation(MSpace::kTransform);

    // get vertices
    int num_vertices = mesh.numVertices();
    data_.num_vtxs = num_vertices;
    MFloatPointArray vertex_array;
    mesh.getPoints(vertex_array, MSpace::kWorld); // kObject is done by removing translation values
                                                 // that way scales and rotations are kept.

    for (int i = 0; i < num_vertices; i++)
    {
        ScbVtx vtx;
        vtx.x = vertex_array[i].x - static_cast<float>(pos.x);
        vtx.y = vertex_array[i].y - static_cast<float>(pos.y);
        vtx.z = vertex_array[i].z - static_cast<float>(pos.z);

        // check for min
        if (vtx.x < data_.bbx || i == 0)
            data_.bbx = vtx.x;
        if (vtx.y < data_.bby || i == 0)
            data_.bby = vtx.y;
        if (vtx.z < data_.bbz || i == 0)
            data_.bbz = vtx.z;
        // check for max
        if (vtx.x > data_.bbdx || i == 0)
            data_.bbdx = vtx.x;
        if (vtx.y > data_.bbdy || i == 0)
            data_.bbdy = vtx.y;
        if (vtx.z > data_.bbdz || i == 0)
            data_.bbdz = vtx.z;

        data_.vertices.push_back(vtx);
    }

    // bbd is the size so :
    data_.bbdx -= data_.bbx;
    data_.bbdy -= data_.bby;
    data_.bbdz -= data_.bbz;

    // get UVs
    MFloatArray u_array;
    MFloatArray v_array;
    mesh.getUVs(u_array, v_array);
    MIntArray uv_counts;
    MIntArray uv_ids;
    mesh.getAssignedUVs(uv_counts, uv_ids);

    // get triangles
    MIntArray triangle_counts;
    MIntArray triangle_vertices;
    mesh.getTriangles(triangle_counts, triangle_vertices);
    int numPolys = mesh.numPolygons();

    // fill data
    int cur = 0;
    for (int i = 0; i < numPolys; i++)
    {
        int triangle_count = triangle_counts[i];
        int shader = shader_indices[i];
        for (int j = 0; j < triangle_count; j++)
            data_.shader_per_triangle.push_back(shader);
        for (int j = 0; j < triangle_count * 3; j++)
        {
            
            data_.indices.push_back(triangle_vertices[cur]);
            data_.u_vec.push_back(u_array[uv_ids[cur]]);
            data_.v_vec.push_back(1 - v_array[uv_ids[cur]]);
            cur++;
        }
    }
    data_.num_indices = cur;

    // fill materials
    for (int i = 0; i < shader_count; i++)
    {
        ScbMaterial material;
        
        // get the plug for SurfaceShader
        MPlug shader_plug = MFnDependencyNode(shaders[i]).findPlug("surfaceShader");

        // get the connections to this plug
        MPlugArray plug_array;
        shader_plug.connectedTo(plug_array, true, false, &status);

        // first connection is material.
        MFnDependencyNode surface_shader(plug_array[0].node());

        strcpy_s(material.name, ScbMaterial::kNameLen, surface_shader.name().asChar());

        data_.materials.push_back(material);
    }

    return MS::kSuccess;
}
MStatus CVstAimCmd::redoIt()
{
	MStatus mStatus;

	if ( !mStatus )
	{
		setResult( MString( "Cannot parse command line" ) + mStatus.errorString() );
		return MS::kFailure;
	}

	if ( m_mArgDatabase->isFlagSet( kHelp ) )
	{
		PrintHelp();
	}
	else
	{
		// See if there are two object specified

		MDagPath mDagPath;
		MSelectionList optSelectionList;

		// Validate specified items to whole dag nodes
		{
			MSelectionList tmpSelectionList;
			m_mArgDatabase->getObjects( tmpSelectionList );
			for ( MItSelectionList sIt( tmpSelectionList, MFn::kDagNode ); !sIt.isDone(); sIt.next() )
			{
				if ( sIt.getDagPath( mDagPath ) )
				{
					optSelectionList.add( mDagPath, MObject::kNullObj, true );
				}
			}
		}

		if ( m_mArgDatabase->isFlagSet( "create" ) || optSelectionList.length() >= 2 && m_mArgDatabase->numberOfFlagsUsed() == 0 )
		{
			// Error if there aren't at least two
			if ( optSelectionList.length() < 2 )
			{
				displayError( GetName() + " needs at least two objects specified or selected when -create is used" );
				return MS::kFailure;
			}

			// Get name command line arg
			MString optName;
			if ( m_mArgDatabase->isFlagSet( "name" ) )
			{
				m_mArgDatabase->getFlagArgument( "name", 0, optName );
			}

			m_undoable = true;
			m_mDagModifier = new MDagModifier;

			MObject vstAimObj( m_mDagModifier->MDGModifier::createNode( GetName() ) );
			if ( m_mDagModifier->doIt() != MS::kSuccess )
			{
				displayError( MString( "Couldn't create " ) + GetName() + " node" );
				m_mDagModifier->undoIt();
				delete m_mDagModifier;
				m_mDagModifier = NULL;
				m_undoable = false;

				return MS::kFailure;
			}

			m_mDagModifier->renameNode( vstAimObj, optName.length() ? optName : GetName() );
			if ( m_mDagModifier->doIt() != MS::kSuccess )
			{
				if ( optName.length() )
				{
					displayWarning( MString( "Couldn't rename newly created vstNode \"" ) + optName + "\"" );
				}
			}

			// Set options on the newly create vstAim node

			MFnDependencyNode vstAimFn( vstAimObj );

			MPlug sP;
			MPlug dP;

			if ( m_mArgDatabase->isFlagSet( kAim ) )
			{
				MVector aim;
				m_mArgDatabase->getFlagArgument( kAim, 0, aim.x );
				m_mArgDatabase->getFlagArgument( kAim, 1, aim.y );
				m_mArgDatabase->getFlagArgument( kAim, 2, aim.z );

				sP = vstAimFn.findPlug( "aimX" );
				sP.setValue( aim.x );

				sP = vstAimFn.findPlug( "aimY" );
				sP.setValue( aim.y );

				sP = vstAimFn.findPlug( "aimZ" );
				sP.setValue( aim.z );
			}

			if ( m_mArgDatabase->isFlagSet( kUp ) )
			{
				MVector up;
				m_mArgDatabase->getFlagArgument( kUp, 0, up.x );
				m_mArgDatabase->getFlagArgument( kUp, 1, up.y );
				m_mArgDatabase->getFlagArgument( kUp, 2, up.z );

				sP = vstAimFn.findPlug( "upX" );
				sP.setValue( up.x );

				sP = vstAimFn.findPlug( "upY" );
				sP.setValue( up.y );

				sP = vstAimFn.findPlug( "upZ" );
				sP.setValue( up.z );
			}

			// Now connect up the newly created vstAim node

			MDagPath toAim;
			optSelectionList.getDagPath( 1, toAim );
			const MFnDagNode toAimFn( toAim );

			if ( toAim.hasFn( MFn::kJoint ) )
			{
				MPlug joP( toAimFn.findPlug( "jointOrient" ) );
				if ( !joP.isNull() )
				{
					MAngle jox, joy, joz;
					joP.child( 0 ).getValue( jox );
					joP.child( 1 ).getValue( joy );
					joP.child( 2 ).getValue( joz );
					if ( abs( jox.value() ) > FLT_EPSILON || abs( joy.value() ) > FLT_EPSILON || abs( joz.value() ) > FLT_EPSILON )
					{
						mwarn << "Joint orient on node being constrained is non-zero ( " << jox.asDegrees() << " " << joy.asDegrees() << " " << joz.asDegrees() << " ), setting to 0" << std::endl;
						joP.child( 0 ).setValue( MAngle( 0.0 ) );
						joP.child( 1 ).setValue( MAngle( 0.0 ) );
						joP.child( 2 ).setValue( MAngle( 0.0 ) );
					}
				}
			}

			if ( toAim.hasFn( MFn::kTransform ) )
			{
				MPlug mP( toAimFn.findPlug( "rotateAxis" ) );
				if ( !mP.isNull() )
				{
					MAngle rx, ry, rz;
					mP.child( 0 ).getValue( rx );
					mP.child( 1 ).getValue( ry );
					mP.child( 2 ).getValue( rz );
					if ( abs( rx.value() ) > FLT_EPSILON || abs( ry.value() ) > FLT_EPSILON || abs( rz.value() ) > FLT_EPSILON )
					{
						mwarn << "Rotate Axis on node being constrained is non-zero ( " << rx.asDegrees() << " " << ry.asDegrees() << " " << rz.asDegrees() << " ), setting to 0" << std::endl;
						mP.child( 0 ).setValue( MAngle( 0.0 ) );
						mP.child( 1 ).setValue( MAngle( 0.0 ) );
						mP.child( 2 ).setValue( MAngle( 0.0 ) );
					}
				}
			}

			MDagPath aimAt;
			optSelectionList.getDagPath( 0, aimAt );
			const MFnDagNode aimAtFn( aimAt );

			// toAim.rotateOrder -> vstAim.rotateOrder
			sP = toAimFn.findPlug( "rotateOrder" );
			dP = vstAimFn.findPlug( "rotateOrder" );
			m_mDagModifier->connect( sP, dP );

			// toAim.translate -> vstAim.translate
			sP = toAimFn.findPlug( "translate" );
			dP = vstAimFn.findPlug( "translate" );
			m_mDagModifier->connect( sP, dP );

			// toAim.parentMatrix[ instance ] -> vstAim.parentSpace
			sP = toAimFn.findPlug( "parentMatrix" );
			sP = sP.elementByLogicalIndex( toAim.instanceNumber() );
			dP = vstAimFn.findPlug( "parentSpace" );
			m_mDagModifier->connect( sP, dP );

			// aimAt.worldMatrix[ instance ] -> vstAim.aimSpace
			sP = aimAtFn.findPlug( "worldMatrix" );
			sP = sP.elementByLogicalIndex( aimAt.instanceNumber() );
			dP = vstAimFn.findPlug( "aimSpace" );
			m_mDagModifier->connect( sP, dP );

			// vstAim.rotation -> toAim.rotation
			// These have to be connected individually because Maya plays stupid tricks
			// with rotateOrder if they aren't
			sP = vstAimFn.findPlug( "rotateX" );
			dP = toAimFn.findPlug( "rotateX" );
			m_mDagModifier->connect( sP, dP );

			sP = vstAimFn.findPlug( "rotateY" );
			dP = toAimFn.findPlug( "rotateY" );
			m_mDagModifier->connect( sP, dP );

			sP = vstAimFn.findPlug( "rotateZ" );
			dP = toAimFn.findPlug( "rotateZ" );
			m_mDagModifier->connect( sP, dP );

			if ( m_mDagModifier->doIt() != MS::kSuccess )
			{
				displayWarning( MString( GetName() ) + ": Couldn't connect everything when creating" );
			}

			// Save the current selection just in case we want to undo stuff
			MGlobal::getActiveSelectionList( m_mSelectionList );

			MGlobal::select( vstAimObj, MGlobal::kReplaceList );
			setResult( vstAimFn.name() );
		}
		else if ( m_mArgDatabase->isFlagSet( "select" ) )
		{
			MSelectionList mSelectionList;
			MDagPath mDagPath;

			for ( MItDag dagIt; !dagIt.isDone(); dagIt.next() )
			{
				if ( MFnDependencyNode( dagIt.item() ).typeName() == GetName() )
				{
					dagIt.getPath( mDagPath );
					mSelectionList.add( mDagPath, MObject::kNullObj, true );
				}
			}

			if ( mSelectionList.length() )
			{
				m_undoable = true;
				// Save the current selection just in case we want to undo stuff
				MGlobal::getActiveSelectionList( m_mSelectionList );
				MGlobal::setActiveSelectionList( mSelectionList, MGlobal::kReplaceList );
			}
		}
		else
		{
			displayError( GetName() + ": No valid operation specified via command line arguments\n" );
		}
	}

	return MS::kSuccess;
}
Beispiel #11
0
	void PhongMat::Insert(std::ostream& fout) const {
		
		MStatus status;
		MObject object;
		/*
		for(int j = 0; j < shaderNode.attributeCount(); j++)
		{			
			MPlug m = shaderNode.findPlug(shaderNode.attribute(j), false);
			std::cout << " " << shaderNode.attribute(j).apiTypeStr() << " " << " plug " << m.name() << std::endl;
		}
		std::cout << std::endl;*/
		//MPlug reflectivityPlug = MFnDependencyNode(shaderNode).findPlug("reflectivity");

		MPlug sigmaPlug = MFnDependencyNode(shaderNode).findPlug("cosinePower");		

		MPlug colorPlug = MFnDependencyNode(shaderNode).findPlug("color");
		status = colorPlug.getValue(object);
		if (status != MStatus::kSuccess) { MGlobal::displayWarning("Could not get color value out"); }

		MFnNumericData colorData(object, &status);
		if (status != MStatus::kSuccess) { MGlobal::displayWarning("Could not get color value out (2)");  }

		MPlug specularPlug = MFnDependencyNode(shaderNode).findPlug("specularColor");
		status = specularPlug.getValue(object);
		if (status != MStatus::kSuccess) { MGlobal::displayWarning("Could not get specular color value out"); }
		
		MFnNumericData specularData(object, &status);
		if (status != MStatus::kSuccess) { MGlobal::displayWarning("Could not get specular color data"); }
				
		fout << "Material \"phongmat\" ";																		
		
		if (colorData.numericType() == MFnNumericData::k3Float) {
			float r,g,b;
			colorData.getData(r,g,b);						
			fout << "\"color rhod\" [" << r << " " << g << " " << b << "] ";
		} else if (colorData.numericType() == MFnNumericData::k3Double) {
			double r,g,b;
			colorData.getData(r,g,b);						
			fout << "\"color rhod\" [" << r << " " << g << " " << b << "] ";
		} else {
			MGlobal::displayWarning("Invalid data type");
		}		
		
		if (specularData.numericType() == MFnNumericData::k3Float) {
			float r,g,b;
			specularData.getData(r,g,b);				
			fout << "\"color rhos\" [" << r << " " << g << " " << b << "] ";
			
		} else if (specularData.numericType() == MFnNumericData::k3Double) {
			double r,g,b;
			specularData.getData(r,g,b);
			fout << "\"color rhos\" [" << r << " " << g << " " << b << "] ";
		} else {
			MGlobal::displayWarning("Invalid data type");
		}
			
		float sigma;
		status = sigmaPlug.getValue(sigma);
		if (status == MStatus::kSuccess) 
			fout << "\"float sigma\" [" << sigma << "] ";
		
		// sigma = cosine_power
		fout << std::endl;		
	}
Beispiel #12
0
// Load a joint
void skeleton::loadJoint(MDagPath& jointDag,joint* parent)
{
	int i;
	joint newJoint;
	joint* parentJoint = parent;
	if (jointDag.hasFn(MFn::kJoint))
	{
		MFnIkJoint jointFn(jointDag);

		// Get parent index
		int idx=-1;
		if (parent)
		{
			idx = parent->id;
		}
		// Get joint matrix
		MMatrix worldMatrix = jointDag.inclusiveMatrix();
		/*float translation1[3];
		float rotation1[4];
		float scale1[3];
		extractTranMatrix(worldMatrix,translation1,rotation1,scale1);
		Quaternion q(rotation1[0],rotation1[1],rotation1[2],rotation1[3]);
		float angle;
		Vector3 axis;
		q.ToAngleAxis(angle,axis);
		Vector3 x,y,z;
		q.ToAxes(x,y,z);*/
		//printMatrix(worldMatrix);
	
		// Calculate scaling factor inherited by parent
		// Calculate Local Matrix
		MMatrix localMatrix = worldMatrix;
		if (parent)
			localMatrix = worldMatrix * parent->worldMatrix.inverse();
		float translation2[3];
		float rotation2[4];
		float scale2[3];
		extractTranMatrix(worldMatrix,translation2,rotation2,scale2);
		//printMatrix(localMatrix);
	
		// Set joint info
		newJoint.name = jointFn.partialPathName();
		newJoint.id = m_joints.size();
		newJoint.parentIndex = idx;
		newJoint.jointDag = jointDag;
		newJoint.worldMatrix = worldMatrix;
		newJoint.localMatrix = localMatrix;

		for (int iRow = 0; iRow < 4; iRow++)
			for (int iCol = 0; iCol < 3; iCol++)
				newJoint.tran.m_mat[iRow][iCol] = (FLOAT)worldMatrix[iRow][iCol];

		//printMatrix(worldMatrix);

		/*MQuaternion q;
		q = worldMatrix;
		newJoint.tran.q[0] = (float)q.x;
		newJoint.tran.q[1] = (float)q.y;
		newJoint.tran.q[2] = (float)q.z;
		newJoint.tran.q[3] = (float)q.w;
		newJoint.tran.t[0] = (float)worldMatrix[3][0];
		newJoint.tran.t[1] = (float)worldMatrix[3][1];
		newJoint.tran.t[2] = (float)worldMatrix[3][2];*/

		MPlug plug = jointFn.findPlug("unRibbonEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			if(enabled)
			{
				plug = jointFn.findPlug("unRibbonVisible");
				bool visible;
				plug.getValue(visible);
				plug = jointFn.findPlug("unRibbonAbove");
				float above;
				plug.getValue(above);
				plug = jointFn.findPlug("unRibbonBelow");
				float below;
				plug.getValue(below);
				plug = jointFn.findPlug("unRibbonEdgesPerSecond");
				short edgePerSecond;
				plug.getValue(edgePerSecond);
				plug = jointFn.findPlug("unRibbonEdgeLife");
				float edgeLife;
				plug.getValue(edgeLife);
				plug = jointFn.findPlug("unRibbonGravity");
				float gravity;
				plug.getValue(gravity);
				plug = jointFn.findPlug("unRibbonTextureRows");
				short rows;
				plug.getValue(rows);
				plug = jointFn.findPlug("unRibbonTextureCols");
				short cols;
				plug.getValue(cols);
				plug = jointFn.findPlug("unRibbonTextureSlot");
				short slot;
				plug.getValue(slot);
				plug = jointFn.findPlug("unRibbonVertexColor");
				MObject object;
				plug.getValue(object);
				MFnNumericData data(object);
				float r,g,b;
				data.getData(r,g,b);
				plug = jointFn.findPlug("unRibbonVertexAlpha");
				float alpha;
				plug.getValue(alpha);
				plug = jointFn.findPlug("unRibbonBlendMode");
				short blendMode;
				plug.getValue(blendMode);
				plug = jointFn.findPlug("unRibbonTextureFilename");

				MItDependencyGraph dgIt(plug, MFn::kFileTexture,
					MItDependencyGraph::kUpstream, 
					MItDependencyGraph::kBreadthFirst,
					MItDependencyGraph::kNodeLevel);

				dgIt.disablePruningOnFilter();

				MString textureName;
				if (!dgIt.isDone())
				{
					MObject textureNode = dgIt.thisNode();
					MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
					filenamePlug.getValue(textureName);
				}
				else
				{
					char str[256];
					sprintf(str,"%s ribbon system must has file-texture",newJoint.name.asChar());
					MessageBox(0,str,0,0);
				}

				newJoint.hasRibbonSystem = true;
				newJoint.ribbon.visible = visible;
				newJoint.ribbon.above = above;
				newJoint.ribbon.below = below;
				newJoint.ribbon.gravity = gravity;
				newJoint.ribbon.edgePerSecond = edgePerSecond;
				newJoint.ribbon.edgeLife = edgeLife;
				newJoint.ribbon.rows = rows;
				newJoint.ribbon.cols = cols;
				newJoint.ribbon.slot = slot;
				newJoint.ribbon.color[0] = r;
				newJoint.ribbon.color[1] = g;
				newJoint.ribbon.color[2] = b;
				newJoint.ribbon.alpha = alpha;
				newJoint.ribbon.blendMode = blendMode;
				newJoint.ribbon.textureFilename = textureName.asChar();
			}
		}
		plug = jointFn.findPlug("unParticleEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			if(enabled)
			{
				newJoint.hasParticleSystem = true;

				plug = jointFn.findPlug("unParticleVisible");
				bool visible;
				plug.getValue(visible);
				plug = jointFn.findPlug("unParticleSpeed");
				float speed;
				plug.getValue(speed);
				plug = jointFn.findPlug("unParticleVariationPercent");
				float variation;
				plug.getValue(variation);
				plug = jointFn.findPlug("unParticleConeAngle");
				float coneAngle;
				plug.getValue(coneAngle);
				plug = jointFn.findPlug("unParticleGravity");
				float gravity;
				plug.getValue(gravity);
				plug = jointFn.findPlug("unParticleExplosiveForce");
				float explosiveForce = 0.0f;
				if(!plug.isNull())
				{
					plug.getValue(explosiveForce);
				}
				plug = jointFn.findPlug("unParticleLife");
				float life;
				plug.getValue(life);
				plug = jointFn.findPlug("unParticleLifeVariation");
				float lifeVar;
				if(plug.isNull())
				{
					lifeVar = 0.0f;
				}
				else
				{
					plug.getValue(lifeVar);
				}
				plug = jointFn.findPlug("unParticleEmissionRate");
				float emissionRate;
				plug.getValue(emissionRate);
				plug = jointFn.findPlug("unParticleLimitNum");
				short limitNum;
				plug.getValue(limitNum);
				plug = jointFn.findPlug("unParticleInitialNum");
				short initialNum = 0;
				if(!plug.isNull())plug.getValue(initialNum);
				plug = jointFn.findPlug("unParticleAttachToEmitter");
				bool attachToEmitter;
				plug.getValue(attachToEmitter);
				plug = jointFn.findPlug("unParticleMoveWithEmitter");
				bool moveWithEmitter = false;
				if(!plug.isNull())plug.getValue(moveWithEmitter);
				//23
				plug = jointFn.findPlug("unParticleForTheSword");
				bool forTheSword = false;
				if(!plug.isNull())plug.getValue(forTheSword);
				//24
				plug = jointFn.findPlug("unParticleForTheSwordInitialAngle");
				float forTheSwordInitialAngle = 0;
				if(!plug.isNull())plug.getValue(forTheSwordInitialAngle);
				//25
				plug = jointFn.findPlug("unParticleWander");
				bool wander = false;
				if(!plug.isNull())plug.getValue(wander);
				//25
				plug = jointFn.findPlug("unParticleWanderRadius");
				float wanderRadius = 0.0f;
				if(!plug.isNull())plug.getValue(wanderRadius);
				//25
				plug = jointFn.findPlug("unParticleWanderSpeed");
				float wanderSpeed = 0.0f;
				if(!plug.isNull())plug.getValue(wanderSpeed);
				plug = jointFn.findPlug("unParticleAspectRatio");
				float aspectRatio;
				if(plug.isNull())
				{
					aspectRatio = 1.0f;
				}
				else
				{
					plug.getValue(aspectRatio);
				}
				plug = jointFn.findPlug("unParticleInitialAngleBegin");
				float angleBegin;
				if(plug.isNull())
				{
					angleBegin = 0.0f;
				}
				else
				{
					plug.getValue(angleBegin);
				}
				plug = jointFn.findPlug("unParticleInitialAngleEnd");
				float angleEnd;
				if(plug.isNull())
				{
					angleEnd = 0.0f;
				}
				else
				{
					plug.getValue(angleEnd);
				}
				plug = jointFn.findPlug("unParticleRotationSpeed");
				float rotationSpeed;
				if(plug.isNull())
				{
					rotationSpeed = 0;
				}
				else
				{
					plug.getValue(rotationSpeed);
				}
				plug = jointFn.findPlug("unParticleRotationSpeedVar");
				float rotationSpeedVar;
				if(plug.isNull())
				{
					rotationSpeedVar = 0;
				}
				else
				{
					plug.getValue(rotationSpeedVar);
				}
				plug = jointFn.findPlug("unParticleEmitterWidth");
				float width;
				plug.getValue(width);
				plug = jointFn.findPlug("unParticleEmitterLength");
				float length;
				plug.getValue(length);
				plug = jointFn.findPlug("unParticleEmitterHeight");
				float height = 0.0f;
				if(!plug.isNull())
				{
					plug.getValue(height);
				}
				plug = jointFn.findPlug("unParticleBlendMode");
				short blendMode;
				plug.getValue(blendMode);
				plug = jointFn.findPlug("unParticleTextureFilename");

				MItDependencyGraph dgIt(plug, MFn::kFileTexture,
					MItDependencyGraph::kUpstream, 
					MItDependencyGraph::kBreadthFirst,
					MItDependencyGraph::kNodeLevel);

				dgIt.disablePruningOnFilter();

				MString textureName;
				if (!dgIt.isDone())
				{
					MObject textureNode = dgIt.thisNode();
					MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
					filenamePlug.getValue(textureName);
				}
				else
				{
					char str[256];
					sprintf(str,"%s particle system must has file-texture",newJoint.name.asChar());
					MessageBox(0,str,0,0);
				}
				plug = jointFn.findPlug("unParticleTextureRows");
				short rows;
				plug.getValue(rows);
				plug = jointFn.findPlug("unParticleTextureCols");
				short cols;
				plug.getValue(cols);
				plug = jointFn.findPlug("unParticleTextureChangeStyle");
				short changeStyle;
				if(plug.isNull())
				{
					//0 - 顺序
					//1 - 随机
					changeStyle = 0;
				}
				else
				{
					plug.getValue(changeStyle);
				}
				plug = jointFn.findPlug("unParticleTextureChangeInterval");
				short changeInterval;
				if(plug.isNull())
				{
					//默认30ms换一个
					changeInterval = 30;
				}
				else
				{
					plug.getValue(changeInterval);
				}
				plug = jointFn.findPlug("unParticleTailLength");
				float tailLength;
				plug.getValue(tailLength);
				plug = jointFn.findPlug("unParticleTimeMiddle");
				float timeMiddle;
				plug.getValue(timeMiddle);
				plug = jointFn.findPlug("unParticleColorStart");
				MObject object;
				plug.getValue(object);
				MFnNumericData dataS(object);
				float colorStart[3];
				dataS.getData(colorStart[0],colorStart[1],colorStart[2]);
				plug = jointFn.findPlug("unParticleColorMiddle");
				plug.getValue(object);
				MFnNumericData dataM(object);
				float colorMiddle[3];
				dataM.getData(colorMiddle[0],colorMiddle[1],colorMiddle[2]);
				plug = jointFn.findPlug("unParticleColorEnd");
				plug.getValue(object);
				MFnNumericData dataE(object);
				float colorEnd[3];
				dataE.getData(colorEnd[0],colorEnd[1],colorEnd[2]);
				plug = jointFn.findPlug("unParticleAlpha");
				plug.getValue(object);
				MFnNumericData dataAlpha(object);
				float alpha[3];
				dataAlpha.getData(alpha[0],alpha[1],alpha[2]);
				//Scale
				plug = jointFn.findPlug("unParticleScale");
				plug.getValue(object);
				MFnNumericData dataScale(object);
				float scale[3];
				dataScale.getData(scale[0],scale[1],scale[2]);
				//ScaleVar
				plug = jointFn.findPlug("unParticleScaleVar");
				float scaleVar[3] = {0.0f,0.0f,0.0f};
				if(!plug.isNull())
				{
					plug.getValue(object);
					MFnNumericData dataScaleVar(object);
					dataScaleVar.getData(scaleVar[0],scaleVar[1],scaleVar[2]);
				}
				//FixedSize
				plug = jointFn.findPlug("unParticleFixedSize");
				bool fixedSize = false;
				if(!plug.isNull())
				{
					plug.getValue(fixedSize);
				}
				//HeadLifeSpan
				plug = jointFn.findPlug("unParticleHeadLifeSpan");
				plug.getValue(object);
				MFnNumericData dataHeadLifeSpan(object);
				short headLifeSpan[3];
				dataHeadLifeSpan.getData(headLifeSpan[0],headLifeSpan[1],headLifeSpan[2]);
				plug = jointFn.findPlug("unParticleHeadDecay");
				plug.getValue(object);
				MFnNumericData dataHeadDecay(object);
				short headDecay[3];
				dataHeadDecay.getData(headDecay[0],headDecay[1],headDecay[2]);
				plug = jointFn.findPlug("unParticleTailLifeSpan");
				plug.getValue(object);
				MFnNumericData dataTailLifeSpan(object);
				short tailLifeSpan[3];
				dataTailLifeSpan.getData(tailLifeSpan[0],tailLifeSpan[1],tailLifeSpan[2]);
				plug = jointFn.findPlug("unParticleTailDecay");
				plug.getValue(object);
				MFnNumericData dataTailDecay(object);
				short tailDecay[3];
				dataTailDecay.getData(tailDecay[0],tailDecay[1],tailDecay[2]);
				plug = jointFn.findPlug("unParticleHead");
				bool head;
				plug.getValue(head);
				plug = jointFn.findPlug("unParticleTail");
				bool tail;
				plug.getValue(tail);
				plug = jointFn.findPlug("unParticleUnShaded");
				bool unshaded;
				plug.getValue(unshaded);
				plug = jointFn.findPlug("unParticleUnFogged");
				bool unfogged;
				plug.getValue(unfogged);
				plug = jointFn.findPlug("unParticleBlockByY0");
				bool blockByY0 = false;
				if(!plug.isNull())
					plug.getValue(blockByY0);

				newJoint.particle.visible = visible;
				newJoint.particle.speed = speed;
				newJoint.particle.variation = variation / 100.0f;
				newJoint.particle.coneAngle = coneAngle;
				newJoint.particle.gravity = gravity;
				newJoint.particle.explosiveForce = explosiveForce;
				newJoint.particle.life = life;
				newJoint.particle.lifeVar = lifeVar;
				newJoint.particle.emissionRate = emissionRate;
				newJoint.particle.initialNum = initialNum;
				newJoint.particle.limitNum = limitNum;
				newJoint.particle.attachToEmitter = attachToEmitter;
				newJoint.particle.moveWithEmitter = moveWithEmitter;
				newJoint.particle.forTheSword = forTheSword;
				newJoint.particle.forTheSwordInitialAngle = forTheSwordInitialAngle;
				newJoint.particle.wander = wander;
				newJoint.particle.wanderRadius = wanderRadius;
				newJoint.particle.wanderSpeed = wanderSpeed;
				newJoint.particle.aspectRatio = aspectRatio;
				newJoint.particle.initialAngleBegin = angleBegin;
				newJoint.particle.initialAngleEnd = angleEnd;
				newJoint.particle.rotationSpeed = rotationSpeed;
				newJoint.particle.rotationSpeedVar = rotationSpeedVar;
				newJoint.particle.width = width;
				newJoint.particle.length = length;
				newJoint.particle.height = height;
				newJoint.particle.blendMode = blendMode;
				newJoint.particle.textureFilename = textureName.asChar();
				newJoint.particle.textureRows = rows;
				newJoint.particle.textureCols = cols;
				newJoint.particle.changeStyle = changeStyle;
				newJoint.particle.changeInterval = changeInterval;
				newJoint.particle.tailLength = tailLength;
				newJoint.particle.timeMiddle = timeMiddle;
				newJoint.particle.colorStart[0] = colorStart[0];
				newJoint.particle.colorStart[1] = colorStart[1];
				newJoint.particle.colorStart[2] = colorStart[2];
				newJoint.particle.colorMiddle[0] = colorMiddle[0];
				newJoint.particle.colorMiddle[1] = colorMiddle[1];
				newJoint.particle.colorMiddle[2] = colorMiddle[2];
				newJoint.particle.colorEnd[0] = colorEnd[0];
				newJoint.particle.colorEnd[1] = colorEnd[1];
				newJoint.particle.colorEnd[2] = colorEnd[2];
				newJoint.particle.alpha[0] = alpha[0];
				newJoint.particle.alpha[1] = alpha[1];
				newJoint.particle.alpha[2] = alpha[2];
				newJoint.particle.scale[0] = scale[0];
				newJoint.particle.scale[1] = scale[1];
				newJoint.particle.scale[2] = scale[2];
				newJoint.particle.scaleVar[0] = scaleVar[0];
				newJoint.particle.scaleVar[1] = scaleVar[1];
				newJoint.particle.scaleVar[2] = scaleVar[2];
				newJoint.particle.fixedSize = fixedSize;
				newJoint.particle.headLifeSpan[0] = headLifeSpan[0];
				newJoint.particle.headLifeSpan[1] = headLifeSpan[1];
				newJoint.particle.headLifeSpan[2] = headLifeSpan[2];
				newJoint.particle.headDecay[0] = headDecay[0];
				newJoint.particle.headDecay[1] = headDecay[1];
				newJoint.particle.headDecay[2] = headDecay[2];
				newJoint.particle.tailLifeSpan[0] = tailLifeSpan[0];
				newJoint.particle.tailLifeSpan[1] = tailLifeSpan[1];
				newJoint.particle.tailLifeSpan[2] = tailLifeSpan[2];
				newJoint.particle.tailDecay[0] = tailDecay[0];
				newJoint.particle.tailDecay[1] = tailDecay[1];
				newJoint.particle.tailDecay[2] = tailDecay[2];
				newJoint.particle.head = head;
				newJoint.particle.tail = tail;
				newJoint.particle.unshaded = unshaded;
				newJoint.particle.unfogged = unfogged;
				newJoint.particle.blockByY0 = blockByY0;
			}
		}

		m_joints.push_back(newJoint);
		// Get pointer to newly created joint
		parentJoint = &newJoint;
	}
	// Load children joints
	for (i=0; i<jointDag.childCount();i++)
	{
		MObject child;
		child = jointDag.child(i);
		MDagPath childDag = jointDag;
		childDag.push(child);
		loadJoint(childDag,parentJoint);
	}

}
bool slopeShaderBehavior::shouldBeUsedFor( MObject &sourceNode, MObject &destinationNode,
										   MPlug &sourcePlug, MPlug &destinationPlug)
//
//	Description:
//		Overloaded function from MPxDragAndDropBehavior
//	this method will return true if it is going to handle the connection
//	between the two nodes given.
//
{
	bool result = false;

	if(sourceNode.hasFn(MFn::kLambert))
	{
		//if the source node was a lambert
		//than we will check the downstream connections to see 
		//if a slope shader is assigned to it.
		//
		MObject shaderNode;
		MFnDependencyNode src(sourceNode);
		MPlugArray connections;

		src.getConnections(connections);
		for(unsigned i = 0; i < connections.length(); i++)
		{
			//check the incoming connections to this plug
			//
			MPlugArray connectedPlugs;
			connections[i].connectedTo(connectedPlugs, true, false);
			for(unsigned j = 0; j < connectedPlugs.length(); j++)
			{
				//if the incoming node is a slope shader than 
				//set shaderNode equal to it and break out of the inner 
				//loop
				//
				if(MFnDependencyNode(connectedPlugs[j].node()).typeName() == "slopeShader")
				{
					shaderNode = connectedPlugs[j].node();
					break;
				}
			}

			//if the shaderNode is not null
			//than we have found a slopeShader
			//
			if(!shaderNode.isNull())
			{
				//if the destination node is a mesh than we will take
				//care of this connection so set the result to true
				//and break out of the outer loop
				//
				if(destinationNode.hasFn(MFn::kMesh))
					result = true;

				break;
			}
		}
	}
	if(MFnDependencyNode(sourceNode).typeName() == "slopeShader")
	//if the sourceNode is a slope shader than check what we
	//are dropping on to
	//
	{
		if(destinationNode.hasFn(MFn::kLambert))
			result = true;
		else if(destinationNode.hasFn(MFn::kMesh))
			result = true;
	}	

	return result;
}
MStatus slopeShaderBehavior::connectNodeToNode( MObject &sourceNode, MObject &destinationNode, bool force )
//
//	Description:
//		Overloaded function from MPxDragAndDropBehavior
//	this method will handle the connection between the slopeShader and the shader it is
//	assigned to as well as any meshes that it is assigned to. 
//
{
	MStatus result = MS::kFailure;
	MFnDependencyNode src(sourceNode);

	//if we are dragging from a lambert
	//we want to check what we are dragging
	//onto.
	if(sourceNode.hasFn(MFn::kLambert))
	{
		MObject shaderNode;
		MPlugArray connections;
		MObjectArray shaderNodes;
		shaderNodes.clear();

		//if the source node was a lambert
		//than we will check the downstream connections to see 
		//if a slope shader is assigned to it.
		//
		src.getConnections(connections);
		unsigned i;
		for(i = 0; i < connections.length(); i++)
		{
			//check the incoming connections to this plug
			//
			MPlugArray connectedPlugs;
			connections[i].connectedTo(connectedPlugs, true, false);
			for(unsigned j = 0; j < connectedPlugs.length(); j++)
			{
				//if the incoming node is a slope shader than 
				//append the node to the shaderNodes array
				//
				MObject currentnode = connectedPlugs[j].node();
				if(MFnDependencyNode(currentnode).typeName() == "slopeShader")
				{
					shaderNodes.append(currentnode);
				}
			}
		}

		//if we found a shading node
		//than check the destination node 
		//type to see if it is a mesh
		//
		if(shaderNodes.length() > 0)
		{
			MFnDependencyNode dest(destinationNode);
			if(destinationNode.hasFn(MFn::kMesh))
			{
				//if the node is a mesh than for each slopeShader
				//connect the worldMesh attribute to the dirtyShaderPlug
				//attribute to force an evaluation of the node when the mesh
				//changes
				//
				for(i = 0; i < shaderNodes.length(); i++)
				{
					MPlug srcPlug = dest.findPlug("worldMesh");
					MPlug destPlug = MFnDependencyNode(shaderNodes[i]).findPlug("dirtyShaderPlug");

					if(!srcPlug.isNull() && !destPlug.isNull())
					{
						MString cmd = "connectAttr -na ";
						cmd += srcPlug.name() + " ";
						cmd += destPlug.name();
						MGlobal::executeCommand(cmd);
					}
				}

				//get the shading engine so we can assign the shader
				//to the mesh after doing the connection
				//
				MObject shadingEngine = findShadingEngine(sourceNode);

				//if there is a valid shading engine than make
				//the connection
				//
				if(!shadingEngine.isNull())
				{
					MString cmd = "sets -edit -forceElement ";
					cmd += MFnDependencyNode(shadingEngine).name() + " ";
					cmd += MFnDagNode(destinationNode).partialPathName();
					result = MGlobal::executeCommand(cmd);
				}
			}
		}
	}
	else if(src.typeName() == "slopeShader")
	//if we are dragging from a slope shader
	//than we want to see what we are dragging onto
	//
	{
		if(destinationNode.hasFn(MFn::kMesh))
		{
			//if the user is dragging onto a mesh
			//than make the connection from the worldMesh
			//to the dirtyShader plug on the slopeShader
			//
			MFnDependencyNode dest(destinationNode);
			MPlug srcPlug = dest.findPlug("worldMesh");
			MPlug destPlug = src.findPlug("dirtyShaderPlug");
			if(!srcPlug.isNull() && !destPlug.isNull())
			{
				MString cmd = "connectAttr -na ";
				cmd += srcPlug.name() + " ";
				cmd += destPlug.name();
				result = MGlobal::executeCommand(cmd);
			}
		}
	}

	return result;
}
bool FxAttributeFiller::FillScript( DXCCEffectPath& parameter, MPlug& plug )

{
	MString plugName= Shader->EncodePlug(plug);

	MString MELPlugName= MFnDependencyNode(plug.node()).name() + MString(".") + plugName;

	switch(parameter.End->Description.Class)
	{
	case D3DXPC_SCALAR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
			{
				Script.AppendFormat("\tdxfxControlSliderCreate(\"float\", \"%s\", \"%f\", \"%f\", \"%d\", \"%s\");\n", SasUiLabel.asChar(), SasUiMin, SasUiMax, SasUiSteps, MELPlugName.asChar() );
			}
			else
			{
				Script.AppendFormat("\tdxfxControlScalarCreate(\"float\", \"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
		}
		break;
	case D3DXPC_VECTOR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "ColorPicker") 
				&& parameter.End->Description.Columns >= 3)
			{//COLOR
				Script.AppendFormat("\tdxfxControlColorCreate(\"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
			else
			{//VECTOR
				Script.AppendFormat("\tdxfxControlVectorCreate(\"float\", \"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
		}
		break;				
	case D3DXPC_MATRIX_ROWS:
	case D3DXPC_MATRIX_COLUMNS:
		{
			Script.AppendFormat("\tdxfxControlMatrixCreate(\"float\", \"%s\", \"%s\", %d, %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Rows, parameter.End->Description.Columns);
		}
		break;	
	case D3DXPC_OBJECT:
		switch(parameter.End->Description.Type)
		{
		case D3DXPT_STRING:
			{
				Script.AppendFormat("\tdxfxControlStringCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			{
				Script.AppendFormat("\tdxfxControlTextureCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		default:
			break;
		};
		break;
	default:
		break;
	};

	return true;
}
Beispiel #16
0
MStatus	parseShader(MObject &src, SXRShaderData& d)
{
	MStatus status;

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

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

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

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

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

	dgIt.disablePruningOnFilter();

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

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

	MStringArray rgFolders;

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

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

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

	return (MStatus::kSuccess);
}