def write_ouputState(self,outState_handle,numberofOutput_Val,activeIndex_Val,ThsNde ,activeValue_Val,disableValue_Val): cBuilder = outState_handle.builder() stateList = [] stateList = [ disableValue_Val for k in range(numberofOutput_Val) ] stateList[activeIndex_Val] = activeValue_Val currentDH = OpenMaya.MDataHandle() for n in range(0,numberofOutput_Val): currentDH = cBuilder.addElement(n) currentDH.setInt(stateList[n]) bldChck = cBuilder.elementCount() # prune unwanted index --> equivalent to removeMultiInstance... if bldChck>numberofOutput_Val: depFn = OpenMaya.MFnDependencyNode( ThsNde ) curvePointsPlug = depFn.findPlug('outState') outName = curvePointsPlug.info() for k in range(bldChck-1,numberofOutput_Val-1,-1): try: cBuilder.removeElement(k) except: # --> a bit dirty but it help when node is not connected yet we have access to the correct number of output attribute # when node is connected this fallback is not needed anymore cmds.removeMultiInstance( '%s[%s]'%(outName,k), b=True ) outState_handle.set(cBuilder) outState_handle.setAllClean()
def syncAttribute(self, attr, control, valueField, positionField): attr = self.nodeAttr('aiShutterCurve') values = cmds.gradientControlNoAttr( control, query=True, asString=True) valuesSplit = values.split(',') points = [] for i in range(0,len(valuesSplit)/3): points.append([valuesSplit[i*3+1],valuesSplit[i*3],0]) current = cmds.gradientControlNoAttr( control, query=True, currentKey=True) cmds.floatField(valueField, edit=True, value=float(points[current][1])) cmds.floatField(positionField, edit=True, value=float(points[current][0])) points[current][2] = 1 points.sort() size = cmds.getAttr(attr, size=True) for i in range(0,size): cmds.removeMultiInstance(attr+'['+str(i)+']') curveString = "" for i in range(0,len(points)): cmds.setAttr(attr+'['+str(i)+'].aiShutterCurveX',float(points[i][0])) cmds.setAttr(attr+'['+str(i)+'].aiShutterCurveY',float(points[i][1])) if i is 0: curveString += points[i][1] +"," + points[i][0] +",1" else: curveString += ","+points[i][1] +"," + points[i][0] +",1" # We save the curve points sorted in the attribute, so we will also resort the points in # the gradient control current = [x[2] for x in points].index(1) cmds.gradientControlNoAttr( control, edit=True, currentKey=current, asString=curveString)
def removeMultiInstances(node, attr): attrs = cmds.ls(node + '.' + attr + '[*]') for attr in attrs: if not cmds.listConnections(attr, s=1, d=0): cmds.removeMultiInstance(attr)
def _disconnectAndRemoveAttr(attr, remove=False): """Disconnects inputs and outputs from the given attribute.""" sel = cmds.ls(sl=True) cmds.select(cl=True) # unlock if needed cmds.setAttr(attr, l=False) # if any connection, disconnect srcAttrs = cmds.listConnections(attr, d=False, p=True) or [] destAttrs = cmds.listConnections(attr, s=False, p=True) or [] for srcAttr in srcAttrs: cmds.disconnectAttr(srcAttr, attr) for destAttr in destAttrs: cmds.disconnectAttr(attr, destAttr) # remove element if remove: cmds.removeMultiInstance(attr) # remove alias if cmds.aliasAttr(attr, q=True): cmds.aliasAttr(attr, rm=True) cmds.select(sel or None)
def write_ouputState(self, outState_handle, numberofOutput_Val, activeIndex_Val, ThsNde): cBuilder = outState_handle.builder() bldChck = cBuilder.elementCount() growVal = numberofOutput_Val - bldChck if growVal > 0: #print 'we need to grow this array of ', bldChck , ' elements by ', growVal cBuilder.growArray(growVal) stateList = [] stateList = [0 for k in range(numberofOutput_Val)] stateList[activeIndex_Val] = 1 currentDH = OpenMaya.MDataHandle() for n in range(0, numberofOutput_Val): currentDH = cBuilder.addElement(n) currentDH.setBool(stateList[n]) bldChck = cBuilder.elementCount() # prune unwanted index --> equivalent to removeMultiInstance... if bldChck > numberofOutput_Val: depFn = OpenMaya.MFnDependencyNode(ThsNde) curvePointsPlug = depFn.findPlug('outState') outName = curvePointsPlug.info() for k in range(bldChck - 1, numberofOutput_Val - 1, -1): try: cBuilder.removeElement(k) except: # --> a bit dirty but it help when node is not connected yet we have access to the correct number of output attribute # when node is connected this fallback is not needed anymore cmds.removeMultiInstance('%s[%s]' % (outName, k), b=True) outState_handle.set(cBuilder) outState_handle.setAllClean()
def delete_Connections_at_targetIndex(self, root, targetIndex, IO_Index): attributeList = ['recipe'] cnList = ['input', 'output'] storage = mc.listConnections(root + '.' + attributeList[0]) if storage is None: attributeList = ['recipe'] storage = mc.createNode('recipe', n=''.join( (root, '_', attributeList[0], '1'))) mc.connectAttr(storage + '.nodeState', root + '.' + attributeList[0], f=True) else: storage = storage[0] idxList = mc.getAttr(storage + '.' + cnList[IO_Index], mi=True) idx = 0 if idxList is None: return else: targetIndex = idxList[targetIndex] if targetIndex in idxList: mc.removeMultiInstance(storage + '.' + cnList[IO_Index] + '[%s]' % targetIndex, b=True)
def removeMultiInstances( node, attr ): attrs = cmds.ls( node+'.'+attr+'[*]' ) for attr in attrs: if not cmds.listConnections( attr, s=1, d=0 ): cmds.removeMultiInstance( attr )
def copyVtxAndPast(meshName, index, indices): hists = cmds.listHistory(meshName) skinCluster = '' for hist in hists: if cmds.nodeType(hist) == 'skinCluster': skinCluster = hist if not skinCluster: return None fnSkinCluster = om.MFnDependencyNode(getMObject(skinCluster)) weightListPlug = fnSkinCluster.findPlug('weightList') weightListPlugElement = weightListPlug.elementByLogicalIndex(index) plugWeights = weightListPlugElement.child(0) indicesAndValues = [] for i in range(plugWeights.numElements()): index = plugWeights[i].logicalIndex() value = plugWeights[i].asFloat() indicesAndValues.append([index, value]) for vtxIndex in indices: weightListPlugElement = weightListPlug.elementByLogicalIndex(vtxIndex) plugWeights = weightListPlugElement.child(0) for i in range(plugWeights.numElements()): cmds.removeMultiInstance(plugWeights[0].name()) for index, value in indicesAndValues: cmds.setAttr(plugWeights.name() + '[%d]' % index, value)
def copyVtxAndPast( meshName, index, indices ): hists = cmds.listHistory( meshName ) skinCluster = '' for hist in hists: if cmds.nodeType( hist ) == 'skinCluster': skinCluster = hist if not skinCluster: return None fnSkinCluster = om.MFnDependencyNode( getMObject( skinCluster ) ) weightListPlug = fnSkinCluster.findPlug( 'weightList' ) weightListPlugElement = weightListPlug.elementByLogicalIndex( index ) plugWeights = weightListPlugElement.child( 0 ) indicesAndValues = [] for i in range( plugWeights.numElements() ): index = plugWeights[i].logicalIndex() value = plugWeights[i].asFloat() indicesAndValues.append( [index,value] ) for vtxIndex in indices: weightListPlugElement = weightListPlug.elementByLogicalIndex( vtxIndex ) plugWeights = weightListPlugElement.child( 0 ) for i in range( plugWeights.numElements() ): cmds.removeMultiInstance( plugWeights[0].name() ) for index, value in indicesAndValues: cmds.setAttr( plugWeights.name() + '[%d]' % index, value )
def setJointInfluence(skinCluster, jnt, vtxIndices): cons = cmds.listConnections(jnt + '.wm', type='skinCluster', c=1, p=1, d=1, s=0) if not cons: return None for con in cons: if con.find(skinCluster) != -1: skinClusterAttr = con fnSkinCluster = om.MFnDependencyNode(getMObject(skinCluster)) jntIndex = int(skinClusterAttr.split('[')[-1].replace(']', '')) weightListPlug = fnSkinCluster.findPlug('weightList') for vtxIndex in vtxIndices: weightListPlugElement = weightListPlug.elementByLogicalIndex(vtxIndex) weightPlug = weightListPlugElement.child(0) for i in range(weightPlug.numElements()): cmds.removeMultiInstance(weightPlug[0].name()) cmds.setAttr( skinCluster + '.weightList[%d].weights[%d]' % (vtxIndex, jntIndex), 1.0)
def _clear_maya_attribute(self): cmds.setAttr(self.path(), lock=False) for attr in self._iter_elements(): cmds.setAttr(attr, lock=False) cmds.removeMultiInstance(self.path(), allChildren=True, b=True)
def createCurve(mesh, indices): cons = cmds.listConnections(mesh + '.outMesh', type='sgVerticeToCurve', d=1, s=0) if not cons: vtsToCrv = cmds.createNode('sgVerticeToCurve') cmds.connectAttr(mesh + '.outMesh', vtsToCrv + '.inputMesh') cmds.connectAttr(mesh + '.wm', vtsToCrv + '.inputMeshMatrix') targetIndex = 0 else: vtsToCrv = cons[0] cons = cmds.listConnections(vtsToCrv + '.outputCurve', p=1, c=1) outputs = cons[::2] targetIndex = int(outputs[-1].split('[')[-1].replace(']', '')) + 1 crv = cmds.createNode('nurbsCurve') crvObj = cmds.listRelatives(crv, p=1, f=1)[0] cmds.connectAttr(vtsToCrv + '.outputCurve[%d]' % targetIndex, crv + '.create') cmds.connectAttr(crvObj + '.wim', vtsToCrv + '.input[%d].pim' % targetIndex, f=1) attrs = cmds.ls(vtsToCrv + '.input[%d].verticeIds[*]' % targetIndex) for attr in attrs: cmds.removeMultiInstance(attr) for i in range(len(indices)): if indices[i] == 0: indices[i] = -1 cmds.setAttr( vtsToCrv + '.input[%d].verticeIds[%d]' % (targetIndex, i), indices[i])
def set_multi_index(self): """ sets the corresponding dictionary for a multi index attribute """ for index in self.data['value'].keys(): if cmds.getAttr('{}.{}[{}].{}'.format(self.node, self.name, index, self.multi_name), type=True) == 'TdataCompound': if not cmds.getAttr('{}.{}[{}].{}'.format( self.node, self.name, index, self.multi_name), lock=True): cmds.removeMultiInstance('{}.{}[{}].{}'.format( self.node, self.name, index, self.multi_name)) if self.data['value'][index][0] is not None: for multi_index, multi_value in zip( *self.data['value'][index]): cmds.setAttr( '{}.{}[{}].{}[{}]'.format(self.node, self.name, index, self.multi_name, multi_index), multi_value) else: 'the folowing attribute was not modified {}'.format( '{}.{}[{}].{}'.format(self.node, self.name, index, self.multi_name))
def _repair_mesh(cls, mesh): """Process a single mesh, deleting other UV sets than the active one. Keep only current UV set and ensure it's the default 'map1' """ from maya import cmds uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) current = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0] # Copy over to map1 if current != 'map1': cmds.polyUVSet(mesh, uvSet=current, newUVSet='map1', copy=True) cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1') current = 'map1' # Delete all non-current UV sets deleteUVSets = [uvSet for uvSet in uvSets if uvSet != current] uvSet = None # Maya Bug (tested in 2015/2016): # In some cases the API's MFnMesh will report less UV sets # than maya.cmds.polyUVSet. # This seems to happen when the deletion of UV sets has not # triggered a cleanup of the UVSet array # attribute on the mesh node. It will still have extra # entries in the attribute, though it will not # show up in API or UI. Nevertheless it does show up in # maya.cmds.polyUVSet. # To ensure we clean up the array we'll force delete the # extra remaining 'indices' that we don't want. # TODO: Implement a better fix # The best way to fix would be to get the UVSet # indices from api with MFnMesh (to ensure we keep # correct ones) and then only force delete the other # entries in the array attribute on the node. # But for now we're deleting all entries except first # one. Note that the first entry could never # be removed (the default 'map1' always exists and is # supposed to be undeletable.) try: for uvSet in deleteUVSets: cmds.polyUVSet(mesh, delete=True, uvSet=uvSet) except RuntimeError, e: cls.log.warning('uvSet: {0} - ' 'Error: {1}'.format(uvSet, e)) indices = cmds.getAttr('{0}.uvSet'.format(mesh), multiIndices=True) if not indices: cls.log.warning( "No uv set found indices for: {0}".format(mesh)) return # Delete from end to avoid shifting indices # and remove the indices in the attribute indices = reversed(indices[1:]) for i in indices: attr = '{0}.uvSet[{1}]'.format(mesh, i) cmds.removeMultiInstance(attr, b=True)
def removeFloatVariable(self, nodeAttr, varslayout, index): # Remove variable children = cmds.columnLayout(varslayout, query=1, childArray=1) if len(children) <= index: return baseNameAttr = nodeAttr baseValueAttr = nodeAttr.replace("fparam_name", "fparam_value"); for i in xrange(index+1, len(children)): rembtn, namefld, _, valfld = cmds.formLayout(children[i], query=1, childArray=1) indexStr = "[%d]" % (i - 1) nextIndexStr = "[%d]" % i nameAttr = baseNameAttr + indexStr valueAttr = baseValueAttr + indexStr cmds.setAttr(nameAttr, cmds.getAttr(baseNameAttr + nextIndexStr), type="string") cmds.setAttr(valueAttr, cmds.getAttr(baseValueAttr + nextIndexStr)); self.setupVariableNameCallback(nameAttr, namefld) self.setupFloatVariableValueCallback(valueAttr, valfld) cmds.button(rembtn, edit=1, command=lambda *args: self.removeFloatVariable(nodeAttr, varslayout, i-1)) cmds.deleteUI(children[index]) cmds.removeMultiInstance("%s[%d]" % (baseNameAttr, len(children)-1), b=True) cmds.removeMultiInstance("%s[%d]" % (baseValueAttr, len(children)-1), b=True)
def createInCurve(self, numCurve, paramRand, offsetRand, centerOffset = 0.4 ): node = self.inCurveNode minValue, maxValue = cmds.getAttr( self._surfShape+'.minMaxRangeV' )[0] if numCurve in [1,2,3]: paramRate = ( maxValue-minValue )/numCurve else: paramRate = ( maxValue-minValue )/(numCurve-1) offsetRand *=0.5 outputCurves = cmds.listConnections( node+'.outputCurve' ) if outputCurves: lenOutputCurves = len( outputCurves ) if lenOutputCurves > numCurve: cmds.delete( outputCurves[numCurve-lenOutputCurves:] ) if not numCurve: return None for i in range( numCurve ): addOffsetParam = random.uniform( -paramRate/2*paramRand, paramRate/2*paramRand ) addOffsetCenter = random.uniform( -offsetRand, offsetRand ) outputCurveCon = cmds.listConnections( node+'.outputCurve[%d]' % i ) if not outputCurveCon: crvNode = cmds.createNode( 'nurbsCurve' ) crvObj = cmds.listRelatives( crvNode, p=1 )[0] cmds.connectAttr( node+'.outputCurve[%d]' % i, crvNode+'.create' ) cmds.addAttr( crvObj, ln='paramRate', dv= paramRate*i + addOffsetParam + paramRate*0.5 ) cmds.setAttr( crvObj+'.paramRate', e=1, k=1 ) cmds.addAttr( crvObj, ln='centerRate', dv= centerOffset+addOffsetCenter ) cmds.setAttr( crvObj+'.centerRate', e=1, k=1 ) cmds.connectAttr( crvObj+'.paramRate', node+'.curveInfo[%d].paramRate' % i ) cmds.connectAttr( crvObj+'.centerRate', node+'.curveInfo[%d].centerRate' % i ) else: crvObj = outputCurveCon[0] cmds.setAttr( crvObj+'.paramRate', paramRate*i + addOffsetParam + paramRate*0.5 ) cmds.setAttr( crvObj+'.centerRate', centerOffset+addOffsetCenter ) crvObj = cmds.rename( crvObj, self._surfObj+'_curve_%d' % i ) if i == numCurve -1: if not numCurve in [2,3]: cmds.setAttr( crvObj+'.centerRate', 0 ) self.setGroup( crvObj ) outputLen = fnc.getLastIndex( node+'.outputCurve' )+1 for i in range( outputLen ): outputCons = cmds.listConnections( node+'.outputCurve[%d]' % i ) if not outputCons: cmds.removeMultiInstance( '%s[%d]' %( node+'.outputCurve', i ) ) cmds.removeMultiInstance( '%s[%d]' %( node+'.curveInfo', i ) )
def clearArray(targetPlug): plugChild = targetPlug.child(0) targetInstances = [] for i in range(plugChild.numElements()): targetInstances.append(plugChild[i].name()) targetInstances.reverse() for i in range(len(targetInstances)): cmds.removeMultiInstance(targetInstances[i])
def __delitem__(self, index): target = "{}[{}]".format(self.attr_name, self._logical_index(index)) sources = cmds.listConnections(target, source=True, plugs=True) or [] for source in sources: cmds.disconnectAttr(source, target) cmds.removeMultiInstance(target, b=True)
def clearArray( targetPlug ): plugChild = targetPlug.child( 0 ) targetInstances = [] for i in range( plugChild.numElements() ): targetInstances.append( plugChild[i].name() ) targetInstances.reverse() for i in range( len( targetInstances ) ): cmds.removeMultiInstance( targetInstances[i] )
def main(): samplerInfoList = cmds.ls(type='samplerInfo') if not samplerInfoList: samplerInfo = cmds.shadingNode('samplerInfo', asUtility=True) else: samplerInfo = samplerInfoList[0] ramp = cmds.shadingNode('ramp', n='fresnel_ramp', asTexture=True) cmds.removeMultiInstance(ramp + '.colorEntryList[2]', b=True)
def clearNoneConnectedElements( targetPlug ): removeTargets = [] for i in range( targetPlug.numElements() ): if not cmds.listConnections( targetPlug[i].name() ): removeTargets.append( targetPlug[i].name() ) for target in removeTargets: cmds.removeMultiInstance( target )
def clearNoneConnectedElements(targetPlug): removeTargets = [] for i in range(targetPlug.numElements()): if not cmds.listConnections(targetPlug[i].name()): removeTargets.append(targetPlug[i].name()) for target in removeTargets: cmds.removeMultiInstance(target)
def deleteBitChild(): # Disconnected the child from it's parent. selList = cmds.ls( selection=True, long=True ) for i in selList: connections = NodeUtility.getNodeAttrDestination( i, 'matrix' ) parent = '{0}.{1}'.format( connections[0], connections[1] ) for plug in connections: if plug.find( 'targetWorldMatrix' ) is not -1: cmds.removeMultiInstance( parent, b=True ) cmds.parent( i, world=True )
def mila_clean(node, indices=None): # Remove all empty entry in the node node = mila_node(node) if indices is None: indices = node.indices() for i in indices: if not node.child(i): cmds.removeMultiInstance(node.multiAttr(i), b=True)
def setSkinWeights(skinCluster, vertJointWeightData): ''' vertJointWeightData is a list of 2-tuples containing the vertex component name, and a list of 2-tuples containing the joint name and weight. ie it looks like this: [ ('someMesh.vtx[0]', [('joint1', 0.25), 'joint2', 0.75)]) , ('someMesh.vtx[1]', [('joint1', 0.2), 'joint2', 0.7, 'joint3', 0.1)]), ... ] ''' #convert the vertex component names into vertex indices idxJointWeight = [] for vert, jointsAndWeights in vertJointWeightData: idx = int(vert[vert.rindex('[') + 1:-1]) idxJointWeight.append((idx, jointsAndWeights)) #get an MObject for the skin cluster node skinFn = API_skinClusterClass(skinCluster) #construct a dict mapping joint names to joint indices jApiIndices = {} _tmp = om.MDagPathArray() skinFn.influenceObjects(_tmp) for n in range(_tmp.length()): jApiIndices[str( _tmp[n].partialPathName())] = skinFn.indexForInfluenceObject( _tmp[n]) weightListP = skinFn.findPlug("weightList") weightListObj = weightListP.attribute() weightsP = skinFn.findPlug("weights") tmpIntArray = om.MIntArray() baseFmtStr = str( skinCluster ) + '.weightList[%d]' #pre build this string: fewer string ops == faster-ness! for vertIdx, jointsAndWeights in idxJointWeight: #we need to use the api to query the physical indices used weightsP.selectAncestorLogicalIndex(vertIdx, weightListObj) weightsP.getExistingArrayAttributeIndices(tmpIntArray) weightFmtStr = baseFmtStr % vertIdx + '.weights[%d]' #clear out any existing skin data - and awesomely we cannot do this with the api - so we need to use a weird ass mel command for n in range(tmpIntArray.length()): mc.removeMultiInstance(weightFmtStr % tmpIntArray[n]) #at this point using the api or mel to set the data is a moot point... we have the strings already so just use mel for joint, weight in jointsAndWeights: if weight: infIdx = jApiIndices[joint] mc.setAttr(weightFmtStr % infIdx, weight)
def remove_sample(self, i): """Remove the sample at index i :param i: Index """ indices = cmds.getAttr("{}.sample".format(self.name), mi=True) or [] if i not in indices: raise RuntimeError("Sample {} does not exist.".format(i)) cmds.removeMultiInstance("{}.sample[{}]".format(self.name, i), all=True, b=True)
def fixRamps(rampNodes): for node in rampNodes: getName, getPos, getCol, getInt = [],[],[],[] typeNode = cmds.nodeType(node) ## if node is remap/ramp change attribute values accordingly if typeNode == 'remapValue': attrValue = '.color' attrPostn = '.color_Position' attrColor = '.color_Color' if typeNode == 'ramp': attrValue = '.colorEntryList' attrPostn = '.position' attrColor = '.color' ## Find all multi attributes, using all these flags because it matches the one from the xml export listAllArray = cmds.listAttr(node + attrValue, read = True, hasData = True, visible = True, scalarAndArray = False, multi = True, output = True) for attr in listAllArray: if '.color_Position' in attr or '.position' in attr: posValues = attr, cmds.getAttr(node + '.' + attr) getPos.append(posValues) getName.append(node) if attr.endswith('.color_Color') or attr.endswith('.color'): colValues = attr, cmds.getAttr(node + '.' + attr) getCol.append(colValues) if typeNode == 'remapValue': if '.color_Interp' in attr: intValues = attr, cmds.getAttr(node + '.' + attr) getInt.append(intValues) ## For each in the list, get according information if first value isn't 0 ## Get position, new position, colour, interpolation (if remap) and connection if any ## Break all the plugs down to 0 and then remake it and reconnect for each in getPos: getPlug = each[0].split('[')[1] getPlug = int(getPlug.split(']')[0]) getPosition = int(getPos.index(each)) if getPlug != int(getPosition): newSpot = getPosition oldSpot = getPlug nodeName = getName[getPosition] newPos = getPos[getPosition][1] colour = getCol[newSpot][1][0] if typeNode == 'remapValue': interp = getInt[newSpot][1] findConn = cmds.connectionInfo( nodeName + attrValue + '[' + str(oldSpot) + ']' + attrColor , sourceFromDestination= True) cmds.removeMultiInstance(nodeName + attrValue + '[' + str(oldSpot) + ']', b = True) cmds.setAttr(nodeName + attrValue + '[' + str(newSpot) + ']' + attrPostn , float(newPos)) cmds.setAttr(nodeName + attrValue + '[' + str(newSpot) + ']' + attrColor , colour[0], colour[1], colour[2], type = 'double3') if typeNode == 'remapValue': cmds.setAttr(nodeName + attrValue + '[' + str(newSpot) + '].color_Interp', interp) try: cmds.connectAttr(findConn, nodeName + attrValue + '[' + str(newSpot) + ']' + attrColor , force = True) except: pass
def CreateEyeLam(colorFile, IncFile, EyeLamName): errorV = 0 if not mc.objExists(EyeLamName): myEyeLam = mc.shadingNode('lambert', asShader=True, n=EyeLamName) myEyeLam_SG = mc.sets(renderable=True, noSurfaceShader=True, empty=True, name=myEyeLam + '_SG') mc.connectAttr('%s.outColor' % myEyeLam, '%s.surfaceShader' % myEyeLam_SG, force=True) myRamp = mm.eval('createRenderNodeCB -as2DTexture "" ramp "";') myColorFile = mm.eval('createRenderNodeCB -as2DTexture "" file "";') mc.setAttr("%s.fileTextureName" % myColorFile, IncFile, type="string") mc.setAttr("%s.colorGain" % myColorFile, 0.85949999094009399, 0.85949999094009399, 0.85949999094009399, type="double3") mc.connectAttr("%s.outColor" % myColorFile, "%s.incandescence" % myEyeLam, f=True) myIncFile = mm.eval('createRenderNodeCB -as2DTexture "" file "";') mc.setAttr("%s.fileTextureName" % myIncFile, colorFile, type="string") mc.connectAttr("%s.outColor" % myIncFile, "%s.color" % myEyeLam, f=True) mc.removeMultiInstance('%s.colorEntryList[2]' % myRamp, b=True) mc.setAttr('%s.colorEntryList[1].position' % myRamp, 0.7149999737739563) mc.setAttr('%s.colorEntryList[0].position' % myRamp, 0.46500000357627869) mc.setAttr('%s.colorEntryList[1].color' % myRamp, 0.0056199943646788597, 0.25346201658248901, 0.28099998831748962, type='double3') mc.setAttr('%s.colorEntryList[0].color' % myRamp, 1.0, 1.0, 1.0, type='double3') mc.setAttr('%s.interpolation' % myRamp, 6) mc.connectAttr("%s.outColor" % myRamp, "%s.colorGain" % myIncFile, f=True) myfilePath1 = mc.getAttr('%s.fileTextureName' % myColorFile) myfilePath2 = mc.getAttr('%s.fileTextureName' % myIncFile) if (not os.path.isfile(r'%s' % myfilePath1)) or (not os.path.isfile( r'%s' % myfilePath2)): errorV = 1 retrunV = [EyeLamName, errorV] return retrunV
def repair(self, instance): """Keep only current UV set and ensure it's the default 'map1'""" meshes = cmds.ls(instance, type='mesh', long=True) for mesh in meshes: uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) currentUVSet = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0] if len(uvSets) != 1: # Copy over to map1 if currentUVSet != 'map1': cmds.polyUVSet(mesh, uvSet=currentUVSet, newUVSet='map1', copy=True) cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1') currentUVSet = 'map1' # Delete all non-current UV sets deleteUVSets = [ uvSet for uvSet in uvSets if uvSet != currentUVSet ] uvSet = None # Maya Bug (present in 2015; not sure if also earlier): # In some cases the API's MFnMesh will report less UV sets than maya.cmds.polyUVSet. # This seems to happen when the deletion of UV sets has not triggered a cleanup of the UVSet array # attribute on the mesh node. It will still have extra entries in the attribute, though it will not # show up in API or UI. Nevertheless it does show up in maya.cmds.polyUVSet. # To ensure we clean up the array we'll force delete the extra remaining 'indices' that we don't want. # TODO: Implement a better fix # ----- The best way to fix would be to get the UVSet indices from api with MFnMesh (to ensure we keep # ----- correct ones) and then only force delete the other entries in the array attribute on the node. # ----- But for now we're deleting all entries except first one. Note that the first entry could never # ----- be removed (the default 'map1' always exists and is supposed to be undeletable.) try: for uvSet in deleteUVSets: cmds.polyUVSet(mesh, delete=True, uvSet=uvSet) except RuntimeError, e: print 'uvSet: {0} - Error: {1}'.format( uvSet, e) # print the error indices = cmds.getAttr('{0}.uvSet'.format(mesh), multiIndices=True) indices = reversed( indices ) # delete from end to avoid shifting indices :) it = iter(indices) next(it) # skip first for i in it: cmds.removeMultiInstance('{0}.uvSet[{1}]'.format( mesh, i), b=True)
def remove_other_uv_sets(mesh): """Remove all other UV sets than the current UV set. Keep only current UV set and ensure it's the renamed to default 'map1'. """ uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) current = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0] # Copy over to map1 if current != 'map1': cmds.polyUVSet(mesh, uvSet=current, newUVSet='map1', copy=True) cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1') current = 'map1' # Delete all non-current UV sets deleteUVSets = [uvSet for uvSet in uvSets if uvSet != current] uvSet = None # Maya Bug (tested in 2015/2016): # In some cases the API's MFnMesh will report less UV sets than # maya.cmds.polyUVSet. This seems to happen when the deletion of UV sets # has not triggered a cleanup of the UVSet array attribute on the mesh # node. It will still have extra entries in the attribute, though it will # not show up in API or UI. Nevertheless it does show up in # maya.cmds.polyUVSet. To ensure we clean up the array we'll force delete # the extra remaining 'indices' that we don't want. # TODO: Implement a better fix # The best way to fix would be to get the UVSet indices from api with # MFnMesh (to ensure we keep correct ones) and then only force delete the # other entries in the array attribute on the node. But for now we're # deleting all entries except first one. Note that the first entry could # never be removed (the default 'map1' always exists and is supposed to # be undeletable.) try: for uvSet in deleteUVSets: cmds.polyUVSet(mesh, delete=True, uvSet=uvSet) except RuntimeError as exc: log.warning('Error uvSet: %s - %s', uvSet, exc) indices = cmds.getAttr('{0}.uvSet'.format(mesh), multiIndices=True) if not indices: log.warning("No uv set found indices for: %s", mesh) return # Delete from end to avoid shifting indices # and remove the indices in the attribute indices = reversed(indices[1:]) for i in indices: attr = '{0}.uvSet[{1}]'.format(mesh, i) cmds.removeMultiInstance(attr, b=True)
def _updateInputs(node, newDict, knownDict, unknownDict): u""" 入力コネクションを更新する。 newDict はチェック処理に使われるため、その内容は維持されない。 """ # まず、変化がないかどうかを簡易的に判断する。 attrs = cmds.listAttr(node + '.i', m=True) or [] n = len(attrs) - len(unknownDict) if n == len(knownDict) and n == len(newDict) and knownDict == newDict: #print('NOT_UPDATED: %s.inputs[]' % node) return False # 既存のプラグをチェックしていく。 updated = False node_ = node + '.' for attr in attrs: idx = int(_RE_PLUG_INDEX.search(attr).group(1)) # 知らないコネクションなら維持する。 if idx in unknownDict: #print('KEEP: ' + node_ + attr) continue # 今後必要になるコネクションか? plug = node_ + attr tgt = newDict.pop(idx, None) if tgt: # 既に同じコネクションが在ればそのまま維持。 if tgt == knownDict.get(idx): #print('NOT_CHANGED: ' + plug) continue # 古いコネクションが在れば、そのまま新規に接続し直す。 #print('CONNECT: %s -> %s' % (tgt, plug)) cmds.connectAttr(tgt, plug, f=True) updated = True # 不要なプラグなら削除。 else: #print('REMOVE: ' + plug) cmds.removeMultiInstance(plug, b=True) updated = True # 未処理のプラグを全てコネクトする。 if newDict: fmt = node + '.i[%d]' for i, tgt in newDict.items(): #print('NEW_CONNECT: %s -> %s' % (tgt, fmt % i)) cmds.connectAttr(tgt, fmt % i, f=True) return True return updated
def deletePoseTarget(self, poseName, targetName): '''Delete pose target''' targetAttr = self.poseTargetAttr(poseName, targetName) # Remove alias aliasAttrs = cmds.aliasAttr(self.name, q=1) or [] envAttr = targetAttr + '.poseTargetEnvelope' for attr in aliasAttrs: if envAttr.endswith(attr): cmds.aliasAttr(envAttr, rm=1) cmds.removeMultiInstance(targetAttr, b=1)
def mila_remove_node(parent=None, index=None): """ remove the node from the destination """ parent = mila_node(parent) node = parent.child(index) attrData = parent.attrData(index) # Disconnect the node cmds.disconnectAttr(node.outAttr(), parent.inAttr(index)) # Delete the item cmds.removeMultiInstance(parent.multiAttr(index), b=True) return node, attrData
def main(): samplerInfoList = cmds.ls(type='samplerInfo') if not samplerInfoList: samplerInfo = cmds.shadingNode('samplerInfo', asUtility=True) else: samplerInfo = samplerInfoList[0] ramp = cmds.shadingNode('ramp', n='fresnel_ramp', asTexture=True) cmds.removeMultiInstance(ramp + '.colorEntryList[2]', b=True) cmds.setAttr(ramp + '.colorEntryList[0].color', 1, 1, 1) # 1つ目のポイントの色 cmds.setAttr(ramp + '.colorEntryList[0].position', 0) #1つ目のポイントの位置 cmds.setAttr(ramp + '.colorEntryList[1].color', 0, 0, 0) #2つ目のポイントの色 cmds.setAttr(ramp + '.colorEntryList[1].position', 0.6) #2つ目のポイントの位置 cmds.connectAttr(samplerInfo + '.facingRatio', ramp + '.vCoord')
def toonRampControl(check, name): pos1 = name +".fbColorScale[3].fbColorScale_Position" pos2 = name +".fbColorScale[2].fbColorScale_Position" cmds.setAttr(pos1, 0.52) if check == 0 : num = 2 if check == 1 : num = 1 cmds.setAttr(pos2, 0.48) for i in range(num): i = i+1 cmds.removeMultiInstance(name+".fbColorScale["+str(i)+"]")
def _updateOutputs(node, newDict, knownDict, unknownDict): u""" 出力コネクションを更新する。 既存の不要なプラグの切断や削除までが行われ、 コネクションの新規作成は行われない。 後で newDict に残されたものを `_connectOutputs` で接続する。 :returns: 何らかの編集が行われたかどうか。 """ # まず、変化がないかどうかを簡易的に判断する。 attrs = cmds.listAttr(node + '.o', m=True) or [] n = len(attrs) - len(unknownDict) if n == len(knownDict) and n == len(newDict) and knownDict == newDict: #print('NOT_UPDATED: %s.outputs[]' % node) newDict.clear() return False # 既存のプラグをチェックしていく。 updated = False node_ = node + '.' for attr in attrs: idx = int(_RE_PLUG_INDEX.search(attr).group(1)) # 知らないコネクションなら維持する。 if idx in unknownDict: #print('KEEP: ' + node_ + attr) continue # 今後必要になるコネクションか? plug = node_ + attr tgt = newDict.get(idx) if tgt: # 既に同じコネクションが在ればそのまま維持。 oldtgt = knownDict.get(idx) if tgt == oldtgt: #print('NOT_CHANGED: ' + plug) del newDict[idx] continue # 古いコネクションなら切断する。 #print('DISCONNECT: %s -> %s' % (plug, oldtgt)) cmds.disconnectAttr(plug, oldtgt) updated = True # 不要なプラグなら削除。 else: #print('REMOVE: ' + plug) cmds.removeMultiInstance(plug, b=True) updated = True return updated
def disconnectMultiAttrib(attrib) : # check if the attribute has any connections and exit if none multiLen=cmds.getAttr('fabricVegetation.'+attrib, size=True) if multiLen==0: print 'FVegetation: No inputs to disconnect for '+attrib+'.' return 1 # otherwise disconnect all the incoming connections for i in range(0, multiLen) : # currently there is a bug where the seeds aren't cleared completely cmds.removeMultiInstance('fabricVegetation.'+attrib+'['+str(i)+']', b=True) return 0
def clearArrayElement( targetAttr ): targetAttrPlug = getPlugFromString( targetAttr ) numElements = targetAttrPlug.numElements() delIndies = [] for i in range( numElements ): logicalIndex = targetAttrPlug[i].logicalIndex() if not cmds.listConnections( targetAttr+'[%d]' % logicalIndex ): delIndies.append( logicalIndex ) for delIndex in delIndies: cmds.removeMultiInstance( '%s[%d]' %( targetAttr, delIndex ) )
def _updateInputs(node, newDict, removeDict): u""" 入力コネクションを更新する。 """ if newDict or removeDict: fmt = node + '.i[%d]' for idx in removeDict: if idx not in newDict: #print('REMOVE: ' + (fmt % idx)) cmds.removeMultiInstance(fmt % idx, b=True) for idx, src in newDict.items(): #print('CONNECT: %s -> %s' % (src, fmt % idx)) cmds.connectAttr(src, fmt % idx, f=True) return True return False
def remove_node_from_bake_node(node): """Used to remove node from rig's bake node list, for example, remove a mesh if meshes are not to be exported Args: node: Object to remove from bakeNodes list of rig node Returns: None """ if cmds.objExists(node): cxns = cmds.listConnections("{}.message".format(node), s=False, d=True, plugs=True) if cxns: for cxn in cxns: if 'bakeNodes' in cxn: cmds.disconnectAttr("{}.message".format(node), cxn) cmds.removeMultiInstance(cxn)
def wipeOutWeights(blendShapeNode=None, correctiveGroup=None, correctiveItem=None, type='wipeTargetWeights'): iTg = '%s.inputTarget[0]' %blendShapeNode iTgGr = '.inputTargetGroup[%s]' %correctiveGroup bsW = '.baseWeights' tW = '.targetWeights' if type == 'wipeTargetWeights': stringList = cmds.listAttr(iTg + iTgGr + tW, m=True) for i in xrange(len(stringList)): cmds.removeMultiInstance(blendShapeNode + '.' + stringList[i]) elif type == 'wipeBaseWeights': stringList = cmds.listAttr(iTg + bsW, m=True) for i in xrange(len(stringList)): #print i cmds.removeMultiInstance(blendShapeNode + '.' + stringList[i])
def createNetwork(): # Create nodeRGBToHSV = cmds.shadingNode('rgbToHsv', asUtility=True) nodeRamp = cmds.shadingNode('ramp', asTexture=True) # Make connections between rgbToHsv and ramp cmds.connectAttr( nodeRGBToHSV+'.outHsvH', nodeRamp+'.uCoord', f=True) cmds.connectAttr( nodeRGBToHSV+'.outHsvV', nodeRamp+'.vCoord', f=True) # Modify ramp cmds.removeMultiInstance( nodeRamp+".colorEntryList[1]", b=True) cmds.setAttr( nodeRamp+".colorEntryList[2].color", 1, 1, 1) cmds.setAttr( nodeRamp+".colorEntryList[0].color", 0, 0, 0) cmds.setAttr( nodeRamp+".colorEntryList[2].position", 1) return nodeRGBToHSV, nodeRamp
def syncNameValueArrays(self, nameAttr, valueAttr, vectorValues=False): count0 = cmds.getAttr(nameAttr, size=1) count1 = cmds.getAttr(valueAttr, size=1) count = (count0 if count0 < count1 else count1) indices0 = cmds.getAttr(nameAttr, multiIndices=1) indices1 = cmds.getAttr(valueAttr, multiIndices=1) if count0 > count1: for i in xrange(count1, count0): cmds.removeMultiInstance("%s[%d]" % (nameAttr, indices0[i]), b=True) indices0 = indices0[0:count1] elif count1 > count0: for i in xrange(count0, count1): cmds.removeMultiInstance("%s[%d]" % (valueAttr, indices1[i]), b=True) indices1 = indices1[0:count0] reorder = False for i in xrange(count): if indices0[i] != i or indices1[i] != i: reorder = True break if reorder: vl = [] rl0 = set() rl1 = set() # Get current name/value pairs and list indices beyond count for i in xrange(count): vl.append((cmds.getAttr("%s[%d]" % (nameAttr, indices0[i])), cmds.getAttr("%s[%d]" % (valueAttr, indices1[i])))) if indices0[i] >= count: rl0.add(indices0[i]) if indices1[i] >= count: rl0.add(indices1[i]) for i in xrange(count): k, v = vl[i] cmds.setAttr("%s[%d]" % (nameAttr, i), k, type="string") if vectorValues: v = v[0] cmds.setAttr("%s[%d]" % (valueAttr, i), *v) else: cmds.setAttr("%s[%d]" % (valueAttr, i), v) for i in rl0: cmds.removeMultiInstance("%s[%d]" % (nameAttr, i), b=True) for i in rl1: cmds.removeMultiInstance("%s[%d]" % (valueAttr, i), b=True) return count
def blendMeshAssign( target, deformObj, driverIndices=[], driverWeights=[], targetIndex=None ): node = fnc.getNodeFromHist( deformObj, 'blendAndFixedShape' ) if not node: node = bc.blendAndFix_toSkin( deformObj ) if not node: node = cmds.deformer( deformObj, type='blendAndFixedShape' )[0] meshObjs = cmds.listConnections( node, s=1, d=0, type='mesh' ) if meshObjs: if target in meshObjs: targetShape = cmds.listRelatives( target, s=1 )[0] attrName = targetShape+'.outMesh' fnNode = om.MFnDependencyNode( fnc.getMObject( node ) ) blendMeshInfoPlugs = fnNode.findPlug( 'blendMeshInfos' ) numElements = blendMeshInfoPlugs.numElements() for i in range( numElements ): inputMeshPlug = blendMeshInfoPlugs[i].child( 0 ) cons = om.MPlugArray() inputMeshPlug.connectedTo( cons, True, False ) if cons.length(): if cons[0].name() == attrName: targetIndex = i cmds.removeMultiInstance( "%s[%d]" %( blendMeshInfoPlugs.name(), targetIndex ) ) print blendMeshInfoPlugs.name(), i, 'is deleted' break if not targetIndex == None: assignNum = targetIndex else: fnNode = om.MFnDependencyNode( fnc.getMObject( node ) ) blendMeshInfoPlug = fnNode.findPlug( 'blendMeshInfos' ) assignNum = blendMeshInfoPlug.numElements() targetShape = cmds.listRelatives( target, s=1 )[0] cmds.connectAttr( targetShape+'.outMesh', node+'.blendMeshInfos[%d].inputMesh' % assignNum ) for i in range( len( driverIndices ) ): index = driverIndices[i] weight = driverWeights[i] cmds.setAttr( node+'.blendMeshInfos[%d].targetWeights[%d]' %( assignNum, index ), weight )
def removeAllVariables(self, nodeAttr, varslayout): nameAttr = nodeAttr valueAttr = nodeAttr.replace("fparam_name", "fparam_value") if valueAttr == nameAttr: valueAttr = nameAttr.replace("vparam_name", "vparam_value") indices = cmds.getAttr(nameAttr, multiIndices=1) for index in indices: cmds.removeMultiInstance("%s[%d]" % (nameAttr, index), b=True) indices = cmds.getAttr(valueAttr, multiIndices=1) for index in indices: cmds.removeMultiInstance("%s[%d]" % (valueAttr, index), b=True) children = cmds.columnLayout(varslayout, query=1, childArray=1) for child in children: cmds.deleteUI(child)
def getWeightAndPast(self, index, indices ): weightListPlugElement = self.weightListPlug.elementByLogicalIndex( index ) plugWeights = weightListPlugElement.child( 0 ) indicesAndValues = [] for i in range( plugWeights.numElements() ): index = plugWeights[i].logicalIndex() value = plugWeights[i].asFloat() indicesAndValues.append( [index,value] ) for vtxIndex in indices: weightListPlugElement = self.weightListPlug.elementByLogicalIndex( vtxIndex ) plugWeights = weightListPlugElement.child( 0 ) for i in range( plugWeights.numElements() ): cmds.removeMultiInstance( plugWeights[0].name() ) for index, value in indicesAndValues: cmds.setAttr( plugWeights.name() + '[%d]' % index, value )
def setJointInfluence( skinCluster, jnt, vtxIndices ): cons = cmds.listConnections( jnt+'.wm', type='skinCluster', c=1, p=1, d=1, s=0 ) if not cons: return None for con in cons: if con.find( skinCluster ) != -1: skinClusterAttr = con fnSkinCluster = om.MFnDependencyNode( getMObject( skinCluster ) ) jntIndex = int( skinClusterAttr.split( '[' )[-1].replace( ']', '' ) ) weightListPlug = fnSkinCluster.findPlug( 'weightList' ) for vtxIndex in vtxIndices: weightListPlugElement = weightListPlug.elementByLogicalIndex( vtxIndex ) weightPlug = weightListPlugElement.child( 0 ) for i in range( weightPlug.numElements() ): cmds.removeMultiInstance( weightPlug[0].name() ) cmds.setAttr( skinCluster+'.weightList[%d].weights[%d]' %( vtxIndex, jntIndex ), 1.0 )
def setArcPositions(arcTracer, arcPositions, pastFrames, futureFrames, currentFrame): futureFrames = futureFrames + currentFrame pastFrames = currentFrame - pastFrames # Sort positions arcPositions = sorted(arcPositions, key=attrgetter('time')) # Set positions based on time. frameCount = 0 for position in arcPositions: if pastFrames <= position.time <= futureFrames: cmd.setAttr('%s.position[%s]' % (arcTracer, frameCount), *position.allData()) frameCount += 1 # Cleanup extra attributes created due to variable sub-frame iterations. numAttrs = cmd.getAttr('%s.position' % arcTracer, size=1) if numAttrs - frameCount > 0: for x in range(frameCount, numAttrs): cmd.removeMultiInstance('%s.position[%s]' % (arcTracer, x))
def delete_Connections_at_targetIndex(self,root,targetIndex,IO_Index ): attributeList = ['recipe'] cnList = ['input', 'output'] storage = mc.listConnections(root+'.'+attributeList[0]) if storage is None: attributeList = ['recipe'] storage = mc.createNode('recipe',n=''.join((root,'_',attributeList[0],'1'))) mc.connectAttr(storage+'.nodeState' ,root+'.'+attributeList[0] ,f=True) else: storage = storage[0] idxList = mc.getAttr(storage+'.'+cnList[IO_Index],mi=True) idx = 0 if idxList is None: return else: targetIndex = idxList[targetIndex] if targetIndex in idxList : mc.removeMultiInstance(storage+'.'+cnList[IO_Index]+'[%s]'%targetIndex,b=True)
def repair(self, instance): """Keep only current UV set and ensure it's the default 'map1'""" meshes = cmds.ls(instance, type='mesh', long=True) for mesh in meshes: uvSets = cmds.polyUVSet(mesh, query=True, allUVSets=True) currentUVSet = cmds.polyUVSet(mesh, query=True, currentUVSet=True)[0] if len(uvSets) != 1: # Copy over to map1 if currentUVSet != 'map1': cmds.polyUVSet(mesh, uvSet=currentUVSet, newUVSet='map1', copy=True) cmds.polyUVSet(mesh, currentUVSet=True, uvSet='map1') currentUVSet = 'map1' # Delete all non-current UV sets deleteUVSets = [uvSet for uvSet in uvSets if uvSet != currentUVSet] uvSet = None # Maya Bug (present in 2015; not sure if also earlier): # In some cases the API's MFnMesh will report less UV sets than maya.cmds.polyUVSet. # This seems to happen when the deletion of UV sets has not triggered a cleanup of the UVSet array # attribute on the mesh node. It will still have extra entries in the attribute, though it will not # show up in API or UI. Nevertheless it does show up in maya.cmds.polyUVSet. # To ensure we clean up the array we'll force delete the extra remaining 'indices' that we don't want. # TODO: Implement a better fix # ----- The best way to fix would be to get the UVSet indices from api with MFnMesh (to ensure we keep # ----- correct ones) and then only force delete the other entries in the array attribute on the node. # ----- But for now we're deleting all entries except first one. Note that the first entry could never # ----- be removed (the default 'map1' always exists and is supposed to be undeletable.) try: for uvSet in deleteUVSets: cmds.polyUVSet(mesh, delete=True, uvSet=uvSet) except RuntimeError, e: print 'uvSet: {0} - Error: {1}'.format(uvSet, e) # print the error indices = cmds.getAttr('{0}.uvSet'.format(mesh), multiIndices=True) indices = reversed(indices) # delete from end to avoid shifting indices :) it = iter(indices) next(it) # skip first for i in it: cmds.removeMultiInstance('{0}.uvSet[{1}]'.format(mesh, i), b=True)
def md_addSelectedAttributesToNode(channelNode): slObjects = cmds.ls(selection=True) slAttributes = cmds.channelBox("mainChannelBox", q=True, selectedMainAttributes=True) childNodes = cmds.listConnections((channelNode + ".output")) # TODO Assert and Warn if nothing selected for node in slObjects: for attr in slAttributes: grandChildName = midiBaseName + node + "_" + attr childNodeName = channelNode + "_" + node + "_" + attr setterName = node + "." + attr channelOutput = channelNode + ".output" childInput = childNodeName + ".inputValue" childOutput = childNodeName + ".outValue" grandchildInput = grandChildName + ".input1D" if childNodes is not None and childNodeName in childNodes: # This is already a child node of the channel continue if not cmds.objExists(grandChildName): cmds.createNode("plusMinusAverage", name=grandChildName, ss=True) cmds.addAttr(grandChildName, longName="setterName", dataType="string") cmds.addAttr(grandChildName, longName="nodeName", dataType="string") cmds.addAttr(grandChildName, longName="attrName", dataType="string") cmds.setAttr((grandChildName + ".setterName"), setterName, type="string") cmds.setAttr((grandChildName + ".nodeName"), node, type="string") cmds.setAttr((grandChildName + ".attrName"), attr, type="string") inputIndex = cmds.getAttr(grandchildInput, size=True) grandchildInput = grandchildInput + "[" + str(inputIndex) + "]" cmds.createNode("remapValue", name=childNodeName, ss=True) cmds.connectAttr(channelOutput, childInput) cmds.connectAttr(childOutput, grandchildInput) attrValue = cmds.getAttr(setterName) cmds.removeMultiInstance((childNodeName + ".value[1]"), b=True) cmds.setAttr((childNodeName + ".value[0].value_FloatValue"), attrValue) cmds.addAttr(childNodeName, longName="setterName", dataType="string") cmds.addAttr(childNodeName, longName="nodeName", dataType="string") cmds.addAttr(childNodeName, longName="attrName", dataType="string") cmds.setAttr((childNodeName + ".setterName"), setterName, type="string") cmds.setAttr((childNodeName + ".nodeName"), node, type="string") cmds.setAttr((childNodeName + ".attrName"), attr, type="string")
def removeUnConnectedIndies( attr, keepIndies = [], childIndies =[] ): nodeName, attrName = attr.split( '.' ) selList = om.MSelectionList() selList.add( nodeName ) mObj = om.MObject() selList.getDependNode( 0, mObj ) fnNode = om.MFnDependencyNode( mObj ) wPlug = fnNode.findPlug( attrName ) if not wPlug.numElements(): return -1 rangeList = range( wPlug.numElements() ) rangeList.reverse() for i in rangeList: try: logicalIndex = wPlug[i].logicalIndex() except: break if logicalIndex in keepIndies: continue connections = om.MPlugArray() if childIndies: for index in childIndies: wPlug[i].child(index).connectedTo( connections, True, False ) if connections.length() == 0: cmds.removeMultiInstance( '%s[%d]' % (attr,logicalIndex) ) else: wPlug[i].connectedTo( connections, True, False ) if connections.length() == 0: cmds.removeMultiInstance( '%s[%d]' % (attr,logicalIndex) )
def clearArrayElement( targetAttr ): targetAttrPlug = getPlugFromString( targetAttr ) numElements = targetAttrPlug.numElements() delIndies = [] for i in range( numElements ): logicalIndex = targetAttrPlug[i].logicalIndex() try: childNum = targetAttrPlug[i].numChildren() except: childNum = 0 if not childNum: if not cmds.listConnections( targetAttr+'[%d]' % logicalIndex ): delIndies.append( logicalIndex ) else: childConnectExists = False for j in range( childNum ): childPlug = targetAttrPlug[i].child( j ) if childPlug.isArray(): if not clearArrayElement( childPlug.name() ): childConnectExists = True else: if cmds.listConnections( childPlug.name() ): childConnectExists = True if not childConnectExists: delIndies.append( logicalIndex ) for delIndex in delIndies: cmds.removeMultiInstance( "%s[%d]" %( targetAttr, delIndex ) ) if getLastIndex( targetAttr ) == -1: return True else: return False
def createCurve( mesh, indices ): cons = cmds.listConnections( mesh+'.outMesh', type='sgVerticeToCurve', d=1, s=0 ) if not cons: vtsToCrv = cmds.createNode( 'sgVerticeToCurve' ) cmds.connectAttr( mesh+'.outMesh', vtsToCrv+'.inputMesh' ) cmds.connectAttr( mesh+'.wm', vtsToCrv+'.inputMeshMatrix' ) targetIndex = 0 else: vtsToCrv = cons[0] cons = cmds.listConnections( vtsToCrv+'.outputCurve', p=1, c=1 ) outputs = cons[::2] targetIndex = int( outputs[-1].split( '[' )[-1].replace( ']', '' ) ) + 1 crv = cmds.createNode( 'nurbsCurve' ) crvObj = cmds.listRelatives( crv, p=1, f=1 )[0] cmds.connectAttr( vtsToCrv+'.outputCurve[%d]' % targetIndex, crv+'.create' ) cmds.connectAttr( crvObj+'.wim', vtsToCrv+'.input[%d].pim' % targetIndex, f=1 ) attrs = cmds.ls( vtsToCrv+'.input[%d].verticeIds[*]' % targetIndex ) for attr in attrs: cmds.removeMultiInstance( attr ) for i in range( len( indices ) ): if indices[i] == 0: indices[i] = -1 cmds.setAttr( vtsToCrv+'.input[%d].verticeIds[%d]' % (targetIndex,i), indices[i] )
def setDeltaBySelected( targetMeshObj, targetIndex, deltaIndices ): if not deltaIndices: return None nodeName = bc.getBlendAndFixedShape(targetMeshObj) fnNode = om.MFnDependencyNode( fnc.getMObject( nodeName ) ) blendMeshInfosPlug = fnNode.findPlug( 'blendMeshInfos' ) elementNum = blendMeshInfosPlug.numElements() if targetIndex >= elementNum: return None deltasPlug = blendMeshInfosPlug[targetIndex].child( 1 ) cuDeltaIndices = [] for i in range( deltasPlug.numElements() ): cuDeltaIndices.append( deltasPlug[i].logicalIndex() ) for deltaIndex in cuDeltaIndices: if not deltaIndex in deltaIndices: cmds.removeMultiInstance( blendMeshInfosPlug[targetIndex].name()+'.deltas[%d]' % deltaIndex )
def set_depth(n): cmds.addAttr(n,ln="close", at="double", min=0) cmds.addAttr(n,ln="far", at="double", min=0) cmds.setAttr(n+".far", 1000,e=True,keyable=True) cmds.setAttr(n+".close",10, e=True,keyable=True) zr = cmds.shadingNode("ramp",n="zDepth_ramp", asTexture=True) zps = cmds.shadingNode("samplerInfo",n="zDepth_samplerInfo",asUtility=True) zdb = cmds.shadingNode("distanceBetween",n="zDepth_distanceBetween",asUtility=True) zsr = cmds.shadingNode("setRange",n="zDepth_setRange",asUtility=True) cmds.removeMultiInstance(zr+'.colorEntryList[1]', b=True) cmds.setAttr(zr+'.colorEntryList[2].color',0,0,0, type='double3') cmds.setAttr(zr+'.colorEntryList[2].position',1) cmds.setAttr(zr+'.colorEntryList[0].color',1,1,1, type='double3') cmds.setAttr(zr+'.interpolation', 3,) cmds.connectAttr(zsr+".outValueX", zr+".vCoord") cmds.connectAttr(zdb+".distance", zsr+".valueX") cmds.connectAttr(zps+".pointCamera",zdb+".point1") cmds.connectAttr(n+".far", zsr+".oldMaxX") cmds.connectAttr(n+".close", zsr+".oldMinX") cmds.connectAttr(zr+".outColor",n+".outColor")