Search code examples
c++mayamaya-api

Maya API C++: get material from poly


I am writing a plugin for Maya 2018 using Maya API C ++. I have already successfully obtained a mesh, and created an iterator to iterate through all the polygons:

 ...
 MFnMesh fnMesh(mdagPath, &stat); 
 if (MS::kSuccess != stat)
 {
    // error get mesh
    return MS::kFailure;
 }
 MItMeshPolygon polyIter(mdagPath, mComponent, &stat);
 if (MS::kSuccess != stat) 
 {
    // error create iterator
    return MS::kFailure;
 }
 ...

I successfully get vertices, normals, texture coordinates. But how to get the material that is superimposed on the current polygon? And along with the material texture.


Solution

  • I get all materials, then i get all poly in current material:

        MStatus stat = MStatus::kSuccess;
        MSpace::Space space = MSpace::kWorld; 
        MFnSet fnSet(set, &stat); 
        if (stat == MS::kFailure) 
        {
            MStreamUtils::stdErrorStream() << "ERROR: MFnSet::MFnSet\n";
            return MStatus::kNotImplemented;
        }
        MItMeshPolygon polyIter(mdagPath, comp, &stat); // iterator on vertex
        if ((stat == MS::kFailure)) 
        {
            MStreamUtils::stdErrorStream() << "ERROR: Can't create poly iterator!\n";
            return MStatus::kNotImplemented;
        }
        MFnDependencyNode fnNode(set); 
        MPlug shaderPlug = fnNode.findPlug("surfaceShader");
        MPlugArray connectedPlugs;
        if (shaderPlug.isNull())
        {
            MStreamUtils::stdErrorStream() << "ERROR: Can't find material!\n";
            return MStatus::kNotImplemented;
        }
        shaderPlug.connectedTo(connectedPlugs, true, false);
        MFnDependencyNode fnDN(connectedPlugs[0].node());
    
        MItDependencyGraph dgIt(shaderPlug, MFn::kFileTexture, 
            MItDependencyGraph::kUpstream,
            MItDependencyGraph::kBreadthFirst,
            MItDependencyGraph::kNodeLevel,
            &stat);
        if (stat == MS::kFailure)
        {
            MStreamUtils::stdErrorStream() << "ERROR: Can't load graph textures\n";
            return MStatus::kNotImplemented;
        }
        dgIt.disablePruningOnFilter();
        if (dgIt.isDone()) 
        {
            MStreamUtils::stdErrorStream() << "Warning: Material " << fnDN.name().asChar() << " not textured\n";
            //return MStatus::kNotImplemented;
        }
    
        // no need, here we get the texture
        MObject textureNode = dgIt.thisNode();
        MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
        MString textureName; // name texture + path
        filenamePlug.getValue(textureName);
        (; !polyIter.isDone(); polyIter.next())
        {
            // here get poly and perform actions on it
        }