MEL How-To #91

Back · Previous · Next Maya

How do I determine which Shading Group is associated with a Material?

To determine which Material is associated to a Shading Group, get a list of all connection from the Material's ".outColor" attribute. Iterate this array to find all Shading Groups. The ‘nodeType’ command will identify a Shading Group with the string "shadingEngine".

// ////////////////////////////////////////////////////////////////////
//  getSGFromMaterial
//
// Description: Returns the Shading Group set whose '.surfaceShader'
//  attribute is being fed by the specified Material.
//
//  Returns an array for all Shading Groups using the Material.

global proc string[] getSGFromMaterial( string $material )
{
  string $SG[];

  // First, assert that $material is a Material.
  // (Returns a string array, unfortunately, so requires variable.)
  string $class[] = getClassification( `nodeType $material` );

  if ( $class[0] == "shader/surface" )
  {
    // Assert that there is a connection from the Material's .outColor
    if ( `connectionInfo -is ( $material + ".outColor" )` )
    {
      // There may be more than one connection...
      string $dests[] = `connectionInfo -dfs ( $material + ".outColor" )`;
      for ( $dest in $dests )
      {
        // Iterate through connections and identify ShadingGroup sets.
        if ( "shadingEngine" == `nodeType $dest` )
        {
          $SG[`size $SG`] = rootNode( $dest );
          break;
        }
      }
    }
  }

  return $SG;
}

Note: The following ‘rootNode()’ procedure is required by the procedures above.

// //////////////////////////////////////////////////////////////
//  rootNode
//
// Description: Strips the dot-suffix of the specified string.
//  e.g. "object.attribute" is returned as "object"

proc string rootNode( string $object )
{
  string $buffer[];
  tokenize $object "." $buffer;
  return $buffer[0];
}

Related How-To's

Friday, September 14, 2001