Maya API How-To #08

Back · Previous · Next Maya

How do I assign polygon objects (and individual face components) to a Shading Group?

Given the MEL example:

string $select = `ls -sl`;
string $shadingGroup = "initialShadingGroup`;

// Assign to Shading Group
sets -e -forceElement $shadingGroup $select;

Here's a static member function that I created to allow me to do the same thing:

//********************************************************************
//    Function: MShadingGroup::AssignToShadingGroup   (static)
//
// Description: Assigns the provided DAG (and optional component) to 
//              the specified Shading Group.
//
//       Input: const MObject & shadingGroup: The Shading Group set.
//              const MDagPath & dagPath: The DAG.
//              const MObject & component: (optional) The DAG's
//                                           components.
//
//      Output: (MStatus): The usual.
//
//       Notes: dagPath must be the _shape_ node!
//
//********************************************************************
MStatus MShadingGroup::AssignToShadingGroup(
  const MObject & shadingGroup,
  const MDagPath & dagPath,
  const MObject & component )
{
  MStatus                     status;
  MFnSet                      fnSG( shadingGroup, &status );

  if ( fnSG.restriction() != MFnSet::kRenderableOnly )
    return MS::kFailure;

  status = fnSG.addMember( dagPath, component );
  if ( status != MS::kSuccess )
  {
    cerr << " ! MShadingGroup::assignToShadingGroup could not add Dag/Component to SG ! " << endl;
  }

  return status;
}

So, to duplicate the MEL commands above you would use something like this:

MSelectionList      selList;
MDagPath            dagPath;
MObject             component;
MObject             initialSG;

MGlobal::getSelectionListByName( MString( "initialShadingGroup" ), selList );
selList.getDependNode( 0, initialSG );

MGlobal::getActiveSelectionList( selList );

MItSelectionList    iter( selList );

for ( ; !iter.isDone(); iter.next() )
{
  iter.getDagPath( dagPath, component );
  dagPath.extendToShape();

  MShadingGroup::AssignToShadingGroup( initialSG, dagPath, component );
}

Related How-To's

Wednesday, October 10, 2001