def EvaluateFrames(node, timeAttr, inRenderFrame):
    """
    timeAttr may have expression applied
    EvaluateFrames returns adequatly modified render and sample frames
    """
    timePlug = "%s.%s" % (node, timeAttr)
    outRenderFrame = inRenderFrame
    outSampleFrame = cmds.getAttr(timePlug)
    
    conns = cmds.listConnections(timePlug, s=1, d=0, sh=1, p=1)
    if conns != None:
        restoreConns = []
        srcPlug = conns[0]
        srcNode = srcPlug.split(".")[0]
        hist = cmds.listHistory(srcNode)
        if hist != None:
            for h in hist:
                tconns = cmds.listConnections(h, s=1, d=0, p=1, c=1, type="time")
                if tconns is None:
                    continue
                i = 0
                n = len(tconns)
                while i < n:
                    restoreConns.append((tconns[i+1], tconns[i]))
                    cmds.disconnectAttr(tconns[i+1], tconns[i])
                    cmds.setAttr(tconns[i], inRenderFrame)
                    i += 2
        if len(restoreConns) > 0:
            outRenderFrame = cmds.getAttr(srcPlug)
            for src, dst in restoreConns:
                cmds.connectAttr(src, dst)
   
    return (outRenderFrame, outSampleFrame)
예제 #2
0
def breakReferencePlaceholderConnections(shape):
    """
    Break all reference placeholder connections to the shape.instObjGroups plug.
    @param shape: Shape to break reference placeholder connections from.
    @type shape: str
    """
    # Get Shape Connections
    placeHolderConn = cmds.listConnections(shape, s=True, d=True, p=True, c=True) or []

    # For Each Connection Pair
    for i in range(0, len(placeHolderConn), 2):

        # Check Reference Connection
        placeHolderNode = cmds.ls(placeHolderConn[i + 1], o=True)[0]
        if glTools.utils.reference.isReference(placeHolderNode):

            # Disconnect PlaceHolder
            if cmds.isConnected(placeHolderConn[i], placeHolderConn[i + 1]):
                try:
                    cmds.disconnectAttr(placeHolderConn[i], placeHolderConn[i + 1])
                except:
                    print('FAILED: ' + placeHolderConn[i] + ' >X< ' + placeHolderConn[i + 1] + '!')
                else:
                    print('Disconnected: ' + placeHolderConn[i] + ' >X< ' + placeHolderConn[i + 1] + '...')
            else:
                try:
                    cmds.disconnectAttr(placeHolderConn[i + 1], placeHolderConn[i])
                except:
                    print('FAILED: ' + placeHolderConn[i + 1] + ' >X< ' + placeHolderConn[i] + '!')
                else:
                    print('Disconnected: ' + placeHolderConn[i + 1] + ' >X< ' + placeHolderConn[i] + '...')
예제 #3
0
def removeLocalize(skinClusters):
    """
    If the skinCluster has been localized with multMatrix nodes, remove them
    and reconnect the actual influences.

    :param skinClusters:
    :return: None
    """
    # Remove skinCluster localization
    for sc in skinClusters:
        # The real influences are still connected to the lockWeights attr
        inf_connections = mc.ls(sc + '.lockWeights[*]')
        for inf_con in inf_connections:
            # Get the real influence transform
            inf = rigrepo.libs.common.getFirstIndex(mc.listConnections(inf_con))
            if inf:
                index = rigrepo.libs.common.getIndex(inf_con)
                inf_matrix = sc + '.matrix[' + index + ']'
                localize_node = mc.listConnections(inf_matrix)
                if localize_node:
                    if mc.nodeType(localize_node[0]) == 'multMatrix':
                        mc.connectAttr(inf + '.worldMatrix[0]', inf_matrix, f=1)
                        mc.delete(localize_node)

        # Handle geom matrix
        if mc.listConnections(sc+'.geomMatrix'):
            con = mc.listConnections(sc+'.geomMatrix', p=1)[0]
            mc.disconnectAttr(con, sc+'.geomMatrix')
예제 #4
0
def fixReferenceShaders(refList=None, defaultShader='initialShadingGroup'):
    """
    """
    # Check Reference List
    if not refList: refList = glTools.utils.reference.listReferences()

    # Check Each Reference
    for ref in refList:

        # Initialize Reference Shape List
        shpList = []

        # Check Disconnected Shaders
        c = cmds.listConnections(ref + '.placeHolderList', s=True, d=False, p=True, c=True, sh=True)

        # Check Each Reference Connection
        for i in range(0, len(c), 2):

            # Define Connection Source and Destination
            dst = c[i]
            src = c[i + 1]

            # Check instObjGroups Connections
            if 'instObjGroups' in src:

                # Disconnect placeHolderList Connection
                cmds.disconnectAttr(src, dst)

                # Get Source Shape
                shp = cmds.ls(src, o=True)[0]
                if not shp in shpList:
                    shpList.append(shp)

        # Reconnect to Shader
        if shpList: cmds.sets(shpList, e=True, fe=defaultShader)
예제 #5
0
파일: pMode.py 프로젝트: snaress/studio_dev
def updateOutMesh(srcMesh=None, outMesh=None, force=True):
    """
    Update given outMesh, then remove connection

    :param srcMesh: Source mesh
    :type srcMesh: str
    :param outMesh: Out mesh
    :type outMesh: str
    :param force: Force connection
    :type force: True
    """
    # --- Check Object List ---#
    if srcMesh is None and outMesh is None:
        selObjects = mc.ls(sl=True)
        print selObjects
        if not selObjects:
            print "!!! Error: Select srcMesh, then outMesh !!!"
        else:
            srcMesh = selObjects[0]
            outMesh = selObjects[1]
    # --- Update Mesh ---#
    connectOutMesh(srcMesh, outMesh, force=force)
    mc.refresh()
    mc.disconnectAttr("%s.worldMesh" % srcMesh, "%s.inMesh" % outMesh)
    print "// Update %s.worldMesh ---> %s.inMesh" % (srcMesh, outMesh)
예제 #6
0
def disconnected(targets, testCnxType=("double", "float")):
    if not isinstance(targets, (list, tuple)):
        targets = [targets]
    cnxs = {}
    for target in targets:
        cnx = cmds.listConnections(target,
                                   plugs=True,
                                   destination=False,
                                   source=True,
                                   connections=True)
        if cnx is None:
            cnx = []

        for i in range(0, len(cnx), 2):
            cnxType = cmds.getAttr(cnx[i], type=True)
            if cnxType not in testCnxType:
                continue
            cnxs[cnx[i + 1]] = cnx[i]
            cmds.disconnectAttr(cnx[i + 1], cnx[i])
    try:
        yield cnxs
    finally:
        for s, d in cnxs.iteritems():
            if not cmds.isConnected(s, d):
                cmds.connectAttr(s, d, force=True)
예제 #7
0
 def duplicateObj( self, targetObj, skinNode, addName='_add' ):
     
     if cmds.nodeType( targetObj ) != 'transform':
         targetObj = cmds.listRelatives( targetObj, p=1 )
         
         if targetObj: targetObj = targetObj [0]
         else: return None
     targetShape = cmds.listRelatives( targetObj, s=1 )[0]
     targetAttr = targetShape+'.outMesh'
     outputAttr = cmds.listConnections( skinNode+'.input[0].inputGeometry', s=1, d=0, p=1, c=1 )[1]
     
     secondMesh = cmds.createNode( 'mesh' )
     thirdMesh  = cmds.createNode( 'mesh' )
     
     secondObj = cmds.listRelatives( secondMesh, p=1 )[0]
     thirdObj  = cmds.listRelatives( thirdMesh, p=1 )[0]
     
     cmds.connectAttr( targetAttr, secondMesh+'.inMesh' )
     cmds.connectAttr( outputAttr, thirdMesh +'.inMesh' )
     
     cmds.refresh()
     
     cmds.disconnectAttr( targetAttr, secondMesh+'.inMesh' )
     cmds.disconnectAttr( outputAttr, thirdMesh +'.inMesh' )
     
     secondObj = cmds.rename( secondObj, targetObj+addName )
     thirdObj  = cmds.rename( thirdObj , targetObj+addName+'_inv' )
     
     return secondObj, thirdObj
예제 #8
0
    def connectRenderMeshes(self, uNode, renderMeshes, rewire=1):

        try:

            cmds.undoInfo(openChunk=True)

            if rewire:

                for conn in cmds.listConnections(uNode + '.rendermesh',
                                                 plugs=1,
                                                 destination=1):

                    cmds.disconnectAttr(uNode + '.rendermesh', conn)

            for node in renderMeshes:

                if not attrExists(node + '.export'):

                    cmds.addAttr(node,
                                 longName='export',
                                 attributeType='message')

                cmds.connectAttr(uNode + '.rendermesh', node + '.export')

        except Exception as e:

            print e

        finally:

            cmds.undoInfo(closeChunk=True)
예제 #9
0
def replaceSourceConnection(first, second, nodeType=None):

    if nodeType:
        fSrcCons = cmds.listConnections(first,
                                        s=1,
                                        d=0,
                                        p=1,
                                        c=1,
                                        type=nodeType)
    else:
        fSrcCons = cmds.listConnections(first, s=1, d=0, p=1, c=1)

    if fSrcCons:
        outputs = fSrcCons[1::2]
        inputs = fSrcCons[::2]

        for i in range(len(outputs)):
            inputTarget = inputs[i].replace(first, second)
            if cmds.nodeType(first) == 'joint' and cmds.nodeType(
                    second) == 'transform':
                inputTarget = inputTarget.replace('jointOrient', 'rotate')
            try:
                cmds.connectAttr(outputs[i], inputTarget, f=1)
                cmds.disconnectAttr(outputs[i], inputs[i])
            except:
                pass
예제 #10
0
def shift_mult_matrix_inputs(node, shift):
    if cmds.nodeType(node) != "multMatrix":
        raise RuntimeError(
            "{} is not a multMatrix node.  Unable to shift inputs.".format(
                node))
    if shift == 0:
        return
    indices = cmds.getAttr("{}.matrixIn".format(node), mi=True)
    if not indices:
        return
    if shift > 0:
        indices.reverse()

    for index in indices:
        new_index = index + shift
        if new_index < 0:
            raise RuntimeError("Cannot shift matrix input index < 0")
        plug = "{}.matrixIn[{}]".format(node, index)
        new_plug = "{}.matrixIn[{}]".format(node, new_index)

        # Disconnect any existing connection at the new slot
        existing_connection = cmds.listConnections(new_plug,
                                                   d=False,
                                                   plugs=True)
        if existing_connection:
            cmds.disconnectAttr(existing_connection[0], new_plug)

        connection = cmds.listConnections(plug, d=False, plugs=True)
        if connection:
            cmds.connectAttr(connection[0], new_plug)
        else:
            value = cmds.getAttr(plug)
            cmds.setAttr(new_plug, value, type="matrix")
예제 #11
0
 def connect_utility(self, u_type='md'):
     '''Create utility node connecting source to input and selected
        attributes to output.
        Types: md/reverse.'''
     plugs = self.get_plugs(self.connect_source)
     source_sels = []
     util_nodes = []
     for s, d in plugs:
         u_node = []
         if u_type == 'md':
             u_node = cmds.shadingNode('multiplyDivide',
                                       name='%s_MD' % s.partition('.')[0],
                                       asUtility=True)
             cmds.connectAttr(s, '%s.input1X' % u_node, f=True)
             cmds.connectAttr('%s.outputX' % u_node, d, f=True)
         elif u_type == 'reverse':
             u_node = cmds.shadingNode('reverse',
                                       name='%s_RV' % s.partition('.')[0],
                                       asUtility=True)
             cmds.connectAttr(s, '%s.inputX' % u_node, f=True)
             cmds.connectAttr('%s.outputX' % u_node, d, f=True)
         elif u_type == 'pma':
             u_node = cmds.shadingNode('plusMinusAverage',
                                       name='%s_PMA' % s.partition('.')[0],
                                       asUtility=True)
             cmds.connectAttr(s, '%s.input1D[0]' % u_node, f=True)
             cmds.connectAttr(s, '%s.input1D[1]' % u_node, f=True)
             cmds.disconnectAttr(s, '%s.input1D[1]' % u_node)
             cmds.connectAttr('%s.output1D' % u_node, d, f=True)
         util_nodes.append(u_node)
         source_sels.append(s.rpartition('.')[0])
     #cmds.select(source_sels, r=True)
     return util_nodes
예제 #12
0
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
예제 #13
0
def parentConnect(parent=None, child=None):
    '''
    Specific method for connecting parent / child relationships in a metarig
    
    '''
    #Validation
    if not parent or not child and (len(cmds.ls(sl=1)) == 2):
        parent = cmds.ls(sl=1)[0]
        child = cmds.ls(sl=1)[1]
        
    if not parent or not child:
        return 'Argument Error, Please supply a parent and child node'
    
    if parent in getAllMetaChildren(child):
        return '%s is a meta descendent of %s and cannot also be its parent' % (parent, child)
    
    # Disconnect from old parent's children array
    oldParent = cmds.listConnections('%s.metaParent' % child)
    
    if type(oldParent) == type([]):
        metaChildren = getMetaChildren(oldParent[0])
        childIndex = metaChildren.index(child)
        cmds.disconnectAttr('%s.message' % child, '%s.metaChildren[%s]' % (oldParent[0], childIndex))
    # Connect to new parent's children array
    metaChildren = getMetaChildren(parent)
    cmds.connectAttr('%s.message' % child, '%s.metaChildren[%s]' % (parent, len(metaChildren)))
    
    # Connect new parent
    messageConnect(fromNode=parent, toNode=child, fromName='message', toName='metaParent')
예제 #14
0
def force_visibility_attr(node, name, items):
    attr = attribute.add_visibility_attr(node, name)
    for each in items:
        conn = cmds.listConnections(each + '.v', source=True, destination=False, plugs=True)
        if conn:
            cmds.disconnectAttr(conn[0], each + '.v')
        cmds.connectAttr(attr, each + '.v')
예제 #15
0
def mImportOutkey(keyFile, assetNS, assetName, outAniNode):
	"""
	"""
	inputDict = {}
	jsonFile = keyFile.replace('_outKeys.ma', '_input.json')
	with open(jsonFile, 'r') as json_file:
		inputDict = json.load(json_file)

	imported = False
	outNode = inputDict.keys()[0]
	for inTarget in inputDict[outNode]:
		targetList = cmds.ls('*' + inTarget.split(':')[-1], r= 1, l= 1)
		
		try:
			inNode = [target for target in targetList if target.startswith('|' + assetNS) or target.startswith(assetNS)][0]
		except:
			logger.warning('[' + outAniNode + '] input target not found [' + inTarget.split(':')[-1] + '] -x')
			continue
		
		try:
			inputAni = cmds.listConnections(inNode, p= 1, d= 0, scn= 1)
			if inputAni:
				try:
					cmds.disconnectAttr(inputAni[0], inNode)
					cmds.delete(inputAni[0].split('.')[0])
					logger.warning('viskey PARTIAL deleted. [' + inputAni[0] + ']')
				except:
					logger.warning('viskey PARTIAL delete failed. [' + inputAni[0] + ']')
			if not imported:
				cmds.file(keyFile, i= 1, typ= 'mayaAscii', iv= 1, mnc= 1, ns= ':' + assetName)
				imported = True
			cmds.connectAttr(outAniNode + '.output', inNode)
			logger.info('outNode target connected. [' + outAniNode + '] -> {' + inNode + '}')
		except:
			logger.warning('outNode target connection failed. [' + outAniNode + '] -x {' + inNode + '}')
예제 #16
0
def mImportViskey(keyFile, assetNS, assetName, visAniNode):
	"""
	"""
	visAniMesh = ''
	targetList = cmds.ls('*' + visAniNode.split(':')[-1], r= 1, l= 1)
	
	try:
		visAniMesh = [target for target in targetList if target.startswith('|' + assetNS)][0]
	except:
		logger.warning('viskey target not found [' + visAniNode.split(':')[-1] + '] -x')
		return

	if cmds.objectType(visAniMesh) == 'mesh' and cmds.getAttr(visAniMesh + '.intermediateObject'):
		visAniMesh = cmds.listRelatives(cmds.listRelatives(visAniMesh, p= 1)[0], s= 1, ni= 1, f= 1)[0]
	
	try:
		inputAni = cmds.listConnections(visAniMesh + '.visibility', p= 1, t= 'animCurve')
		if inputAni:
			try:
				cmds.disconnectAttr(inputAni[0], visAniMesh + '.visibility')
				cmds.delete(inputAni[0].split('.')[0])
				logger.warning('viskey PARTIAL deleted. [' + inputAni[0] + ']')
			except:
				logger.warning('viskey PARTIAL delete failed. [' + inputAni[0] + ']')
		cmds.file(keyFile, i= 1, typ= 'mayaAscii', iv= 1, mnc= 1, ns= ':' + assetName)
		cmds.connectAttr(visAniNode + '.output', visAniMesh + '.visibility')
		logger.info('viskey target connected. [' + visAniNode.split(':')[-1] + '] -> {' + visAniMesh + '}')
	except:
		logger.warning('viskey target connection failed. [' + visAniNode.split(':')[-1] + '] -x {' + visAniMesh + '}')
 def createWarp(self, *args):
     terrain = mc.textFieldGrp(self.m_warpTerrainText, query=True, tx=True)
     if (terrain == "") or (self.warpControlPoints == []):
         print "Error. Missing info for the input objects"
     else:
         nodeName = mc.textFieldGrp(self.m_warpNameTextField,
                                    query=True,
                                    tx=True)
         if nodeName == "":
             nodeName = "WarpNode"
         maxCPRadius = mc.floatSliderGrp(self.m_warpMaxRadius,
                                         query=True,
                                         value=True)
         # Create the warp node
         dgModifier = om.MDGModifier()
         warpNode = dgModifier.createNode("WarpNode")
         # Get the name of the node
         dgModifier.doIt()
         nodeName = om.MFnDependencyNode(warpNode).name()
         # Connect the terrain
         mc.connectAttr(terrain + ".worldMesh[0]", nodeName + ".terrain")
         # Set the max radius
         mc.setAttr(nodeName + ".maxRadius", maxCPRadius)
         # Connect all of the control points
         numControlPoints = len(self.warpControlPoints)
         for i in range(numControlPoints):
             mc.connectAttr(self.warpControlPoints[i] + ".translate",
                            nodeName + ".controlPoints[" + str(i) + "]")
             mc.connectAttr(
                 self.warpControlPoints[i] + ".translate",
                 nodeName + ".controlPointsOriginal[" + str(i) + "]")
             mc.disconnectAttr(
                 self.warpControlPoints[i] + ".translate",
                 nodeName + ".controlPointsOriginal[" + str(i) + "]")
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 )
예제 #19
0
    def repair(cls, instance):

        # Use a single undo chunk
        with undo_chunk():
            controls = cmds.sets("controls_SET", query=True)
            for control in controls:

                # Lock visibility
                attr = "{}.visibility".format(control)
                locked = cmds.getAttr(attr, lock=True)
                if not locked:
                    cls.log.info("Locking visibility for %s" % control)
                    cmds.setAttr(attr, lock=True)

                # Remove incoming connections
                invalid_plugs = cls.get_connected_attributes(control)
                if invalid_plugs:
                    for plug in invalid_plugs:
                        cls.log.info("Breaking input connection to %s" % plug)
                        source = cmds.listConnections(plug,
                                                      source=True,
                                                      destination=False,
                                                      plugs=True)[0]
                        cmds.disconnectAttr(source, plug)

                # Reset non-default values
                invalid_plugs = cls.get_non_default_attributes(control)
                if invalid_plugs:
                    for plug in invalid_plugs:
                        attr = plug.split(".")[-1]
                        default = cls.CONTROLLER_DEFAULTS[attr]
                        cls.log.info("Setting %s to %s" % (plug, default))
                        cmds.setAttr(plug, default)
예제 #20
0
def xfer(srcGeom, dstGeom, smooth=False, uv=False, rui=False):
    srcSkin = mel.eval('findRelatedSkinCluster("' + srcGeom + '")')
    if cmds.objExists(srcSkin):
        srcInfs = cmds.skinCluster(srcSkin, q=True, inf=True)
        dstSkin = mel.eval('findRelatedSkinCluster("' + dstGeom + '")')
        if dstSkin:
            cmds.delete(dstSkin)
        dstSkin = cmds.skinCluster(srcInfs,
                                   dstGeom,
                                   n=dstGeom + '_skinCluster',
                                   tsb=True)[0]

        cmds.copySkinWeights(ss=srcSkin,
                             ds=dstSkin,
                             sa='closestPoint',
                             ia='oneToOne',
                             nm=True,
                             sm=smooth)

        cmds.connectAttr(srcSkin + '.skinningMethod',
                         dstSkin + '.skinningMethod',
                         f=True)
        cmds.disconnectAttr(srcSkin + '.skinningMethod',
                            dstSkin + '.skinningMethod')

        return (dstSkin)
    else:

        return (None)
예제 #21
0
    def createAimObject(aimTarget, upObject, constTarget):

        aimObjectMatrix = cmds.createNode('aimObjectMatrix')
        cmds.connectAttr(aimTarget + '.wm', aimObjectMatrix + '.targetMatrix')
        cmds.connectAttr(upObject + '.wm', aimObjectMatrix + '.baseMatrix')

        if cmds.nodeType(constTarget) == 'joint':
            try:
                cmds.setAttr(constTarget + '.jo', 0, 0, 0)
            except:
                pass

        cmds.connectAttr(aimObjectMatrix + '.outRotate',
                         constTarget + '.r',
                         f=1)
        cmds.setAttr(aimObjectMatrix + '.worldSpaceOutput', 1)
        cmds.connectAttr(constTarget + '.pim',
                         aimObjectMatrix + '.parentInverseMatrix',
                         f=1)
        cons = getAttrSourceConnection(constTarget + '.t')
        if cons:
            for i in range(0, len(cons), 2):
                outputCon = cons[i + 1]
                inputCon = upObject + '.' + cons[i + 0].split('.')[-1]
                cmds.connectAttr(outputCon, inputCon)
                cmds.disconnectAttr(cons[i + 1], cons[i])

        cmds.connectAttr(aimObjectMatrix + '.outTranslate',
                         constTarget + '.t',
                         f=1)

        return aimObjectMatrix
예제 #22
0
def duplicateOnlyCurve(curves):

    import sgBFunction_dag
    curves = sgBFunction_dag.getChildrenCurveExists(curves)

    newCurves = []
    for curve in curves:
        curveP = sgBFunction_dag.getParent(curve)
        if curveP:
            newCurveParent = sgBFunction_dag.makeCloneObject(curveP)
        else:
            newCurveParent = None

        newCurveShape = cmds.createNode('nurbsCurve')
        curveShape = sgBFunction_dag.getShape(curve)
        cmds.connectAttr(curveShape + '.local', newCurveShape + '.create')

        newCurve = sgBFunction_dag.getTransform(newCurveShape)
        newCurve = cmds.rename(newCurve, 'du_' + curve.split('|')[-1])
        if newCurveParent:
            newCurve = cmds.parent(newCurve, newCurveParent)[0]
        newCurves.append(newCurve)

    cmds.refresh()

    for i in range(len(newCurves)):
        curveShape = sgBFunction_dag.getShape(curves[i])
        newCurveShape = sgBFunction_dag.getShape(newCurves[i])
        if cmds.isConnected(curveShape + '.local', newCurveShape + '.create'):
            cmds.disconnectAttr(curveShape + '.local',
                                newCurveShape + '.create')

    return newCurves
예제 #23
0
파일: wrap.py 프로젝트: auqeyjf/glTools
def create(geo,wrapGeo,worldSpace=True,prefix=''):
	'''
	Create a wrap deformer using the specified geometry
	@param geo: Geometry to deform
	@type geo: str
	@param wrapGeo: Wrap deformer influence geometry
	@type wrapGeo: str
	@param prefix: Naming prefix
	@type prefix: str
	'''
	# Build/Store Selection
	sel = mc.ls(sl=1)
	mc.select(geo,wrapGeo)
	
	# Create Wrap Deformer
	mm.eval('CreateWrap')
	wrap = mc.ls(mc.listHistory(geo),type='wrap')[0]
	wrap = mc.rename(wrap,prefix+'_wrap')
	
	# World/Local Space Deformation
	if not worldSpace:
		geomMatrixInput = mc.listConnections(wrap+'.geomMatrix',s=True,d=False,p=True)
		if geomMatrixInput: mc.disconnectAttr(geomMatrixInput[0],wrap+'.geomMatrix')
	
	# Clean Base
	cleanWrapBase(wrap)
	
	# Restore Selection
	if sel: mc.select(sel)
	
	# Return Result
	return wrap
예제 #24
0
def parentConnect(parent=None, child=None):
    '''
    Specific method for connecting parent / child relationships in a metarig
    
    '''
    #Validation
    if not parent or not child and (len(cmds.ls(sl=1)) == 2):
        parent = cmds.ls(sl=1)[0]
        child = cmds.ls(sl=1)[1]

    if not parent or not child:
        return 'Argument Error, Please supply a parent and child node'

    if parent in getAllMetaChildren(child):
        return '%s is a meta descendent of %s and cannot also be its parent' % (
            parent, child)

    # Disconnect from old parent's children array
    oldParent = cmds.listConnections('%s.metaParent' % child)

    if type(oldParent) == type([]):
        metaChildren = getMetaChildren(oldParent[0])
        childIndex = metaChildren.index(child)
        cmds.disconnectAttr('%s.message' % child,
                            '%s.metaChildren[%s]' % (oldParent[0], childIndex))
    # Connect to new parent's children array
    metaChildren = getMetaChildren(parent)
    cmds.connectAttr('%s.message' % child,
                     '%s.metaChildren[%s]' % (parent, len(metaChildren)))

    # Connect new parent
    messageConnect(fromNode=parent,
                   toNode=child,
                   fromName='message',
                   toName='metaParent')
예제 #25
0
    def connectShape(self, shape, mesh=None, live=False, delete=False):
        """ Force a shape to match a mesh
			The "connect shape" button is:
				mesh=None, delete=True
			The "match shape" button is:
				mesh=someMesh, delete=False
			There is a possibility of a "make live" button:
				live=True, delete=False
		"""
        if mesh is None:
            attrName = cmds.attributeName(shape.thing, long=True)
            mesh = "{0}_Extract".format(attrName)

        if not cmds.objExists(mesh):
            return

        index = self._getShapeIndex(shape)
        tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(
            self.shapeNode, index)
        outAttr = "{0}.worldMesh[0]".format(mesh)
        inAttr = "{0}.inputTargetItem[6000].inputGeomTarget".format(tgn)
        if not cmds.isConnected(outAttr, inAttr):
            cmds.connectAttr(outAttr, inAttr, force=True)

        if not live:
            cmds.disconnectAttr(outAttr, inAttr)
        if delete:
            cmds.delete(mesh)
예제 #26
0
def delete(renderLayer):
    """Remove the argument render layer from the scene.

    All overrides and collections in the render layer are
    removed."""

    # At time of writing (18-Jun-2015), no render layer overrides.
    # Collections detach themselves on delete.
    for child in renderLayer.getCollections():
        collection.delete(child)
    
    # Inform our parent (if any) of upcoming delete.
    parent = renderLayer.parent()
    if parent:
        parent._preRenderLayerDelete(renderLayer)

    # Keep an access to the legacy render layer node instance
    legacyRenderLayerName = renderLayer._getLegacyNodeName()
    
    # First disconnect from the render layer
    cmds.disconnectAttr(legacyRenderLayerName + '.msg', renderLayer.name() + '.lrl')

    # Second delete the legacy render layer
    legacyLayer.delete(legacyRenderLayerName)

    # Third delete the render layer
    utils.deleteNode(renderLayer)
예제 #27
0
def edo_transferMesh():
    sels = cmds.ls(sl=1)
    if sels == None or sels == []:
        cmds.confirmDialog(title='error',
                           message='you must select something',
                           button='god it',
                           defaultButton='Yes',
                           cancelButton='No',
                           dismissString='No')
        return False
    if not len(sels) >= 2:
        cmds.confirmDialog(title='error',
                           message='you must select more than two mesh',
                           button='god it',
                           defaultButton='Yes',
                           cancelButton='No',
                           dismissString='No')
        return False
    sc = sels[0]
    dt = sels[1]
    input = cmds.listConnections(dt + '.inMesh', s=1, d=0)
    if not input == None:
        cmds.confirmDialog(title='error',
                           message='the direct mesh is connected,check it!',
                           button='god it',
                           defaultButton='Yes',
                           cancelButton='No',
                           dismissString='No')
        return False
    else:
        edo_setMeshVertexsZero(dt)
        cmds.connectAttr(sc + '.outMesh', dt + '.inMesh', f=1)
        edo_setMeshVertexsZero(dt)
        cmds.disconnectAttr(sc + '.outMesh', dt + '.inMesh')
예제 #28
0
 def sk_bakeStereoCameraConnect(self,source,target):
     # needAttrs
     needAttrs = ['filmFit','focalLength','horizontalFilmAperture','verticalFilmAperture','overscan','interaxialSeparation','zeroParallax']
     for attr in needAttrs:
         sourceAttr = '%s.%s'%(source,attr)
         targetAttr = '%s.%s'%(target,attr)
         checkNodeType = mc.nodeType(target)
         if checkNodeType in ['stereoRigFrustum'] and not mc.ls(targetAttr):
             continue
         if attr in ['interaxialSeparation','zeroParallax'] and not mc.ls(sourceAttr):
             continue
         cons = mc.listConnections(targetAttr,s=1,d=0)
         if cons:
             continue
         mc.setAttr(targetAttr,mc.getAttr(sourceAttr))
     # 初始化
     checkNodeType = mc.nodeType(source)
     if checkNodeType in ['stereoRigFrustum']:
         return
     attrs = mc.listAttr(source,write = 1,connectable = 1)
     for attr in attrs:
         sourceAttr = '%s.%s'%(source,attr)
         targetAttr = '%s.%s'%(target,attr)
         if not mc.ls(targetAttr):
             continue
         cons = mc.listConnections(targetAttr,destination = 0,s=1)
         if not cons:
             continue
         try:
             mc.disconnectAttr(sourceAttr,targetAttr)
         except:
             pass
     # 连接
     attrs = mc.listConnections(source,connections = 1,plugs = 1,destination = 0,s=1)
     if not attrs:
         return
     for i in range(len(attrs)/2):
         sourceAttr = attrs[2*i+1]
         checkKey = source.split('|')[-1]
         checkSource =  sourceAttr.split('|')[-1].split('.')[0]
         if checkSource == checkKey:
             continue
         targetAttr = ('%s.%s')%(target,attrs[2*i].split('.')[-1])
         cons = mc.listConnections(targetAttr,s=1,d=0,plugs = 1)
         if cons:
             if sourceAttr == cons[0]:
                 continue
         mc.connectAttr(sourceAttr,targetAttr,f=1)
     # 属性
     addAttrList = ['displayFilmGate','displayResolution','displayGateMask','displayFieldChart','stereo']
     addAttrList +=['displaySafeAction','displaySafeTitle','displayFilmPivot','displayFilmOrigin','overscan']
     for checkAttr in addAttrList:
         sourceAttr = '%s.%s'%(source,checkAttr)
         targetAttr = '%s.%s'%(target,checkAttr)
         if not mc.ls(sourceAttr):
             continue
         cons = mc.listConnections(targetAttr,s=1,d=0,plugs =1)
         if cons:
             mc.disconnectAttr(cons[0],targetAttr)
         mc.setAttr(targetAttr,mc.getAttr(sourceAttr))
예제 #29
0
def make_path():
    global final_loc

    # 首选原点物体, 后选运动物体
    check_selection_obj()
    # 按选择顺序创建LOCATOR, 并且约束到相同的位移
    zero_loc = mc.spaceLocator(n='loc_o', p=[0.0, 0.0, 0.0])
    new_loc = mc.spaceLocator(n='loc_move', p=[0.0, 0.0, 0.0])
    mc.pointConstraint(first_full_name, zero_loc[0])
    mc.orientConstraint(first_full_name, zero_loc[0])
    mc.pointConstraint(last_full_name, new_loc[0])
    mc.orientConstraint(last_full_name, new_loc[0])
    # 将运动物体的LOC父子关系到原点物体的LOC
    mc.parent(new_loc[0], zero_loc[0])
    # 创建一个新的LOC, 作为最终LOC
    loc = mc.spaceLocator(n='final_motion_loc', p=[0.0, 0.0, 0.0])
    # 连接属性
    mc.connectAttr('%s.translate' % new_loc[0], '%s.translate' % loc[0], f=True)
    mc.connectAttr('%s.rotate' % new_loc[0], '%s.rotate' % loc[0], f=True)
    st = mc.playbackOptions(q=True, min=True)
    et = mc.playbackOptions(q=True, max=True)
    # BAKE ATTRIBUTE
    mc.bakeResults(sm=True, sb=True, dic=True, pok=True, sac=False, ral=False,
                   bol=False, cp=False, s=False, t=(st, et))
    mc.disconnectAttr('%s.translate' % new_loc[0], '%s.translate' % loc[0])
    mc.disconnectAttr('%s.rotate' % new_loc[0], '%s.rotate' % loc[0])
    final_loc = loc[0]
예제 #30
0
 def importAssetCache(self, cacheXmlLt, cacheErrorCheck = False):
     """ cacheXmlLt = "R:/data/cache/sq001/sh001/light/char/ben00c_ben/ben00c_ben.xml" """
     if os.path.exists(cacheXmlLt):
         cacheChannels = mc.cacheFile(fileName=cacheXmlLt,q=1,channelName=1)
         cacheGeos = self.getCacheGeos()
         cacheGeoDict, cacheChannelsTmp = {}, []
         for chn in cacheChannels:
             for geo in cacheGeos:
                 baseChn = utils.stripNames(utils.convertName(chn, "texture"))
                 baseGeo = utils.stripNames(utils.stripNames(geo, ":"), "|")
                 if baseChn in baseGeo:
                     cacheGeoDict[chn] = geo
                     cacheChannelsTmp.append(chn)
                     continue
     else:
         utils.msgWin("Error", "File does not exist : %s"%cacheXmlLt, self.silent)
         return False
     if cacheErrorCheck:
         missedChannels = list(set(cacheChannels).difference(set(cacheGeoDict.keys())))
         if len(missedChannels) > 0:
             msg = "Cache geometry missing\n"
             msg += "\n".join(missedChannels)
             utils.msgWin("Error", msg, self.silent)
             return missedChannels
         else:
             return False
     for chNode in self.getCacheNodes():
         mc.delete(chNode)
     for chn in cacheGeoDict.keys():
         deformShp = cacheGeoDict[chn]
         try:
             shpSwitch = mc.deformer(deformShp, type="historySwitch")
         except:
             continue
         shpHist = mc.listHistory(deformShp, pdo=1)
         if shpHist:
             for hist in shpHist:
                 if mc.nodeType(hist) == "tweak":
                     dblList = mc.listAttr("%s.plist"%hist, m= 1)
                     fltList = mc.listAttr("%s.vlist"%hist, m= 1)
                     dbCon, flCon = False, False
                     if dblList:
                         if len(dblList) > 1: dbCon = True
                     if fltList:
                         if len(fltList) > 1: flCon = True
                     if not(dbCon or flCon):
                         mc.delete(hist)
                     break
         conns = mc.listConnections("%s.ip[0].ig"%shpSwitch[0], p=1)
         mc.connectAttr(conns[0], "%s.ug[0]"%shpSwitch[0])
         mc.setAttr("%s.playFromCache"%shpSwitch[0], 1)
         mc.getAttr("%s.op[0]"%shpSwitch[0], sl = 1)
         mc.setAttr("%s.playFromCache"%shpSwitch[0], 0)
         mc.disconnectAttr(conns[0], "%s.ug[0]"%shpSwitch[0])
         switch = mc.rename(shpSwitch[0],'cacheSwitch#')
         mc.setAttr(switch+'.ihi',0)
         cacheNode = mc.cacheFile(f = cacheXmlLt, attachFile = True, ia = '%s.inp[0]'%switch, cnm = chn)
         mc.connectAttr(cacheNode+".inRange", switch + '.playFromCache')
     utils.msgWin("Message", "Cache loaded successfully for %s"%self.namespace, self.silent)
     return True
예제 #31
0
def saveControlShapes(filepath, controls=None):

	if not controls: controls = mc.ls(sl=True, o=True) or []
	c = len(controls)
	if c == 0: return

	l = [None]*c
	for i in range(c):
		if not mc.objExists(controls[i]+".worldSpace"): continue
		l[i] = mc.curve(d=1, p=(0,0,0), k=(0))
		mc.connectAttr(controls[i]+".worldSpace", l[i]+".create")
		shape = mc.listRelatives(controls[i], pa=True, s=True)[0]
		mc.setAttr(l[i]+".overrideEnabled", True)
		mc.setAttr(l[i]+".overrideColor", mc.getAttr(shape+".overrideColor"))
		l[i] = mc.rename(l[i], controls[i])

	mc.dgdirty(a=True)

	for i in range(len(l)):
		na = mc.listConnections(l[i]+".create", s=True, d=False, p=True)[0]
		mc.disconnectAttr(na, l[i]+".create")

	mc.select(l)
	mc.file(filepath, f=True, op="v=0;", typ="mayaAscii", es=True)
	mc.delete(l)
	print("Result: "+filepath)
예제 #32
0
def getSourceCurveAttr( shape ):
    
    cons = cmds.listConnections( shape+'.create', s=1, d=0, p=1, c=1 )
    shapeP = cmds.listRelatives( shape, p=1 )[0]
    
    if not cons:
        
        duObj = cmds.duplicate( shape )[0]
        duShapes = cmds.listRelatives( duObj, s=1, f=1 )
        
        targetOrig = ''
        for duShape in duShapes:
            if not cmds.getAttr( duShape+'.io' ):
                targetOrig = duShape
                break
        
        cmds.setAttr( targetOrig+'.io', 1 )
        targetOrig = cmds.parent( targetOrig, shapeP, s=1, add=1 )[0]
        
        cmds.delete( duObj )
        
        cons = cmds.listConnections( shape+'.controlPoints', p=1, c=1, s=1, d=0 )
        if cons:
            for i in range( 0, len( cons ), 2 ):
                cmds.connectAttr( cons[i+1], cons[i].replace( shape, targetOrig ) )
                cmds.disconnectAttr( cons[i+1], cons[i] )
            
        return targetOrig+'.local'
        
    else:
        return cons[1]
예제 #33
0
def no_display_layers(node_list):
    """
    remove DAG nodes connection with displayLayer
    """
    cmds.undoInfo(ock=True)

    # remove `displayLayerManager` type node
    invalid = set(cmds.ls(node_list, type="displayLayerManager"))
    node_list = [x for x in node_list if x not in invalid]
    # get connections with `displayLayer` type node
    conn_pair = cmds.listConnections(
        node_list, connections=True, plugs=True, type="displayLayer") or []

    try:
        # connection list *conn_pair* must be pairable
        # [source, destination, src, dst, ...]
        assert len(conn_pair) % 2 == 0
        # remove connection
        for i in range(0, len(conn_pair), 2):
            cmds.disconnectAttr(conn_pair[i + 1], conn_pair[i])
        yield
    except AssertionError:
        cmds.warning("This is a bug. The connection list is not pairable.")
    finally:
        cmds.undoInfo(cck=True)
        cmds.undo()
def _disable_editing_for_deformer(deformer):
    # Select the inverted blend shape, so we're symmetrical with what enable_editing does.
    # That way, enable_editing and disable_editing toggles back and forth cleanly.
    inverted_mesh_shape = _find_inverted_shape_for_deformer(deformer)
    inverted_mesh = cmds.listRelatives(inverted_mesh_shape, p=True, path=True)[0]
    cmds.select(inverted_mesh)
    
    posed_mesh = _get_active_sculpting_mesh_for_deformer(deformer)
    if not posed_mesh:
        OpenMaya.MGlobal.displayWarning('%s isn\'t enabled for editing' % deformer)

        # Don't show the "disabled editing" message, so it doesn't imply that it was
        # actually enabled before.
        return False

    # .tweak[0] is connected to posed_mesh's .tweakLocation.  Disconnect this connection.
    cmds.disconnectAttr('%s.tweak[0]' % deformer, '%s.tweakLocation' % posed_mesh)

    # If we have a .savedTweakConnection, connect posed_mesh's .tweakLocation back to it.
    saved_tweak_connection = cmds.listConnections('%s.savedTweakConnection[0]' % deformer, p=True)
    if saved_tweak_connection:
        print 'Restoring', saved_tweak_connection
        saved_tweak_connection = saved_tweak_connection[0]
        cmds.connectAttr(saved_tweak_connection, '%s.tweakLocation' % posed_mesh)
        cmds.disconnectAttr(saved_tweak_connection, '%s.savedTweakConnection[0]' % deformer)

    cmds.setAttr('%s.enableTweak' % deformer, False)

    return True
예제 #35
0
def facialRenderConnect(connect=False): 
    nodeKey = 'facialRender_lt'
    targetAttr = '.color'
    connectKey = 'tmpFacialConnect'

    if not connect: 
        if mc.objExists(nodeKey): 
            srcNode = '%s.outColor' % nodeKey
            dstNodes = mc.listConnections(srcNode, s = False, d = True, p = True)
            
            if dstNodes: 
                dstNodeAttr = dstNodes[0]
                dstNode = dstNodeAttr.split('.')[0]

                mc.disconnectAttr(srcNode, dstNodeAttr)
                mc.rename(dstNode, '%s_%s' % (dstNode, connectKey))

    else: 
        targetShd = mc.ls('*_%s' % connectKey)

        if targetShd and mc.objExists(nodeKey): 
            queryNode = mc.listConnections('%s.color' % targetShd[0], s=True, d=False, p=True)
            
            if not queryNode: 
                mc.connectAttr('%s.outColor' % nodeKey, '%s.color' % targetShd[0], f=True)
                mc.rename(targetShd[0], targetShd[0].replace('_%s' % connectKey, ''))
예제 #36
0
파일: leg.py 프로젝트: lazerdaze/lancer
    def createToeFKIK(self):
        pc = cmds.parentConstraint(self.toeFKControl,
                                   self.toeIKControl,
                                   self.toe,
                                   n='{}_fkik_pc0'.format(self.toe),
                                   mo=True)[0]

        for axis in ['X', 'Y', 'Z']:
            cmds.disconnectAttr('{}.constraintTranslate{}'.format(pc, axis),
                                '{}.translate{}'.format(self.toe, axis))

        pcAttr = cmds.parentConstraint(pc, q=True, wal=True)
        cmds.connectAttr('{}.{}'.format(self.master, Component.fkik),
                         '{}.{}'.format(pc, pcAttr[-1]),
                         f=True)

        reverse = cmds.createNode('reverse', n='{}_fkik_re0'.format(self.toe))
        cmds.connectAttr('{}.{}'.format(self.master, Component.fkik),
                         '{}.inputX'.format(reverse),
                         f=True)
        cmds.connectAttr('{}.outputX'.format(reverse),
                         '{}.{}'.format(pc, pcAttr[0]),
                         f=True)
        cmds.connectAttr('{}.outputX'.format(reverse),
                         '{}.v'.format(self.toeFKGroup),
                         f=True)
        return
예제 #37
0
def updateRestShape(mesh, newRest, window=None):
    allShapes = cmds.listRelatives(mesh, children=1, shapes=1) or []
    noInter = cmds.listRelatives(mesh, children=1, shapes=1,
                                 noIntermediate=1) or []
    hist = cmds.listHistory(mesh)
    inter = (set(allShapes) - set(noInter)) & set(hist)
    if not inter:
        if window is not None:
            QMessageBox.warning(window, "No Intermediates",
                                "No intermediate meshes found")
        return
    inter = list(inter)

    if len(inter) == 1:
        orig = inter[0]
    else:
        origs = [i for i in inter if 'Orig' in i]
        if len(origs) != 1:
            if window is not None:
                QMessageBox.warning(
                    window, "Too Many Intermediates",
                    "Too Many intermediate meshes found: {0}".format(origs))
            return
        orig = origs[0]

    outMesh = '{0}.worldMesh[0]'.format(newRest)
    inMesh = '{0}.inMesh'.format(orig)

    cmds.connectAttr(outMesh, inMesh, force=1)
    cmds.refresh(force=1)
    cmds.disconnectAttr(outMesh, inMesh)
    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)
예제 #39
0
    def connectRoot(self, uNode, root, rewire=1):

        try:

            cmds.undoInfo(openChunk=True)

            if rewire:

                conns = cmds.listConnections(uNode + '.export_root',
                                             plugs=1,
                                             source=1)

                if conns:

                    for conn in conns:

                        cmds.disconnectAttr(conn, uNode + '.export_root')

            if not attrExists(root + '.export'):

                cmds.addAttr(root, longName='export', attributeType='message')

            cmds.connectAttr(root + '.export', uNode + '.export_root')

        except Exception as e:

            print e

        finally:

            cmds.undoInfo(closeChunk=True)
예제 #40
0
def copy_curves(curves):
    """
    This is a clean curve copy. It create a new node and transfer the vertexes
    value from the original one to the copy
    """
    copies = []
    connections = []
    for curve in curves:
        copy = mc.createNode('nurbsCurve')
        copies.append(copy)
        out_attr = '{}.worldSpace[0]'.format(curve)
        in_attr = '{}.create'.format(copy)
        connections.append([out_attr, in_attr])
        mc.connectAttr(out_attr, in_attr)
        # match the transforms
        parent = mc.listRelatives(curve, parent=True)[0]
        matrix = mc.xform(parent, query=True, worldSpace=True, matrix=True)
        copy_parent = mc.listRelatives(copy, parent=True)[0]
        mc.xform(copy_parent, worldSpace=True, matrix=matrix)
    # cause i'm too lazy to parse vertexes with OpenMaya Api, I just connect
    # the output from the original ones to the new input.
    # After I disconnect cause this create a independent copy.
    # The refresh is needed to force maya to store the data in the new node.
    mc.refresh()
    for out_attr, in_attr in connections:
        mc.disconnectAttr(out_attr, in_attr)
    return copies
예제 #41
0
def separateParentConnection(node, attr):

    parentAttr = cmds.attributeQuery(attr, node=node, listParent=1)

    if parentAttr:
        cons = cmds.listConnections(node + '.' + parentAttr[0],
                                    s=1,
                                    d=0,
                                    p=1,
                                    c=1)
        if cons:
            cmds.disconnectAttr(cons[1], cons[0])
            srcAttr = cons[1]
            srcNode, srcParentAttr = srcAttr.split('.')
            srcAttrs = cmds.attributeQuery(srcParentAttr,
                                           node=srcNode,
                                           listChildren=1)
            dstAttrs = cmds.attributeQuery(parentAttr[0],
                                           node=node,
                                           listChildren=1)
            for i in range(len(srcAttrs)):
                if cmds.connectAttr(srcNode + '.' + srcAttrs[i],
                                    node + '.' + dstAttrs[i]):
                    continue
                cmds.connectAttr(srcNode + '.' + srcAttrs[i],
                                 node + '.' + dstAttrs[i],
                                 f=1)
예제 #42
0
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)
예제 #43
0
파일: plug.py 프로젝트: hal1932/pm2
 def disconnect(self, plug):
     if plug is str:
         plug = Plug.fromName(plug)
     if plug.isArray:
         mc.disconnectAttr(self.name, plug.name, nextAvailable = True)
     else:
         mc.disconnectAttr(self.name, plug.name)
예제 #44
0
def duplicateOnlyCurve( curves ):
    
    import sgBFunction_dag
    curves = sgBFunction_dag.getChildrenCurveExists( curves )
    
    newCurves = []
    for curve in curves:
        curveP = sgBFunction_dag.getParent( curve )
        if curveP:
            newCurveParent = sgBFunction_dag.makeCloneObject( curveP )
        else:
            newCurveParent = None
        
        newCurveShape = cmds.createNode( 'nurbsCurve' )
        curveShape = sgBFunction_dag.getShape( curve )
        cmds.connectAttr( curveShape+'.local', newCurveShape+'.create' )
        
        newCurve = sgBFunction_dag.getTransform( newCurveShape )
        newCurve = cmds.rename( newCurve, 'du_' + curve.split( '|' )[-1] )
        if newCurveParent:
            newCurve = cmds.parent( newCurve, newCurveParent )[0]
        newCurves.append( newCurve )
    
    cmds.refresh()
    
    for i in range( len( newCurves ) ):
        curveShape = sgBFunction_dag.getShape( curves[i] )
        newCurveShape = sgBFunction_dag.getShape( newCurves[i] )
        if cmds.isConnected( curveShape+'.local', newCurveShape+'.create' ):
            cmds.disconnectAttr( curveShape+'.local', newCurveShape+'.create' )
    
    return newCurves
예제 #45
0
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
예제 #46
0
def replaceConnection( first, second ):
    
    fSrcCons = cmds.listConnections( first, s=1, d=0, p=1, c=1 )
    
    if fSrcCons:
        outputs = fSrcCons[1::2]
        inputs  = fSrcCons[::2]
        
        for i in range( len( outputs ) ):
            try:
                cmds.connectAttr( outputs[i], inputs[i].replace( first, second ), f=1 )
                cmds.disconnectAttr( outputs[i], inputs[i] )
            except: pass
    
    fDesCons = cmds.listConnections( first, s=0, d=1, p=1, c=1 )
    
    if fDesCons:
        outputs = fDesCons[::2]
        inputs  = fDesCons[1::2]
        
        for i in range( len( outputs ) ):
            try:
                cmds.connectAttr( outputs[i].replace( first, second ), inputs[i], f=1 )
                cmds.disconnectAttr( outputs[i], inputs[i] )
            except:pass
예제 #47
0
def clearInput(switchList):
	'''
	Disconnect all incoming mesh connections to the list of specified meshSwitch nodes
	@param switchList: The list of meshSwitch nodes to disconnect incoming connections from.
	@type switchList: list
	'''
	# Check switchList
	if type(switchList) == str or type(switchList) == unicode:
		switchList = [str(switchList)]
	
	# For each switch
	for meshSwitch in switchList:
		
		# Get list of incoming mesh connections
		connectionList = mc.listConnections(meshSwitch+'.inMesh',s=True,d=False,p=True,c=True)
		if not connectionList: continue
		
		# Iterate over connections
		for i in range(len(connectionList)):
			
			# Skip odd numbered iteration
			if i%2: continue
			
			# Disconnect attribute
			mc.disconnectAttr(connectionList[i+1],connectionList[i])
예제 #48
0
파일: lattice.py 프로젝트: Bumpybox/Tapp
def latticeRemove():

    #undo enable
    cmds.undoInfo(openChunk=True)

    #getting nodes
    sel = cmds.ls(selection=True)
    if not sel:
        cmds.warning('No nodes selected!')
        return

    lat = sel[-1]
    objs = sel[0:-1]

    if cmds.nodeType(cmds.listRelatives(lat, shapes=True)[0]) != 'lattice':
        cmds.warning('Last selected is NOT a lattice!')
        return

    #removing from lattice
    for obj in objs:
        try:
            cmds.lattice(lat, e=True, remove=True, geometry=obj)

            #disconnecting shapes
            shapes = cmds.listRelatives(obj, shapes=True)
            for shp in shapes:
                source = cmds.listConnections(shp + '.inMesh', source=True)
                if cmds.nodeType(source) == 'ffd':
                    attr = cmds.listConnections(shp + '.inMesh', plugs=True)[0]
                    cmds.disconnectAttr(attr, shp + '.inMesh')
        except:
            pass

    cmds.undoInfo(closeChunk=True)
예제 #49
0
def createControllerOnTarget( target, pivotCtlOn=True ):

    import sgBFunction_connection
    import sgBFunction_dag
    import sgBModel_data
    targetPos = cmds.getAttr( target+'.wm' )
    targetP = cmds.listRelatives( target, p=1, f=1 )[0]
    
    targetName = target.split( '|' )[-1]
    ctl = cmds.circle( n='CTL_' + targetName )[0]
    ctlChild = cmds.createNode( 'transform', n='CTLChild_'+targetName );ctlChild = cmds.parent( ctlChild, ctl )[0]
    pivCtl = cmds.createNode( 'transform', n='PivCTL_'+targetName  ); cmds.setAttr( pivCtl+'.dh', 1 )
    cmds.setAttr( pivCtl+'.overrideEnabled', 1 )
    cmds.setAttr( pivCtl+'.overrideColor', 18 )
    ctlP = cmds.group( ctl, n='P'+ctl )
    ctlPPiv = cmds.group( ctlP, pivCtl, n='Piv' + ctlP )
    cmds.xform( ctlPPiv, ws=1, matrix=targetPos )

    cloneObject = sgBFunction_dag.getConstrainedObject( targetP )
    ctlPPiv = cmds.parent( ctlPPiv, cloneObject )[0]
    cmds.xform( pivCtl, os=1, matrix= sgBModel_data.getDefaultMatrix() )
    
    ctl = cmds.listRelatives( ctlP, c=1, f=1 )[0]
    sgBFunction_connection.getSourceConnection( target, ctlPPiv )

    for attr in [ 't', 'tx', 'ty', 'tz', 'r', 'rx', 'ry', 'rz', 's', 'sx', 'sy', 'sz', 'sh' ]:
        cons = cmds.listConnections( target+'.'+attr, s=1, d=0, p=1, c=1 )
        if not cons: continue
        for i in range( 0, len( cons ), 2 ):
            cmds.disconnectAttr( cons[i+1], cons[i] )
    
    sgBFunction_connection.constraintAll( ctlChild, target )
    
    cmds.connectAttr( pivCtl+'.t',  ctlP+'.t' )
    cmds.connectAttr( pivCtl+'.r',  ctlP+'.r' )
    cmds.connectAttr( pivCtl+'.s',  ctlP+'.s' )
    cmds.connectAttr( pivCtl+'.sh', ctlP+'.sh' )
    
    mmdcCtlChild = cmds.createNode( 'multMatrixDecompose' )
    cmds.connectAttr( ctlPPiv+'.wm', mmdcCtlChild+'.i[0]' )
    cmds.connectAttr( pivCtl+'.wim', mmdcCtlChild+'.i[1]' )
    cmds.connectAttr( mmdcCtlChild+'.ot',  ctlChild+'.t' )
    cmds.connectAttr( mmdcCtlChild+'.or',  ctlChild+'.r' )
    cmds.connectAttr( mmdcCtlChild+'.os',  ctlChild+'.s' )
    cmds.connectAttr( mmdcCtlChild+'.osh', ctlChild+'.sh' )
    
    ctlShape = sgBFunction_dag.getShape( ctl )
    circleNode = cmds.listConnections( ctlShape+'.create', s=1, d=0 )[0]
    
    mm = cmds.createNode( 'multMatrix' )
    trGeo = cmds.createNode( 'transformGeometry' )
    
    cmds.connectAttr( ctlPPiv+'.wm', mm+'.i[0]' )
    cmds.connectAttr( pivCtl+'.wim', mm+'.i[1]' )
    
    cmds.connectAttr( circleNode+'.outputCurve', trGeo+'.inputGeometry' )
    cmds.connectAttr( mm+'.matrixSum', trGeo+'.transform' )
    cmds.connectAttr( trGeo+'.outputGeometry', ctlShape+'.create', f=1 )
    
    return ctl
예제 #50
0
파일: rigbase.py 프로젝트: jonntd/mayadev-1
def repairConstraint():
    mtxObjs = cmds.ls( type='multMatrixDecompose' )
    mtxObjs += cmds.ls( type='decomposeMatrix' )
    mtxObjs += cmds.ls( type='blendTwoMatrixDecompose' )
    for mtx in mtxObjs:
        cons = cmds.listConnections( mtx, d=1, s=0, c=1, p=1, type='transform' )
        
        if not cons:
            continue
        
        outputs = cons[::2]
        inputs = cons[1::2]
        
        for i in range( len( outputs ) ):
            output = outputs[i]
            input = inputs[i]
            
            if input.find( 'jointOrient' ):
                continue
            
            try:
                cmds.connectAttr( output+'X', input+'X' )
                cmds.connectAttr( output+'Y', input+'Y' )
                cmds.connectAttr( output+'Z', input+'Z' )
                
                cmds.disconnectAttr( output, input )
            except: pass
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)
예제 #52
0
def unlock(plug):
    """Unlocks attribute and disconnects inputs for a plug.

    This will also recursively unlock the attribute
    upwards to any parent attributes for compound
    attributes, to ensure it's fully unlocked and free
    to change the value.

    """
    node, attr = plug.rsplit(".", 1)

    # Unlock attribute
    cmds.setAttr(plug, lock=False)

    # Also unlock any parent attribute (if compound)
    parents = cmds.attributeQuery(attr, node=node, listParent=True)
    if parents:
        for parent in parents:
            unlock("{0}.{1}".format(node, parent))

    # Break incoming connections
    connections = cmds.listConnections(plug,
                                       source=True,
                                       destination=False,
                                       plugs=True,
                                       connections=True)
    if connections:
        for destination, source in grouper(connections, 2):
            cmds.disconnectAttr(source, destination)
예제 #53
0
def disconnect_skeleton_connections(root_joint):
    """Cleanly disconnects all incoming connections to skeleton hierarchy

    Args:
        Joiint to traverse down from and disconnect all transform attrs from

    Returns:
        None

    Example:
        disconnect_skeleton_connections("Cn_root_jnt")
    """
    if cmds.objExists(root_joint):
        all_joints = cmds.listRelatives(root_joint, ad=True, type="joint")
        all_joints.append(root_joint)
        if all_joints:
            for jnt in all_joints:
                attrs = ['tx', 'ty', 'tz', 'translate',
                         'rx', 'ry', 'rz', 'rotate',
                         'sx', 'sy', 'sz', 'scale',
                         'visibility']
                for attr in attrs:
                    incoming_connection = cmds.listConnections("{}.{}".format(jnt, attr), source=True,
                                                               destination=False, plugs=True)
                    if incoming_connection:
                        cmds.disconnectAttr(incoming_connection[0], "{}.{}".format(jnt, attr))
            LOG.info("Deleted incoming skeleton connections for: {}".format(root_joint))
예제 #54
0
파일: control.py 프로젝트: zz-knight/cmt
    def _set_from_curve(self, transform):
        """Store the parameters from an existing curve in the CurveShape object.

        :param transform: Transform
        """
        shape = shortcuts.get_shape(transform)
        if shape and cmds.nodeType(shape) == "nurbsCurve":
            create_attr = "{}.create".format(shape)
            connection = cmds.listConnections(create_attr, plugs=True, d=False)
            if connection:
                cmds.disconnectAttr(connection[0], create_attr)
            self.transform = transform
            self.cvs = cmds.getAttr("{}.cv[*]".format(shape))
            self.degree = cmds.getAttr("{}.degree".format(shape))
            self.form = cmds.getAttr("{}.form".format(shape))
            self.knots = get_knots(shape)
            if cmds.getAttr("{}.overrideEnabled".format(shape)):
                if cmds.getAttr("{}.overrideRGBColors".format(shape)):
                    self.color = cmds.getAttr(
                        "{}.overrideColorRGB".format(shape))[0]
                else:
                    self.color = cmds.getAttr("{}.overrideColor".format(shape))
            else:
                self.color = None
            if connection:
                cmds.connectAttr(connection[0], create_attr)
예제 #55
0
def _disconnectPaintWeights(rbsNode):
	"""Disconnects any outgoing connection from the paintable weights."""

	pAttr = '%s.weightList[0].weights' % rbsNode
	destConnList = cmds.listConnections(pAttr, s=False, p=True) or []
	for dest in destConnList:
		src = cmds.listConnections(dest, d=False, p=True)[0]
		cmds.disconnectAttr(src, dest)
예제 #56
0
파일: rigbase.py 프로젝트: jonntd/mayadev-1
def reconnectContraint():
    attrs = ['ot', 'or', 'os', 'osh']
    mtxDcmps = cmds.ls( type='multMatrixDecompose' )
    for mtxDcmp in mtxDcmps:
        target = cmds.listConnections( mtxDcmp+'.ot' )
        if target:
            cmds.disconnectAttr( mtxDcmp+'.ot', target+'.t' )
            cmds.connectAttr( )
예제 #57
0
 def deactivate(self):
     refGeom = self.refLocator.getChildren()
     for rg in refGeom:
         if stripNamespaces(rg.split('|')[-1]).startswith(REF_INST_NAME):
             m.delete(rg)
     if self.getActiveStateFromMaya():
         m.disconnectAttr(self.refNode + '.message', self.refLocator.shape + '.refNodeMessage')
     self.active = False
예제 #58
0
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)
예제 #59
0
def disconnect(parent, children, attr = "meta"):
	children = _utils.make_list(children)
	parent = str(parent)
	full_attr = _NAMESPACE+attr
	for child in children:
		for conn in cmds.listConnections("{0}.message".format(child), p=1):
			if conn.find(full_attr)>-1 and conn.find(parent)>-1:
				cmds.disconnectAttr("{0}.message".format(child), conn)