def getShaveAttrs(self,filePath): output = open(filePath,'wb') attrDict = dict() shaveAttrs = cmds.listAttr(self.shaveNode,se = True) valueSetAttrs = [] connectedAttrs = [] for attr in shaveAttrs: try: if cmds.connectionInfo('%s.%s'%(self.shaveNode,attr),id = True): connection = cmds.connectionInfo('%s.%s'%(self.shaveNode,attr),sfd = True) connectedAttrs.append([connection,attr]) else: attrValue = cmds.getAttr('%s.%s'%(self.shaveNode,attr)) print attr,attrValue valueSetAttrs.append([attr,attrValue]) except (RuntimeError,ValueError): pass attrDict['valueSet'] = valueSetAttrs attrDict['connected'] = connectedAttrs pickle.dump(attrDict,output) output.close()
def attachCurves(name, identifier, jobInfo, isConstant=False): cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._attach.attachCurves") if cmds.objExists( name ): curObj = cmds.connectionInfo(name+".visibility", sfd=True) if curObj and cmds.objectType(curObj) == "ExocortexAlembicCurvesDeform": attachTimeAndFile(curObj, jobInfo, isConstant) return # create deformer, and attach time and file newDform = cmds.deformer(name, type="ExocortexAlembicCurvesDeform")[0] cmds.setAttr(newDform+".identifier", identifier, type="string") attachTimeAndFile(newDform, jobInfo, isConstant) # get curObj new "output" attribute connection if cmds.objExists( curObj ): if curObj != None and cmds.objectType(curObj) != "ExocortexAlembicCurves": originalCur = cmds.connectionInfo(curObj+".output", sfd=True).split('.')[0] cmds.delete(curObj) curObj = cmds.createNode("ExocortexAlembicCurves") attachTimeAndFile(curObj, jobInfo, isConstant) cmds.connectAttr(curObj+".outCurve", originalCur+".create") cmds.connectAttr(jobInfo.filenode+".outFileName", curObj+".fileName") cmds.setAttr(curObj+".identifier", identifier, type="string") cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._attach.attachCurves") pass
def constrainJoints(self): # Rivet & constrain joints to the ArcCtrl surface rivetArgs=[] cjLen=1 for j in self.jointHierarchy[1:]: if self.spread: cj=removeAll\ ( self.jointHierarchy[1:], iterable(mc.listRelatives(j,c=True,type='transform')) ) rivetArgs.extend(cj) cjLen=len(cj)+1 rivetArgs.append(j) skipRotate=[] for sr in range(1,cjLen+1): skipRotate.append(-sr) rivetArgs.append(self.ArcCtrl.outputSurface) self.rivet=Rivet(rivetArgs,constraint=True,skipRotate=skipRotate) if not\ ( mc.connectionInfo(self.jointHierarchy[-1]+'.r',id=True) or mc.connectionInfo(self.jointHierarchy[-1]+'.rx',id=True) or mc.connectionInfo(self.jointHierarchy[-1]+'.ry',id=True) or mc.connectionInfo(self.jointHierarchy[-1]+'.rz',id=True) ): mc.parentConstraint(self.ArcCtrl.handles[-1],self.jointHierarchy[-1],st=('x','y','z'),mo=True) if self.spread or self.curl: for j in cj: mc.parentConstraint(self.ArcCtrl.handles[-1],j,st=('x','y','z'),mo=True)
def getObjMaterials(): global remapAndLuminaceNodes shadingType = ['blinn', 'phong', 'RedshiftArchitectural', 'aiStandard'] displacementShading = ['RedshiftDisplacement', 'displacementShader'] duplicateMaterials = list() selObjsList = cmds.ls(sl = 1, tr = 1) if not selObjsList: assert 'No object is selected!' obj = selObjsList[0] duplicateNodes = list() cmds.select(obj, r = 1) cmds.hyperShade(smn = 1) selObjsDuplicateMaterials = cmds.duplicate(un = 1) for item in selObjsDuplicateMaterials: dupliMater = cmds.rename(item, '%s_duplicate'%(item)) duplicateNodes.append(dupliMater) for item in duplicateNodes: if cmds.nodeType(item) in shadingType: duplicateShading = cmds.sets(r = 1, nss = 1, em = 1, n = '%s_SG'%item) cmds.connectAttr('%s.outColor'%item, '%s.surfaceShader'%duplicateShading, f = 1) duplicateMaterials.append(item) elif cmds.nodeType(item) == 'RedshiftDisplacement': conInfo = cmds.connectionInfo('%s.displacementShader'%duplicateShading, sfd = 1) if not conInfo: cmds.connectAttr('%s.out'%item, '%s.displacementShader'%duplicateShading, f = 1) elif cmds.nodeType(item) == 'displacementShader': conInfo = cmds.connectionInfo('%s.displacementShader'%duplicateShading, sfd = 1) if not conInfo: cmds.connectAttr('%s.displacement'%item, '%s.displacementShader'%duplicateShading, f = 1) cmds.sets(obj, e = 1, fe = duplicateShading) cmds.select(selObjsList, r = 1) return list(set(duplicateMaterials))
def channelbox_command_break(box, menuItem, key, *args): with sysCmd.Undo(): for plug in channelBox_SelectedPlugs(box): if cmds.connectionInfo(plug, isDestination=1): destination = cmds.connectionInfo(plug, getExactDestination=1) # when delete source conn from character, must remove from character set or set becomes inconsistent src_conn = cmds.listConnections(destination, s=1, d=0, type="character") if src_conn: warn_msg = "Removed \'^1s\' from character \'^2s\'." cmds.warning(cmds.format(warn_msg, s=(destination, src_conn[0]))) cmds.character(destination, e=1, rm=src_conn[0]) # is tracking edits? import maya.api.OpenMaya as om obj = om.MSelectionList().add(destination).getDependNode(0) depend_fn = om.MFnDependencyNode(obj) tracking_edits = depend_fn.isTrackingEdits() del obj del depend_fn if tracking_edits: src = cmds.connectionInfo(destination, sourceFromDestination=1) cmds.disconnectAttr(src, destination) else: cmds.delete(destination, icn=1)
def isConnected (attr, node = None, incoming = True, outgoing = True): ''' Check if attribute is connected .. python :: isConnected ("testMe.translateX") # Result: False @param attr: Attribute name or path @type attr: *str* @param node: Attribute parent node @type node: *str* @return: Return status @rtype: *bool* ''' # Resolve attribute attrPath = resolveArgs (attr, node) [0] # Check if attribute is connected if outgoing and cmds.connectionInfo (attrPath, isSource = True): return True elif incoming and cmds.connectionInfo (attrPath, isDestination = True): return True else: return False
def channelbox_command_selectConnection(box, menuItem, key, *args): with sysCmd.Undo(): for plug in channelBox_SelectedPlugs(box): if cmds.connectionInfo(plug, isDestination=1): destination = cmds.connectionInfo(plug, getExactDestination=1) dest_input = cmds.listConnections(destination) cmds.select(dest_input[0], r=1)
def createDistanceNodeBetweenObjects (obj1,obj2): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Creates a distance node between objects ARGUMENTS: obj1(string) obj2(string) RETURNS: none >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ """ Creates a distance node between objects """ pos1 = returnWorldSpacePosition (obj1) pos2 = returnWorldSpacePosition (obj2) tmp = mc.distanceDimension( sp=pos1, ep=pos2 ) distBuffer = mc.listRelatives ( [tmp], p=True) distanceObj = mc.rename (distBuffer, (obj1+'_to_'+obj2+'_distMeas') ) #return the stupid locators it makes so we can connect our own stuff distanceStartPoint = (distanceObj+'Shape.startPoint') distanceEndPoint = (distanceObj+'Shape.endPoint') locAttr1connection = (mc.connectionInfo (distanceStartPoint,sourceFromDestination=True)) locAttr2connection = (mc.connectionInfo (distanceEndPoint,sourceFromDestination=True)) locAttr1Stripped = '.'.join(locAttr1connection.split('.')[0:-1]) locAttr2Stripped = '.'.join(locAttr2connection.split('.')[0:-1]) loc1Buffer = (mc.listRelatives (locAttr1Stripped,parent=True)) loc2Buffer = (mc.listRelatives (locAttr2Stripped,parent=True)) #distObj1 = mc.rename (loc1Buffer, (obj1+'_distLoc') ) #distObj2 = mc.rename (loc2Buffer, (obj2+'_distLoc') ) return distanceObj
def on_actionLoadSourceControl_triggered(self, clicked=None): if clicked == None:return selectOBJ = mc.ls(sl=True) if len(selectOBJ) == 0:return self.sourceControlFLD.setText(selectOBJ[0]) KeyableAttr = mc.listAttr(selectOBJ[0], k=True) del self.sourceAtrLst[:] del self.targentAtrLst[:] # loop Attributes.. for Attr in KeyableAttr: SDKeys = mc.connectionInfo('%s.%s'%(selectOBJ[0], Attr), dfs=True) # loop driven Attributes.. for key in SDKeys: if mc.nodeType(key) == 'unitConversion': keyNode = mc.connectionInfo('%s.output'%key.split('.')[0], dfs=True)[0].split('.')[0] elif mc.nodeType(key) not in ('animCurve','animCurveTA', 'animCurveTL', 'animCurveTT','animCurveTU','animCurveUA','animCurveUL','animCurveUT','animCurveUU'): continue else: keyNode = key.split('.')[0] DriverValues = mc.keyframe(keyNode, q=True, fc=True) DrivenValues = mc.keyframe(keyNode, q=True, vc=True) DriverAttribute = mc.connectionInfo('%s.output'%keyNode, dfs=True)[0] # if more than one Drivers, from add node get the attribute.. if DriverAttribute.endswith(']'): DriverAttribute = mc.connectionInfo('%s.output'%(DriverAttribute.split('.')[0]), dfs=True)[0] self.sourceAtrLst.append(['%s.%s'%(selectOBJ[0], Attr), DriverAttribute, DriverValues, DrivenValues]) self.on_actionInputSearchReplace_triggered()
def getReferences(loadState=False, nodesInRef=False): """Returns a dictionary with the namespace as keys and a list containing the proxyManager if there is one, the refnode, and its load state """ result = dict() proxyManagers = set() references = cmds.file(query=True, reference=True) for i in references: refNode = cmds.referenceQuery(i, referenceNode=True) connection = cmds.connectionInfo(refNode + '.proxyMsg', sourceFromDestination=True) if connection: proxyManagers.update([connection.split('.')[0]]) else: namespace = cmds.file(i, parentNamespace=True, query=True)[0] + ':' + cmds.file(i, namespace=True, query=True) namespace = cmds.file(i, namespace=True, query=True) # namespace = ('' if namespace.startswith(':') else ':') + namespace result[i] = {'namespace': namespace, 'proxyManager': None, 'refNode': refNode} for proxy in proxyManagers: connection = cmds.connectionInfo(proxy + '.activeProxy', destinationFromSource=True) activeProxy = cmds.listConnections(connection, source=False)[0] namespace = cmds.referenceQuery(activeProxy, parentNamespace=True)[0] refNode = cmds.referenceQuery(activeProxy, referenceNode=True) result[namespace] = {'proxyManager': proxy, 'refNode': refNode} for ref in result: if loadState: isLoaded = cmds.referenceQuery(result[ref]['refNode'], isLoaded=True) result[ref]['isLoaded'] = isLoaded if nodesInRef: nodes = cmds.referenceQuery(result[ref]['refNode'], nodes=True, dagPath=True) result[ref]['nodesInRef'] = nodes return result
def connect_zDepth(*args): r_cam = cmds.textScrollList('r_cam', q=True, si=True) if not(type(r_cam) == types.NoneType): for rc in r_cam: x = cmds.listRelatives(rc, shapes=True) wh = "vrayRE_Z_depth.vray_depthWhite" bl = "vrayRE_Z_depth.vray_depthBlack" bMin = cmds.connectionInfo(wh ,id=True) bMax = cmds.connectionInfo(bl ,id=True) cMin = cmds.connectionInfo(wh ,sfd=True) cMax = cmds.connectionInfo(bl ,sfd=True) if bMin : cmds.disconnectAttr(cMin, wh) cmds.connectAttr( x[0]+".nearClipPlane", wh ) else : cmds.connectAttr( x[0]+".nearClipPlane", wh ) if bMax : cmds.disconnectAttr(cMax, bl) cmds.connectAttr( x[0]+".farClipPlane" , bl ) else : cmds.connectAttr( x[0]+".farClipPlane" , bl )
def getObjMaterials(): global remapAndLuminaceNodes shadingType = ["blinn", "phong", "RedshiftArchitectural", "aiStandard"] displacementShading = ["RedshiftDisplacement", "displacementShader"] duplicateMaterials = list() selObjsList = cmds.ls(sl=1, tr=1) if not selObjsList: assert "No object is selected!" for obj in selObjsList: duplicateNodes = list() cmds.select(obj, r=1) cmds.hyperShade(smn=1) selObjsDuplicateMaterials = cmds.duplicate(un=1) for item in selObjsDuplicateMaterials: dupliMater = cmds.rename(item, "%s_duplicate" % (item)) duplicateNodes.append(dupliMater) for item in duplicateNodes: if cmds.nodeType(item) in shadingType: duplicateShading = cmds.sets(r=1, nss=1, em=1, n="%s_SG" % item) cmds.connectAttr("%s.outColor" % item, "%s.surfaceShader" % duplicateShading, f=1) duplicateMaterials.append(item) elif cmds.nodeType(item) == "RedshiftDisplacement": conInfo = cmds.connectionInfo("%s.displacementShader" % duplicateShading, sfd=1) if not conInfo: cmds.connectAttr("%s.out" % item, "%s.displacementShader" % duplicateShading, f=1) elif cmds.nodeType(item) == "displacementShader": conInfo = cmds.connectionInfo("%s.displacementShader" % duplicateShading, sfd=1) if not conInfo: cmds.connectAttr("%s.displacement" % item, "%s.displacementShader" % duplicateShading, f=1) cmds.sets(obj, e=1, fe=duplicateShading) cmds.select(selObjsList, r=1) return list(set(duplicateMaterials))
def connect_alpha(self, newNode, mayaMat): alpha_attr1 = '.transparency' alpha_attr2 = '.matteOpacity' # may use this in the future if cmds.connectionInfo(mayaMat + "%s" % alpha_attr1, isDestination=1): plug_source = cmds.connectionInfo(mayaMat + "%s" % alpha_attr1, sourceFromDestination=1) node_source = plug_source.split(".")[0] node_outAlpha = node_source + '.outAlpha' node_outTransparency = node_source + '.outTransparency' for i in self.aiTransparencyList: if ".opacity" in i: print 'opacity mode' try: cmds.connectAttr(node_outTransparency, newNode + i) except: cmds.connectAttr(node_outAlpha, newNode + i) if i == ".Kt" and self.useaiTransparency is True: cmds.connectAttr(node_outTransparency, newNode + i) print "alpha connect ok!" return True else: return False
def getReferenceFromNamespace(ns, parentNS=None): """ Get the reference node associated with the specified namespace @param ns: Namespace to query reference node from @type ns: str @param parentNS: Parent namespace to query reference nodes from @type parentNS: str or None """ # Check Namespace if ns.endswith(":"): ns = ns[:-1] if not cmds.namespace(ex=ns): raise Exception('Namespace "' + ns + '" does not exist!') # Check Parent Namespace if parentNS: parentNS += ":" else: parentNS = "" # Check Each Reference for refNode in listReferences(parentNS): # Get Reference Namespace try: refNS = cmds.referenceQuery(refNode, namespace=True) except: # print('Unable to get namespace from reference "'+refNode+'"!') continue # Strip Leading ":" if refNS.startswith(":"): refNS = refNS[1:] # Check Namespace Match if refNS == parentNS + ns: # Check Proxy Manager Connections if cmds.attributeQuery("proxyMsg", n=refNode, ex=True): proxyManager = ( cmds.ls(cmds.listConnections(refNode + ".proxyMsg", s=True, d=False) or [], type="proxyManager") or [] ) if proxyManager: # Check Active Proxy activeProxyPlug = cmds.connectionInfo(proxyManager[0] + ".activeProxy", destinationFromSource=True)[ 0 ] activeProxyInfo = cmds.connectionInfo(activeProxyPlug, destinationFromSource=True) if not activeProxyInfo: raise Exception('Error getting active reference from proxy manager "' + proxyManager[0] + '"!') return cmds.ls(activeProxyInfo[0], o=True)[0] # Return Reference return refNode # No Reference Found from Namespace - Print Msg print ("Unable to determine reference from namespace: " + ns) return ""
def listNodeConnections(*args,**keywords): s=True d=True sn=False sel=[] if len(args)==0: sel=mc.ls(sl=True) for a in args: if isIterable(a): sel.extend(a) else: sel.append(a) for k in keywords: if k=='s' or k=='source': s=keywords[k] if k=='d' or k=='destination': d=keywords[k] if k=='sn' or k=='shortName': sn=keywords[k] elif k in locals(): exec(k+'=keywords[k]') connections=[] for conn in removeDuplicates(mc.listConnections(sel[0],s=s,d=d,p=True)): if len(sel)==1 or mc.ls(conn,o=True)[0]==sel[1]: if mc.connectionInfo(conn,isSource=True): for dfs in mc.connectionInfo(conn,dfs=True): if mc.ls(dfs,o=True)[0]==sel[0]: if sn: connections.append\ ( [ mc.ls(conn,o=True)[0]+'.'+mc.listAttr(conn,sn=True)[0], mc.ls(dfs,o=True)[0]+'.'+mc.listAttr(dfs,sn=True)[0] ] ) else: connections.append([conn,dfs]) if mc.connectionInfo(conn,id=True): sfd=mc.connectionInfo(conn,sfd=True) if mc.ls(sfd,o=True)[0]==sel[0]: if sn: connections.append\ ( [ mc.ls(sfd,o=True)[0]+'.'+mc.listAttr(sfd,sn=True)[0], mc.ls(conn,o=True)[0]+'.'+mc.listAttr(conn,sn=True)[0] ] ) else: connections.append([sfd,conn]) return removeDuplicates(connections)
def breakCncts(attr, s=1, d=1): if s: n=MC.connectionInfo(attr, sfd=1) if n: MC.disconnectAttr(n, attr) if d: for n in MC.connectionInfo(attr, dfs=1): MC.disconnectAttr(attr, n)
def attachedGeo(self, node): shapez = {} sgs = m.connectionInfo("%s.outColor" % node, dfs=True) for sg in sgs: sg = sg.split(".")[0] for index in m.getAttr("%s.dagSetMembers" % sg, mi=True): shape = m.connectionInfo("%s.dagSetMembers[%s]" % (sg, index), sfd=True).split(".")[0] shapez[shape] = m.listRelatives(shape, p=True) return shapez
def has_shader_connected(node_name): # check that the shape has a shader connected if not cmds.listConnections(node_name, t='shadingEngine'): return False shadingEngine = cmds.listConnections(node_name, t='shadingEngine')[0] if not cmds.connectionInfo(shadingEngine + '.surfaceShader', sourceFromDestination=True).split('.')[0]: return False return cmds.connectionInfo(shadingEngine + '.surfaceShader', sourceFromDestination=True).split('.')[0]
def _isError(shader): if not mc.connectionInfo(shader+'.standard_bump', id=True): for a in ('.standard_bumpX', '.standard_bumpY', '.standard_bumpZ'): if mc.getAttr(shader+a) != 0: return False if not mc.connectionInfo(shader+'.overall_bump', id=True): for a in ('.overall_bumpX', '.overall_bumpY', '.overall_bumpZ'): if mc.getAttr(shader+a) != 0: return False return True
def attachTimeAndFile(node, jobInfo, isConstant=False): connAttr = cmds.connectionInfo(node+".inTime", sfd=True) if connAttr == "" and not isConstant: cmds.connectAttr(jobInfo.timeCtrl+".outTime", node+".inTime") node = node + ".fileName" # compute once, used 2-3 times connAttr = cmds.connectionInfo(node, sfd=True) if connAttr != None and connAttr != "": cmds.disconnectAttr(connAttr, node) cmds.connectAttr(jobInfo.filenode+".outFileName", node) pass
def duplicateShape(*args,**keywords): asHistory=False shortNames=\ { 'ah':'asHistory' } for k in keywords: if k in locals(): exec(k+'=keywords[k]') elif k in shortNames: exec(shortNames[k]+'=keywords[k]') if len(args)==0: args=mc.ls(sl=True) sel=[] for a in args: sel.extend(iterable(a)) for i in range(0,len(sel)): sel[i]=shape(sel[i]) returnVal=[] for sh in sel: tr=mc.listRelatives(sh,p=True)[0] trDup=mc.duplicate(tr,rc=True)[0] shDup=mc.listRelatives(trDup,s=True)[mc.listRelatives(tr,s=True).index(sh)] mc.parent(shDup,tr,s=True,add=True) mc.delete(trDup) returnVal.append(shDup) if asHistory: hist='' plugIn='' plugOut='' if mc.nodeType(sh)=='mesh': plugIn='.inMesh' plugOut='.outMesh' if mc.connectionInfo(sh+'.inMesh',id=True): hist=mc.connectionInfo(sh+'.inMesh',sfd=True) elif 'nurbs' in mc.nodeType(sh): plugIn='.create' plugOut='.local' if mc.connectionInfo(sh+'.create',id=True): hist=mc.connectionInfo(sh+'.create',sfd=True) if mc.objExists(sh+plugIn) and mc.objExists(shDup+plugIn): if mc.objExists(hist): mc.connectAttr(hist,shDup+plugIn,f=True) mc.connectAttr(shDup+plugOut,sh+plugIn,f=True) mc.setAttr(shDup+'.io',True) if len(returnVal)==1: return returnVal[0] elif len(returnVal)==0: return '' else: return returnVal
def getDrivenKeys(obj): keys = mc.listConnections(obj, t="animCurve") or [] for unc in mc.listConnections(obj, t="unitConversion") or []: keys.extend(mc.listConnections(unc, t="animCurve") or list()) for k in keys: driver = mc.connectionInfo("%s.input" % k, sfd=True) driven = mc.connectionInfo("%s.output" % k, dfs=True) if not driver or not driven: continue if mc.nodeType(driver) == "unitConversion": driver = mc.connectionInfo("%s.input" % driver.split(".")[0], sfd=True) yield driver, driven[0]
def getConnected(self, node=None): if node: pass else: return False connectList = [] upList = [] downList = [] sourceList = [] destList = [] connections = cmds.listConnections(node, p=True) print connections if connections: for plug in connections: if cmds.connectionInfo(plug, isDestination=1): connectList.append(plug) upList.append(plug) if cmds.connectionInfo(plug, isSource=1): connectList.append(plug) downList.append(plug) for plug in upList: source_plug = cmds.connectionInfo(plug, sourceFromDestination=1) sourceList.append([source_plug, plug]) for plug in downList: dest_plug = cmds.connectionInfo(plug, destinationFromSource=1) destList.append([plug, dest_plug]) connectDict = {"up": upList, "down": downList, "source": sourceList, "destination": destList, "all": connectList} return connectDict
def getConnected(self, obj, attr, indexValue=0): attrName = '{}.{}'.format(obj, attr) attrNameIndex = '{}.{}[{}]'.format(obj, attr, indexValue) if cmds.attributeQuery(attr, node=obj, ex=True): if cmds.attributeQuery(attr, node=obj, m=True): query = cmds.listConnections(attrNameIndex) return query[0] if query else None elif cmds.connectionInfo(attrName, id=True): query = cmds.listConnections( cmds.connectionInfo(attrName, ged=True)) return query[0] if query else None else: query = cmds.listConnections(attrName) return query[0] if query else None else: return None
def getNextFreeMultiIndex(nodeattr, start=0, max=10000000): """Get the next available index, usefull for indexMatters(True) nodes like the plusMinusAverage.""" for i in xrange(start, max): con = cmds.connectionInfo(nodeattr + "[{}]".format(i), sourceFromDestination=True) if not con: return i return None
def getSelectedHairSystems(): out = cmds.ls(selection=True, dagObjects=True, typ='hairSystem') numOut = len(out) pfxHair = cmds.ls(selection=True, dagObjects=True, typ='pfxHair') numPfxHair = len(pfxHair) for pfx in pfxHair: hairSys = sourceNodeNameFromConnection('{}.renderHairs'.format(pfx)) if hairSys: numOut = appendUniqueEntry(hairSys, out) hCurves = getSelectedHairCurves() for curve in hCurves: hairSys = '' con = cmds.connectionInfo('{}.outHair'.format(curve), destinationFromSource=True) if con: node = kmmu.plugNode(con[0]) nType = cmds.nodeType() if nType == 'hairSystem': hairSys = node if hairSys: numOut = appendUniqueEntry(hairSys, out) return out
def wireToSkincluster(): curveTransform = cmds.ls(sl = True)[0] curveShape = cmds.listRelatives(curveTransform, type = 'shape')[0] curveConnection = cmds.connectionInfo('%s.worldSpace[0]'%curveShape,dfs = True)[0] wire = curveConnection.split('.')[0] SkinningLib.extrapFromWire(wire)
def connectedIndices(self): out = [] for index in self.indices(): if cmds.connectionInfo(self.inAttr(index), isExactDestination=True): out.append(index) return out
def doIt( self, argList ): """Creates forest instances from a scene object.""" argsLen = argList.length() if argsLen >= 4: SpeedTreeForest = argList.asString(0) partCloudShape = argList.asString(1) tree = argList.asString(2) setIndex = argList.asInt(3) if argsLen == 5: instancerPrefix = argList.asString(4) else: instancerPrefix = partCloudShape[:-5] instancerName = instancerPrefix + '_Instancer' treeShape = '' partInstancer = '' SpeedTreeAsset = '' treePlug = mc.connectionInfo( SpeedTreeForest + '.forestObjects[' + str( setIndex ) + ']', sfd=1 ) if tree != '': if mc.nodeType( tree ) != None: treeShapes = mc.listRelatives( tree, s=1 ) if treeShapes != None and len( treeShapes ) > 0: treeShape = treeShapes[0] supportedTreeTypes = [ 'transform', 'mesh', 'nurbsSurface', 'nurbsCurve', 'subdiv' ] assignForestObject = False #remove existing object if there is one cons = mc.listConnections( partCloudShape ) if ( cons != None and len( cons ) > 0 and mc.objExists( cons[0] ) and mc.nodeType( cons[0] ) == 'instancer' and mc.nodeType( treeShape ) != 'particle' ): if treePlug != '': oldObj = mel.eval( "instancer -index 0 -q -obj " + cons[0] ) if oldObj != '': mc.particleInstancer( partCloudShape, n=cons[0], edit=True, obj=oldObj, rm=True ) partInstancer = mc.particleInstancer( partCloudShape, n=cons[0], edit=True, obj=tree, a=True ) assignForestObject = True elif mc.nodeType( tree ) in supportedTreeTypes and mc.nodeType( treeShape ) != 'particle': partInstancer = mc.particleInstancer( partCloudShape, n=instancerName, obj=tree, a=True, lod='geometry', p='position', r='rotationPP', sc='UserVector1PP' ) useBBs = mc.getAttr( SpeedTreeForest + ".bb" ) mc.setAttr( partInstancer + '.lod', useBBs ) assignForestObject = True if assignForestObject: if treePlug != '': mc.disconnectAttr( treePlug, SpeedTreeForest + '.forestObjects[' + str( setIndex ) + ']' ) mc.setAttr( treePlug.split( '.' )[0] + '.visibility', 1 ) mc.connectAttr( tree + '.message', SpeedTreeForest + '.forestObjects[' + str( setIndex ) + ']' ) #create asset if MayaVersion >= 2009: SpeedTreeAsset = mc.container( q=True, findContainer=[ partCloudShape ] ) if partInstancer != '' and SpeedTreeAsset != None and SpeedTreeAsset != '': mc.container( SpeedTreeAsset, edit=True, addNode=partInstancer, force=True )
def setFK(self,*jnt): copied=[] for e in jnt: name=e.split('_')[0]+'_FK_'+e.split('_')[2] dup= cmds.duplicate (e,n=name,rr=True,rc=True) tmp=setUniqueName(dup[0],'JNT') par= cmds.listRelatives (tmp,p=True,typ='joint') chi= cmds.listRelatives (tmp,c=True,typ='joint') if par is not None: if len(copied) is not 0: cmds.parent (tmp,copied[-1]) if cmds.connectionInfo (tmp+'.inverseScale',id=True) is False: cmds.connectAttr (copied[-1]+'.scale',tmp+'.inverseScale',f=True) if chi is not None: cmds.delete (chi) copied.append(tmp) cmds.parent(copied[0],'FKJoint_GRP') self.FkCon=fkControllerMaker( 'octagon', 'yellow', copied ) for s in self.FkCon[0]: sha= cmds.listRelatives (s,s=True,typ='nurbsCurve') cmds.rotate (0,0,90,sha[0]+'.cv[*]',os=1) nul= cmds.listRelatives (self.FkCon[0][0],p=True) cmds.parent (nul,'FKControl_GRP') return self.FkCon[0]
def _scale_skeleton(cls, binder_namespace): for jnt in mc.ls(type='joint'): if not jnt.startswith(binder_namespace) and jnt.endswith( 'C_pelvis'): source_root_joint = jnt break scale = (1.0, 1.0, 1.0) meta_nodes = getMetaNodes(mTypes='MsvAnimationBinderRig') if meta_nodes: for obj in meta_nodes: joint = obj.rootJoints[0].mNode scale = mc.getAttr(mc.listRelatives(joint, p=True)[0] + '.s')[0] break parent_grp = mc.listRelatives(source_root_joint, p=True) if parent_grp: parent_grp = parent_grp[0] # Be careful there is a link between this group and it's children joints # group.scale -> joint.inverseScale, we need to break it to let scale work dests = mc.connectionInfo('%s.scale' % parent_grp, destinationFromSource=True) for dest in dests: mc.disconnectAttr('%s.scale' % parent_grp, dest) else: parent_grp = mc.group(source_root_joint, n='output_Grp', w=True, r=True) mc.xform(parent_grp, os=True, pivots=(0, 0, 0)) if scale != (1.0, 1.0, 1.0): mc.xform(parent_grp, s=scale, os=True)
def updateBumpControl(self): # We were unable to set the values, something must be plugin, get it and build controls for it nodeAttr = cmds.connectionInfo(self.attr("bump"), sfd=True) if not nodeAttr: cmds.setAttr(self.attr("bump"), 0, 0, 0) cmds.columnLayout(self.columnLayout, edit=True, manage=False) return for child in cmds.layout( self.columnLayout, query=True, childArray=True) or []: cmds.deleteUI(child) node = nodeAttr.split(".")[0] self.value = cmds.attrFieldSliderGrp(attribute="%s.bumpValue" % node, label="Bump Value", columnWidth=columnWidthData, parent=self.columnLayout) self.depth = cmds.attrFieldSliderGrp(attribute="%s.bumpDepth" % node, label="Bump Depth", columnWidth=columnWidthData, parent=self.columnLayout) try: self.interp = cmds.attrEnumOptionMenuGrp( attribute="%s.bumpInterp" % node, label="Use As:", columnWidth=columnWidthData3, parent=self.columnLayout) except: pass cmds.columnLayout(self.columnLayout, edit=True, manage=True)
def on_actionConnectHairSystem_triggered(self, clicked=None): if clicked==None:return HairSystem = [] for checkBox in self.HairSystemList.children(): if checkBox.isChecked(): HairSystem.append(str(checkBox.text())) if len(HairSystem) == 0:return ControlFile = os.path.join(scriptTool.getScriptPath(), 'jiesuankaiguan.ma') mc.file(ControlFile, i=True) #---------------------------- HairControlG = mc.ls(assemblies=True)[-1] HairControl = [x for x in mc.listRelatives(HairControlG, ad=True, path=True) if x.endswith('ctrl')][0] attractionScale = [x for x in mc.listRelatives(HairControlG, ad=True, path=True) if x.endswith('attractionScale')][0] mc.connectAttr('%s.%s'%(HairSystem[0], 'message'), '%s.%s'%(attractionScale, 'hairSystem'), f=True) for i, sysNode in enumerate(HairSystem): JointA = mc.connectionInfo('%s.%s'%(sysNode, 'iterations'), sfd=True) JointA = JointA.split('.')[0] mc.connectAttr('%s.%s'%(HairControl, 'chainStartEnveloppe'), '%s.%s'%(JointA, 'chainStartEnveloppe'), f=True) mc.connectAttr('%s.%s'%(HairControl, 'chainStartFrame'), '%s.%s'%(sysNode, 'startFrame'), f=True) mc.connectAttr('%s.%s'%(HairControl, 'chainStiffness'), '%s.%s'%(sysNode, 'stiffness'), f=True) mc.connectAttr('%s.%s'%(HairControl, 'chainDamping'), '%s.%s'%(sysNode, 'damp'), f=True) mc.connectAttr('%s.%s'%(HairControl, 'chainGravity'), '%s.%s'%(sysNode, 'gravity'), f=True) mc.connectAttr('%s.%s'%(HairControl, 'chainCollide'), '%s.%s'%(sysNode, 'collide'), f=True) mc.connectAttr('%s.%s'%(HairControl, 'StarCurveAttract'), '%s.%s'%(sysNode, 'startCurveAttract'), f=True) if i > 0: mc.connectAttr('%s.%s'%(HairSystem[0], 'attractionScale[0]'), '%s.%s'%(sysNode, 'attractionScale[0]')) mc.connectAttr('%s.%s'%(HairSystem[0], 'attractionScale[1]'), '%s.%s'%(sysNode, 'attractionScale[1]')) if mc.objExists('hairExp'):return mel.eval('source "%s"'%os.path.join(scriptTool.getScriptPath(), 'makeScriptNode.mel').replace('\\', '/')) mc.setAttr('hairExp.scriptType', 1)
def k001_check_hairlinkarnold(): from maya.cmds import pluginInfo, ls, connectionInfo, listConnections k_return = [] k_lsshaveHair = [] k_lshairSystem = [] k_lsshaveHair = [ a for a in ls(type='hairSystem') if a.find("rig_") == -1 and listConnections(a, type='pfxHair') ] if pluginInfo('shaveNode', q=1, loaded=1): k_lsshaveHair += ls(type='shaveHair') else: pass for k_shave in k_lsshaveHair: k_attrn = [] try: k_attrn = connectionInfo((k_shave + ".aiHairShader"), id=1) except: pass if k_attrn: k_listai = listConnections(k_shave + ".aiHairShader", d=1) if k_listai: pass else: k_return.append(k_shave) else: k_return.append(k_shave) return k_return
def light_ibd(self): name = self.light light_instObjGroups = str(self.light.name()) + '.instObjGroups' if cmds.connectionInfo(light_instObjGroups, isSource=True): return 1 else: return 0
def attachPolyMesh(name, identifier, jobInfo, isConstant=False): cmds.ExocortexAlembic_profileBegin( f="Python.ExocortexAlembic._attach.attachPolyMesh") if cmds.objectType(name) != "mesh": print("Only mesh can be attached too!") cmds.ExocortexAlembic_profileEnd( f="Python.ExocortexAlembic._attach.attachPolyMesh") return polyObj = cmds.connectionInfo( name + ".inMesh", sfd=True).split('.')[0] # cmds.plugNode doesn't exist! if polyObj and cmds.objectType( polyObj ) == "ExocortexAlembicPolyMeshDeform": # it's already attached to a deform, simply change the file reference attachTimeAndFile(polyObj, jobInfo, isConstant) return # create deformer, and attach time and file newDform = cmds.deformer(name, type="ExocortexAlembicPolyMeshDeform")[0] cmds.setAttr(newDform + ".identifier", identifier, type="string") attachTimeAndFile(newDform, jobInfo, isConstant) if jobInfo.useFaceSets: cmds.ExocortexAlembic_createFaceSets(f=cmds.getAttr(jobInfo.filenode + ".outFileName"), i=identifier, o=name) cmds.ExocortexAlembic_profileEnd( f="Python.ExocortexAlembic._attach.attachPolyMesh") pass
def remove_texture_duplicates(): textures = cmds.ls(tex=True) file2Node = dict() node2Node = list() needDelete = list() for texture in textures: tex_file = cmds.getAttr(texture + ".fileTextureName") if tex_file == "": continue plc2dTex = cmds.listConnections(texture, d=False) if plc2dTex != None and cmds.listConnections(plc2dTex[0], d=False) != None: continue otherTexture = file2Node.get(tex_file, None) if otherTexture == None: file2Node[tex_file] = texture else: node2Node.append(texture) node2Node.append(otherTexture) needDelete.append(texture) dsts = cmds.connectionInfo(texture + ".outColor", destinationFromSource=True) for dst in dsts: cmds.connectAttr(otherTexture + ".outColor", dst, force=True) for each in needDelete: parents = cmds.listConnections(each, t="place2dTexture") cmds.delete(each) if parents != None: cmds.delete(parents) sys.stdout.write(str(len(needDelete)) + " textures removed.\n")
def attachCamera(name, identifier, jobInfo, isConstant=False): cmds.ExocortexAlembic_profileBegin( f="Python.ExocortexAlembic._attach.attachCamera") camObj = cmds.connectionInfo(name + ".focalLength", sfd=True) if camObj and cmds.objectType(camObj) == "ExocortexAlembicCamera": attachTimeAndFile(camObj, jobInfo, isConstant) return reader = cmds.createNode("ExocortexAlembicCamera") cmds.connectAttr(reader + ".focalLength", name + ".focalLength") cmds.connectAttr(reader + ".focusDistance", name + ".focusDistance") cmds.connectAttr(reader + ".lensSqueezeRatio", name + ".lensSqueezeRatio") cmds.connectAttr(reader + ".horizontalFilmAperture", name + ".horizontalFilmAperture") cmds.connectAttr(reader + ".verticalFilmAperture", name + ".verticalFilmAperture") cmds.connectAttr(reader + ".horizontalFilmOffset", name + ".horizontalFilmOffset") cmds.connectAttr(reader + ".verticalFilmOffset", name + ".verticalFilmOffset") cmds.connectAttr(reader + ".fStop", name + ".fStop") cmds.connectAttr(reader + ".shutterAngle", name + ".shutterAngle") attachTimeAndFile(reader, jobInfo, isConstant) cmds.ExocortexAlembic_profileEnd( f="Python.ExocortexAlembic._attach.attachCamera") pass
def attachCurves(name, identifier, jobInfo, isConstant=False): cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._attach.attachCurves") try: conX = cmds.listConnections( name + ".create", d=False, type="ExocortexAlembicCurvesDeform" ) or cmds.listConnections(name + ".create", d=False, type="ExocortexAlembicCurves") if conX: curObj = conX[0] attachTimeAndFile(curObj, jobInfo, isConstant) return [curObj] # create deformer, and attach time and file newDform = cmds.deformer(name, type="ExocortexAlembicCurvesDeform")[0] cmds.setAttr(newDform + ".identifier", identifier, type="string") attachTimeAndFile(newDform, jobInfo, isConstant) # get curObj new "output" attribute connection conX = cmds.listConnections(name + ".create", d=False, type="ExocortexAlembicCurvesDeform") if conX: curObj = conX[0] originalCur = cmds.connectionInfo(curObj + ".output", sfd=True).split(".")[0] cmds.delete(curObj) curObj = cmds.createNode("ExocortexAlembicCurves") attachTimeAndFile(curObj, jobInfo, isConstant) cmds.connectAttr(curObj + ".outCurve", originalCur + ".create") cmds.connectAttr(jobInfo.filenode + ".outFileName", curObj + ".fileName") cmds.setAttr(curObj + ".identifier", identifier, type="string") except: return ["!", traceback.format_exc()] finally: cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._attach.attachCurves") return [curObj]
def reset_actor(): from . import sisidebar_sub sel = cmds.ls(sl=True, l=True) joints = cmds.ls(sl=True, l=True, type="joint") if not joints: joints = [] for s in sel: if cmds.nodeType(s) == "KTG_ModelRoot": child_joints = cmds.ls(cmds.listRelatives(s, ad=True, f=True), l=True, type="joint") if child_joints: joints += child_joints if not sel: joints = cmds.ls(l=True, type="joint") for j in joints: con_info = cmds.connectionInfo(j + ".bindPose", dfs=True) if not con_info: continue con_info = con_info[0] bind_info = con_info.replace("world", "xform") pose = cmds.getAttr(bind_info) cmds.xform(j, m=pose) sisidebar_sub.get_matrix()
def ChangeBSTarget(self, *args): #替换blendshape目标体 selObj = cmds.ls(sl = True, type = "transform") if len(selObj) != 2 : cmds.confirmDialog(t=u'敬告!!!', m=u'请选择两个模型,原bs + 现bs', b=[u'好的'], db=u'好的') return OrgAttr = selObj[0] + ".worldMesh[0]" CurrentAttr = selObj[1] + ".worldMesh[0]" if not (cmds.objExists(OrgAttr) and cmds.objExists(CurrentAttr)): cmds.confirmDialog(t=u'敬告!!!', m=u'请选择两个模型,原bs + 现bs', b=[u'好的'], db=u'好的') return destination = cmds.connectionInfo(OrgAttr, destinationFromSource = True) if len(destination) >= 1 and cmds.objExists(destination[0]): cmds.disconnectAttr(OrgAttr, destination[0]) cmds.connectAttr(CurrentAttr, destination[0]) else: cmds.confirmDialog(t=u'敬告!!!', m=u'所选模型不是bsTarget', b=[u'好的'], db=u'好的') return self.Align(selObj[1], selObj[0]) baseName = str(selObj[0]) tempName = baseName.split("|") baseName = tempName[len(tempName) - 1] changObj = selObj[1] parentObj = cmds.listRelatives(selObj[0], parent= True) cmds.delete(selObj[0]) Obj = cmds.rename(changObj, baseName) cmds.parent(Obj, parentObj)
def Opcom(arg): selAs = cmds.ls(type='aiStandard') editedm=cmds.ls(typ=('aiUtility','aiStandard','aiWriteColor','file','place2dTexture','displacementShader','bump2d','shadingEngine','ramp','blendColors','condition','gammaCorrect','luminance','samplerInfo','surfaceLuminance','aiSkin','aiHair')) for i in range(0,len(selAs)): AsOp=cmds.listConnections(selAs[i] + '.opacity',plugs=True,d=0) AsOpfile = cmds.listConnections(selAs[i] + '.opacity',d=0) AsOpjust=cmds.connectionInfo(selAs[i] + '.opacity',id=True) AsOptO = selAs[i] + '.opacity' AsOpt = cmds.getAttr(AsOptO) if AsOpt != [(1.0,1.0,1.0)]: AsOptOname = AsOptO[0:len(AsOptO)-len(".opacity")]#去除opacity属性后缀 AsOptAi2WT = cmds.listConnections(AsOptOname,s=0,type='aiWriteColor') AsTrueOPAU = cmds.listConnections(AsOptAi2WT,d=0,type='aiUtility') AsOptSG2WT2 = cmds.listConnections(AsOptAi2WT,s=0,type='aiUtility') AsOptSG = cmds.listConnections(AsOptSG2WT2,s=0,type='shadingEngine') AsOptSGs = cmds.listConnections(AsOptSG,d=0) AsTrueshapes = [b for b in AsOptSGs if b not in editedm] AsTrueshapesS = cmds.listRelatives(AsTrueshapes) for b in range(0,len(AsTrueshapesS)): cmds.setAttr(AsTrueshapesS[b] + ".aiOpaque",0) if AsOpjust == True: for c in range(0,len(AsOpfile)): cmds.connectAttr(AsOpfile[c] + '.outAlpha',AsTrueOPAU[c] + '.opacity',f=True) cmds.setAttr(AsOpfile[c]+'.alphaIsLuminance',1) cmds.setAttr(AsOptAi2WT[c] +'.blend',1)
def copyFromProxy(self): animCurves = [] for ac in cmds.ls(type="animCurveTL"): animCurves.append(ac) for ac in cmds.ls(type="animCurveTA"): animCurves.append(ac) for ac in cmds.ls(type="animCurveTU"): animCurves.append(ac) cmds.progressWindow(title=u"导入动画", status=u"导入中...") cmds.progressWindow(e=True, progress=0, max=len(animCurves)) for cv in animCurves: cmds.progressWindow(e=True, step=1) if cmds.referenceQuery(cv, isNodeReferenced=True): continue out = cmds.connectionInfo("%s.output" % cv, destinationFromSource=True) if not out: continue out = out[0] if out.find('___Proxy') == -1: continue if not len((':%s' % out).split(self.namespace)) == 2: continue attr = out.split(".")[-1] target = out.split("___")[0] try: cmds.copyKey(cv) cmds.pasteKey(target, attribute=attr, option=self.configuration['mode']) except Exception, e: print "%s" % e
def manual_codebook(self, mayaMesh, jointList): sel = om.MSelectionList() sel.add(mayaMesh) dPath = sel.getDagPath(0) mMesh = om.MFnMesh(dPath) num = mMesh.numVertices #fine skinCluster skincluster = mel.eval('findRelatedSkinCluster("%s")' % mayaMesh) # array codeBook arrayL = [] correct_JList = [] for i in range(num): spct = cmds.skinPercent(skincluster, mayaMesh + '.vtx[' + str(i) + ']', q=1, value=1) # please do not paint skinweight for x in range(len(spct)): if spct[x] >= 0.6: arrayL.append(x) codeBook = np.array(arrayL) #correct joint Index for y in range(len(jointList)): b = cmds.connectionInfo(skincluster + '.matrix[' + str(y) + ']', sfd=1) j = b.split('.')[0] correct_JList.append(j) return codeBook, correct_JList
def copyToProxy(self, startTime, endTime): animCurves = [] for ac in cmds.ls(type="animCurveTL"): animCurves.append(ac) for ac in cmds.ls(type="animCurveTA"): animCurves.append(ac) for ac in cmds.ls(type="animCurveTU"): animCurves.append(ac) cmds.progressWindow(title=u"导出动画", status=u"导出中...") cmds.progressWindow(e=True, progress=0, max=len(animCurves)) for cv in animCurves: cmds.progressWindow(e=True, step=1) if cmds.referenceQuery(cv, isNodeReferenced=True): continue out = cmds.connectionInfo("%s.output" % cv, destinationFromSource=True) if out and len((':%s' % out[0]).split(self.namespace)) == 2: out = out[0] loc = "%s|%s___Proxy" % (self.grp, out.split(".")[0]) attr = out.split(".")[-1] #print "%s.output"%cv, "-> %s.%s"%(loc, attr) try: cmds.copyKey(cv) cmds.pasteKey(loc, attribute=attr) cmds.setKeyframe(loc, time=[startTime, endTime]) except Exception, e: print u"%s" % e
def setComponents(componentList, convexHullNode, index, preserveExisting=True, optimize=True): """ Given a list of components (in the form of ['f[0]','vtx[23:67]', ...]), set the specified, indexed componentList attribute for the convex hull. If preserveExisting is True, the any components that are already on the attribute will be preserved. Otherwise, they will be overwritten. If optimize is set to True, convert the list of components into the more compact form that Maya typically expects. """ inputAttr = '%s.input[%d]' % (convexHullNode, index) if preserveExisting: comps = cmds.getAttr('%s.ics' % inputAttr) if comps is not None: componentList.extend(comps) if optimize: attr = '%s.input' mesh = cmds.connectionInfo('%s.inputPolymesh' % inputAttr, sfd=True, dfs=False) if mesh is None or mesh == '': mel.eval('warning "Unable to determine connected to ' \ '%s.inputPolymesh' % inputAttr) else: meshName, plug = _splitattr(mesh) componentList = _optimizeComponentList(meshName, componentList) # Flatten the list to a space-delimited string numComponents = len(componentList) print componentList cmds.setAttr('%s.ics' % inputAttr, numComponents, type='componentList', *componentList)
def checkDeleteConnection(self , attr ): # 被输入方 if mc.connectionInfo(attr , isDestination = 1): destination = mc.connectionInfo(attr , getExactDestination = 1) srcConn = mc.listConnections(destination, s = 1, d = 0 , type = 'character') if srcConn: # 断开 mc.character(destination , e = 1 ,rm = srcConn[0]) sArr = mc.ls(destination , ro = 1) if sArr: src = mc.connectionInfo(destination , sourceFromDestination = 1) if src: mc.disconnectAttr(src , destination) else: mc.delete(destination , icn = 1)
def testNamespace(self): self.buildScene() self.__files.append(util.expandFileName('testNamespace_foo_a.abc')) self.__files.append(util.expandFileName('testNamespace_bar_a.abc')) self.__files.append(util.expandFileName('testNamespace_a.abc')) MayaCmds.AbcExport(j='-root foo:a -fr 1 4 -file ' + self.__files[-3]) MayaCmds.AbcExport(j='-root bar:a -fr 1 4 -file ' + self.__files[-2]) MayaCmds.AbcExport(j='-root a -fr 1 4 -file ' + self.__files[-1]) self.buildStatic() MayaCmds.AbcImport(self.__files[-3], connect='foo:a') self.failUnless( 'testNamespace_foo_a_AlembicNode.outPolyMesh[0]' == MayaCmds. connectionInfo("|foo:a|foo:b|foo:bShape.inMesh", sfd=True)) MayaCmds.AbcImport(self.__files[-2], connect='bar:a') self.failUnless( 'testNamespace_bar_a_AlembicNode.outPolyMesh[0]' == MayaCmds. connectionInfo("|bar:a|bar:b|bar:bShape.inMesh", sfd=True)) MayaCmds.AbcImport(self.__files[-1], connect='a') self.failUnless( 'testNamespace_a_AlembicNode.outPolyMesh[0]' == MayaCmds.connectionInfo("|a|b|bShape.inMesh", sfd=True))
def mila2Json(): objectList=[] nodeList=[] ### generate list of nodes in network selection = cmds.ls(sl=True) if selection ==[] or len (selection) >1: print "Please select one shader object" sys.exit(2) _mapNetwork (selection[0],objectList) ### create node objects for i in objectList: nodeList.append(node(i)) for n in nodeList: print "reading: %s"%n.name print "type: %s"%n.type ### connections c=_getConnections(n.name) if c is not None: for connection in c: print "adding connection: %s" % str(connection) try: n.addConnection(connection[0],connection[1]) except: print("unable to add connection: %s " %connection) #### attributes print "getting attrs" attrs = cmds.listAttr(n.name,multi=True) for a in attrs: attribute = "%s.%s"%(n.name,a) isConnected=None try: isConnected =cmds.connectionInfo(attribute,ges=True) except: print "trouble checking conneciton of attr, skipping" if (isConnected == ""): print "getting attr %s" %attribute try: type = cmds.attributeQuery(a,node=n.name,at=True) except: type= None print "type: %s" %type if type !="message": try: value= cmds.getAttr(attribute) except: pass n.addValue(a,value,type) print n.attributes[a] else: print "ignoring message" else: print "skipping, attribute connected %s.%s" %(n.name,a) writeJson(nodeList)
def setComponents(componentList, convexHullNode, index, preserveExisting=True, optimize=True): """ Given a list of components (in the form of ['f[0]','vtx[23:67]', ...]), set the specified, indexed componentList attribute for the convex hull. If preserveExisting is True, the any components that are already on the attribute will be preserved. Otherwise, they will be overwritten. If optimize is set to True, convert the list of components into the more compact form that Maya typically expects. """ inputAttr = "%s.input[%d]" % (convexHullNode, index) if preserveExisting: comps = cmds.getAttr("%s.ics" % inputAttr) if comps is not None: componentList.extend(comps) if optimize: attr = "%s.input" mesh = cmds.connectionInfo("%s.inputPolymesh" % inputAttr, sfd=True, dfs=False) if mesh is None or mesh == "": mel.eval('warning "Unable to determine connected to ' "%s.inputPolymesh" % inputAttr) else: meshName, plug = _splitattr(mesh) componentList = _optimizeComponentList(meshName, componentList) # Flatten the list to a space-delimited string numComponents = len(componentList) print componentList cmds.setAttr("%s.ics" % inputAttr, numComponents, type="componentList", *componentList)
def capReplace(*args): sel = cmds.ls(sl=True, type="transform") if sel < 2: cmds.warning( "You don't have two things selected (cap and one ctrl minimum)!") return newCap = sel[0] ctrls = sel[1:] for ctrl in ctrls: oldCap = cmds.connectionInfo("{0}.capRig".format(ctrl), sfd=True).partition(".")[0] dupe = rig.swapDupe(newCap, oldCap, delete=True, name=oldCap) cmds.connectAttr("{0}.rotateCap".format(ctrl), "{0}.rotateY".format(dupe)) cmds.connectAttr("{0}.message".format(dupe), "{0}.capRig".format(ctrl)) cmds.setAttr("{0}.v".format(dupe), 1) # if not already, parent cap replace obj in folder and hide par = cmds.listRelatives(newCap, p=True) if not par or par[0] != "pastaRigSetupComponents_Grp": cmds.parent(newCap, "pastaRigSetupComponents_Grp") cmds.setAttr("{0}.v".format(newCap), 0) cmds.select(ctrls, r=True)
def addJoint(side='L'): if mc.objExists('%s_armPalm_bnd_0'%side):return # make joint and locators Joint = mc.createNode('joint', name='%s_armPalm_bnd_0'%side) JointGroup = mc.group(Joint, name='%s_armPalm_bndgrp_0'%side) FKloc = mc.spaceLocator(p=(0,0,0), name='%s_armPalmFK_loc_0'%side)[0] IKloc = mc.spaceLocator(p=(0,0,0), name='%s_armPalmIK_loc_0'%side)[0] # constraint constraintNode = mc.parentConstraint(FKloc, IKloc, JointGroup) # match position mc.delete(mc.parentConstraint('%s_armMiddleAIK_jnt_0'%side, FKloc)) mc.delete(mc.parentConstraint('%s_armMiddleAIK_jnt_0'%side, IKloc)) # parent locator mc.parent(FKloc, '%s_armWristFk_jnt_0'%side) mc.parent(IKloc, '%s_armMiddleAIK_jnt_0'%side) # make ikfk switch reverseNode = [x.split('.')[0] for x in mc.connectionInfo('%s_armFkIk_ctl_0.FKIKBlend'%side, dfs=True) if mc.nodeType(x.split('.')[0])=='reverse'][0] mc.connectAttr('%s.outputX'%reverseNode, '%s.%sW0'%(constraintNode[0], FKloc)) mc.connectAttr('%s_armFkIk_ctl_0.FKIKBlend'%side, '%s.%sW1'%(constraintNode[0], IKloc)) # add to bind set mc.sets(Joint, e=True, forceElement='bind_joints_set') # connect jointLayer mc.connectAttr('jointLayer.drawInfo', '%s.drawOverride'%Joint) # parent joint mc.parent(JointGroup, '%s_armBind_org_0'%side)
def makeActive( rfn ): """ Make active all nested references. """ result = [] references = referenceRelatives( rfn, onlyLoaded=False, parents=False ) if references: m_count = len( references ) if m_count > 1: for i in range( 0, m_count ): if references[i] not in result: result.append( references[i] ) pm = cmds.listConnections( "%s.proxyMsg" % references[i], type="proxyManager" ) if pm: pm = pm[0] #Get active reference. rfn = "" proxy = cmds.listConnections( "%s.proxyList" % pm, type="reference", source=False, destination=True ) if proxy: for n in range( 0, len( proxy )): if cmds.referenceQuery( proxy[n], isLoaded=True ): rfn = proxy[n] break if rfn == "": rfn = proxy[0] #Deactivate all non active references. active = cmds.listConnections( "%s.activeProxy" % pm, plugs=True ) if active: for n in range( 0, len( active )): cmds.disconnectAttr( "%s.activeProxy" % pm, active[n] ) #Make active reference. lproxy = cmds.connectionInfo( "%s.proxyMsg" % rfn, sourceFromDestination=True ) if lproxy: cmds.connectAttr( "%s.activeProxy" % pm, lproxy ) return result
def expose_output_attr(self, dagpath): """ Expose an attribute as an output attribute of the compound. :param str dagpath: The attribute to expose :return: The dagpath of the exposed attribute :raises: ValueError: If the attribute is the source of an existing connection. """ dagpath = ( dagpath.__melobject__() if hasattr(dagpath, "__melobject__") else dagpath ) if cmds.connectionInfo(dagpath, isSource=True): raise ValueError("Cannot expose a source attribute: %r" % dagpath) # TODO: Manage name collision src_node, attr_name = dagpath.split(".") dst_dagpath = _utils_attr.transfer_attribute(src_node, self.output, attr_name) # Our reference attribute might not be "writable" (a possible connection source). # TODO: Don't use pymel? pymel.Attribute(dst_dagpath).__apimattr__().setWritable(True) cmds.connectAttr(dagpath, dst_dagpath) return dst_dagpath
def replace_follicle_atcach_geometry(follicle, new_geo): ''' connect follicle to new face... ''' position = mc.xform(follicle, q=True, ws=True, t=True) geo_shape = mc.listRelatives(new_geo, s=True, path=True)[0] #- disconnect old connect... for attr in ('is', 'inm', 'iwm'): source_attr = mc.connectionInfo('{0}.{1}'.format(follicle, attr), sfd=True) if source_attr: mc.disconnectAttr(source_attr, '{0}.{1}'.format(follicle, attr)) #- set new UV parameters... if mc.nodeType(geo_shape) == 'mesh': u_value, v_value = polygon.get_polygon_uv_at_point(new_geo, position) else: u_value, v_value = nurbsSurface.get_nurbs_uv_at_point(new_geo, position) set_follicle_parameter(follicle, u_value, v_value) #- connect geometry... if mc.nodeType(geo_shape) == 'mesh': connect_follicle_polygon(follicle, new_geo) else: connect_follicle_nurbs(follicle, new_geo) return True
def on_actionLoadSourceControl_triggered(self, clicked=None): if clicked == None: return selectOBJ = mc.ls(sl=True) if len(selectOBJ) == 0: return self.sourceControlFLD.setText(selectOBJ[0]) KeyableAttr = mc.listAttr(selectOBJ[0], k=True) del self.sourceAtrLst[:] del self.targentAtrLst[:] # loop Attributes.. for Attr in KeyableAttr: SDKeys = mc.connectionInfo('%s.%s' % (selectOBJ[0], Attr), dfs=True) # loop driven Attributes.. for key in SDKeys: if mc.nodeType(key) == 'unitConversion': keyNode = mc.connectionInfo('%s.output' % key.split('.')[0], dfs=True)[0].split('.')[0] elif mc.nodeType(key) not in ('animCurve', 'animCurveTA', 'animCurveTL', 'animCurveTT', 'animCurveTU', 'animCurveUA', 'animCurveUL', 'animCurveUT', 'animCurveUU'): continue else: keyNode = key.split('.')[0] DriverValues = mc.keyframe(keyNode, q=True, fc=True) DrivenValues = mc.keyframe(keyNode, q=True, vc=True) DriverAttribute = mc.connectionInfo('%s.output' % keyNode, dfs=True)[0] # if more than one Drivers, from add node get the attribute.. if DriverAttribute.endswith(']'): DriverAttribute = mc.connectionInfo( '%s.output' % (DriverAttribute.split('.')[0]), dfs=True)[0] self.sourceAtrLst.append([ '%s.%s' % (selectOBJ[0], Attr), DriverAttribute, DriverValues, DrivenValues ]) self.on_actionInputSearchReplace_triggered()
def copy_attributes(src_name, dst_name, include=None, prefix=None, connect=False, copy_values=False): include = set(include) if include else None src_obj = mobject_from_name(src_name) src_dep = om.MFnDependencyNode(src_obj) dst_obj = mobject_from_name(dst_name) dst_dep = om.MFnDependencyNode(dst_obj) existing_attrs = set(cmds.listAttr(dst_name)) with context.selection(): cmds.select([dst_name], replace=True) for attr_name in cmds.listAttr(src_name): if include and attr_name not in include: continue if prefix and not attr_name.startswith(prefix): continue # Skip any attributes which are part of a multi-attribute unless # specifically requested. if not include and cmds.attributeQuery( attr_name, node=src_name, listParent=True): continue attr_obj = src_dep.attribute(attr_name) attr_plug = om.MPlug(src_obj, attr_obj) # Create the attribute on the destination of it doesn't exist. if attr_name not in existing_attrs: dst_dep.addAttribute(attr_obj) if connect: src_attr = src_name + '.' + attr_name dst_attr = dst_name + '.' + attr_name existing_conn = cmds.connectionInfo(dst_attr, sourceFromDestination=True) if existing_conn and existing_conn != src_attr: cmds.warning('Replacing connection from %r to %r' % (existing_conn, dst_attr)) if not existing_conn or existing_conn != src_attr: cmds.connectAttr(src_attr, dst_attr) elif copy_values: # Evaluate the mel required to copy the values. for mel_chunk in attr_plug.getSetAttrCmds(): mel.eval(mel_chunk)
def light_ibd(self): for i in self.lights_list: name = i light_instObjGroups = str(name) + '.instObjGroups' if cmds.connectionInfo(light_instObjGroups, isSource=True): return 1 else: return 0
def wireToSkincluster(): curveTransform = cmds.ls(sl=True)[0] curveShape = cmds.listRelatives(curveTransform, type='shape')[0] curveConnection = cmds.connectionInfo('%s.worldSpace[0]' % curveShape, dfs=True)[0] wire = curveConnection.split('.')[0] SkinningLib.extrapFromWire(wire)