Message 1 of 2
Problem with array attribute update
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
Hi, I have a problem with attribute update in MPxNode.
Here is the code below:
import sys
import maya.OpenMaya as om
import maya.api.OpenMaya as om2
import maya.api.OpenMayaUI as omui
import maya.api.OpenMayaRender as omr
def maya_useNewAPI():
pass
##########################################################
# csPoly Node.
##########################################################
class csPoly( om2.MPxNode ):
kPluginNodeName = 'csPoly'
kPluginNodeClassify = 'utility/general'
kPluginNodeId = om2.MTypeId( 0x86027 )
@staticmethod
def nodeCreator():
""" Creates an instance of our node class and delivers it to Maya as a pointer. """
return csPoly()
@staticmethod
def nodeInitializer():
tAttr = om2.MFnTypedAttribute()
nAttr = om2.MFnNumericAttribute()
cAttr = om2.MFnCompoundAttribute()
# Input connections
csPoly.inMesh = tAttr.create('inMesh', 'inm', om2.MFnMeshData.kMesh)
tAttr.readable = False
tAttr.keyable = False
csPoly.addAttribute(csPoly.inMesh)
csPoly.faceIDs = tAttr.create("faceIDs", "fid", om2.MFnData.kString)
csPoly.addAttribute(csPoly.faceIDs)
csPoly.xValue = nAttr.create( "xValue", "xv", om2.MFnNumericData.kFloat )
nAttr.keyable = False
csPoly.addAttribute( csPoly.xValue )
csPoly.yValue = nAttr.create( "yValue", "yv", om2.MFnNumericData.kFloat )
nAttr.keyable = False
csPoly.addAttribute( csPoly.yValue )
csPoly.zValue = nAttr.create( "zValue", "zv", om2.MFnNumericData.kFloat )
nAttr.keyable = False
csPoly.addAttribute( csPoly.zValue )
csPoly.controlPoints = nAttr.create( "controlPoints", "cp", csPoly.xValue, csPoly.yValue, csPoly.zValue )
nAttr.array = True
nAttr.keyable = False
csPoly.addAttribute( csPoly.controlPoints )
# Output connections
csPoly.outMesh = tAttr.create('outMesh', 'onm', om2.MFnMeshData.kMesh)
tAttr.writable = False
tAttr.storable = False
tAttr.keyable = False
csPoly.addAttribute(csPoly.outMesh)
csPoly.attributeAffects( csPoly.inMesh, csPoly.outMesh )
csPoly.attributeAffects( csPoly.controlPoints, csPoly.outMesh )
def __init__( self ):
om2.MPxNode.__init__( self )
self.collectFlag = 1
self.faceVertsId = None
def collectData( self ):
self.inFaceIDs = om2.MPlug( self.thisMObject(), self.faceIDs ).asString()
listStrIDs = self.inFaceIDs.split(',')
listIDs = [ int(x) for x in listStrIDs ]
self.mFnMeshsrc=om2.MFnMesh( om2.MPlug( self.thisMObject(), self.inMesh ).asMDataHandle().asMesh() )
# get all unique verts IDs fro specified polygon IDs
outVertConects = [ x for p in listIDs for x in list(self.mFnMeshSrc.getPolygonVertices(p)) ]
self.faceVertsId = set(outVertConects)
listSorted = list(set(outVertConects))
listSequental = range(len(listSorted))
self.outVertConectsOrdered = [ x + ( listSequental[listSorted.index(x)] - listSorted[listSorted.index(x)] ) for x in outVertConects]
self.outVertCounts = [ self.mFnMeshSrc.getPolygonVertices(p).__len__() for p in listIDs]
self.vValues = [ 0.0 ] * len(listIDs)
self.resultMesh = om2.MFnMeshData().create()
self.outFnMesh = om2.MFnMesh()
inMeshPointArray = self.mFnMeshSrc.getPoints(om2.MSpace.kWorld )
outPoints = [ inMeshPointArray[k] for k in self.faceVertsId ]
self.outFnMesh.create( outPoints, self.outVertCounts, self.outVertConectsOrdered, self.vValues, self.vValues, self.resultMesh)
def compute( self, plug, data ):
if plug == self.outMesh:
# get all MDataHandle values
pntsInArray = data.inputArrayValue( self.controlPoints )
outMeshPlug = data.outputValue( self.outMesh )
if self.collectFlag:
self.collectData()
self.collectFlag = 0
elif self.collectFlag == 0:
self.inMeshPoint = []
self.resultMeshData = om2.MFnMesh().setObject( self.resultMesh )
for p in xrange(pntsInArray.__len__()):
self.inMeshPoint.append(om2.MPoint(pntsInArray.jumpToLogicalElement(p).inputValue().asFloat3()))
#pntsInArray.jumpToLogicalElement(p).inputValue().setClean()
#pntsInArray.jumpToLogicalElement(p).inputValue().child( self.xValue ).setClean()
#pntsInArray.jumpToLogicalElement(p).inputValue().child( self.yValue ).setClean()
#pntsInArray.jumpToLogicalElement(p).inputValue().child( self.zValue ).setClean()
self.resultMeshData.setPoints( self.inMeshPoint, om2.MSpace.kObject )
outMeshPlug.setMObject(self.resultMesh)
data.setClean( self.outMesh )
controller_flag_short = '-c'
controller_flag_long = '-controller'
name = 'createCsPoly'
##########################################################
# createcsPoly Command.
##########################################################
class createcsPolyPoly(om2.MPxCommand):
# The command used to create csPoly node
def __init__(self):
om2.MPxCommand.__init__(self)
self.nameCsPoints = 'csPoints'
self.namecsPoly = 'csPoly'
self.csPoints = om2.MObject()
self.csPoly = om2.MObject()
self.dgmod = om2.MDGModifier()
self.dagmod = om2.MDagModifier()
self.connectedNodes = None
self.optimized = 1
def doIt(self, args):
sel = om2.MGlobal.getActiveSelectionList()
if sel.length() == 0:
return
argData = om2.MArgParser(self.syntax(), args)
dp = om2.MDagPath()
comp = om2.MObject()
dp, comp = sel.getComponent( 0 )
argData.getObjectStrings()
# Get the controller
if argData.isFlagSet(controller_flag_short):
self.controller = argData.flagArgumentString(controller_flag_short, 0)
selLength = sel.length()
if selLength == 2:
try:
mItVtx = om2.MItMeshPolygon( dp, comp )
parentController = sel.getDagPath( 1 )
parentCntMobject = sel.getDependNode(1)
mesh = dp.extendToShape(0)
except:
dp, comp = sel.getComponent( 1 )
mItVtx = om2.MItMeshPolygon( dp, comp )
parentController = sel.getDagPath( 0 )
parentCntMobject = sel.getDependNode(0)
mesh = dp.extendToShape(0)
else:
mItVtx = om2.MItMeshPolygon( dp, comp )
mesh = dp.extendToShape(0)
selList = om2.MSelectionList()
selList.add(self.controller)
parentController = selList.getDagPath(0)
parentCntMobject = selList.getDependNode(0)
idx = []
while not mItVtx.isDone():
point = mItVtx.index()
idx.append(int(point))
mItVtx.next(0)
componentList = list( sorted( set( idx ) ) )
if len( componentList ) > 0 and len( str( parentController ) ) > 0:
outMeshPlig = om2.MFnDependencyNode( mesh.node() ).findPlug( 'outMesh', 1 )
self.connectedNodes = [ x for x in outMeshPlig.connectedTo( 1, 1 ) if self.nameCsPoints in x.name() ]
csPointsNodes = [ x.node() for x in outMeshPlig.connectedTo( 1, 1 ) if 'csPoints' in x.name() ]
fnTrGeo = om2.MFnDependencyNode()
fnTrGeo_node = fnTrGeo.create("transformGeometry")
# Create csPoly node
self.csPoly = self.dgmod.createNode( om2.MTypeId(0x86027 ) )
fn_Poly_node = om2.MFnDependencyNode( self.csPoly )
fn_Poly_node.findPlug( 'faceIDs', 0 ).setString( (", ".join(str(i) for i in componentList) ) )
outVertConects = [ x for p in componentList for x in list(om2.MFnMesh(mesh.node()).getPolygonVertices(p)) ]
sortedOutVerts = list(set(outVertConects))
for o in xrange(len(sortedOutVerts)):
meshPnts = om2.MFnDependencyNode( mesh.node() ).findPlug( 'controlPoints', 0 ).elementByLogicalIndex(sortedOutVerts[o])
polyPoints = fn_Poly_node.findPlug( 'controlPoints', 0 ).elementByLogicalIndex(o)
self.dgmod.connect( meshPnts.child(0), polyPoints.child(0) )
self.dgmod.connect( meshPnts.child(1), polyPoints.child(1) )
self.dgmod.connect( meshPnts.child(2), polyPoints.child(2) )
self.dgmod.connect( outMeshPlig, fn_Poly_node.findPlug( 'inMesh', 0 ) )
objPolyShp = om2.MFnDagNode().create("mesh", 'polyCube', parentCntMobject)
self.dgmod.connect( fn_Poly_node.findPlug( 'outMesh', 0 ), om2.MFnDependencyNode(fnTrGeo_node).findPlug( 'inputGeometry', 0 ) )
self.dgmod.connect( om2.MFnDependencyNode(parentCntMobject).findPlug( 'worldInverseMatrix', 0 ).elementByLogicalIndex(0), om2.MFnDependencyNode(fnTrGeo_node).findPlug( 'transform', 0 ) )
self.dgmod.connect( om2.MFnDependencyNode(fnTrGeo_node).findPlug( 'outputGeometry', 0 ), om2.MFnDependencyNode(objPolyShp).findPlug( 'inMesh', 0 ) )
return self.redoIt()
def redoIt(self):
self.clearResult()
self.dgmod.doIt()
fn_csPoints_node = om2.MFnDependencyNode(self.csPoints)
if self.nameCsPoints and self.nameCsPoints != 'csPoints#':
pass
else:
name = fn_csPoints_node.name()
self.setResult(name)
fn_csPoly_node = om2.MFnDependencyNode(self.csPoly)
if self.namecsPoly and self.namecsPoly != 'csPoly#':
name2 = fn_csPoly_node.setName(self.namecsPoly)
else:
name2 = fn_csPoly_node.name()
self.setResult(name2)
def undoIt(self):
if not self.connectedNodes:
self.dgmod.undoIt()
self.dagmod.doIt()
def isUndoable(self):
return True
def hasSyntax(self):
return True
##########################################################
# Plug-in initialization.
##########################################################
def creator():
return createcsPolyPoly()
def syntaxCreator():
syntax = om2.MSyntax()
syntax.setObjectType( om2.MSyntax.kStringObjects )
syntax.addFlag( controller_flag_short, controller_flag_long, om2.MSyntax.kString )
return syntax
def initializePlugin( mobject ):
""" Initialize the plug-in """
mplugin = om2.MFnPlugin( mobject, "Alex Smirnov", "1.0", "Any" )
""" Initialize the createcsPoly command """
try:
mplugin.registerCommand( name, creator, syntaxCreator )
except:
sys.stderr.write( "Failed to register command: " + name )
raise
""" Initialize the csPoly node """
try:
mplugin.registerNode( csPoly.kPluginNodeName, csPoly.kPluginNodeId, csPoly.nodeCreator, csPoly.nodeInitializer )
except:
sys.stderr.write( "Failed to register node: " + csPoly.kPluginNodeName )
raise
def uninitializePlugin( mobject ):
""" Uninitialize the plug-in """
mplugin = om2.MFnPlugin( mobject )
""" Uninitialize the createcsPoly command """
try:
mplugin.deregisterCommand( name )
except:
sys.stderr.write( 'Failed to deregister command: ' + name )
""" Uninitialize the csPoly node """
try:
mplugin.deregisterNode( csPoly.kPluginNodeId )
except:
sys.stderr.write( 'Failed to deregister node: ' + csPoly.kPluginNodeName )
raiseThe main concept is that my custom node takes array attribute 'Control poinst', get the points position and replicate the part of the original mesh with predefined polygon IDs. But problem is that array atribute in my node update only once. However if I set AttributeAffects and setClean (commented lines) this attribute doesn't update. Can't figure out what I'm doing wrong.
Here is the quick start code that automatically setup node in the scene, just run the cone in script editor:
import maya.cmds as mc
mc.file( new=1, f=1 ) mc.unloadPlugin( 'createCsPoly' ) mc.loadPlugin( 'createCsPoly' ) sphereObj = mc.polySphere() mc.delete( sphereObj[0], ch=1 ) cir = mc.circle() mc.delete( cir[0], ch=1 ) mc.select( sphereObj[0] + '.f[10:50]', r=1 ) mc.select( cir[0], add=1 ) mc.createCsPoly()