Beispiel #1
0
def displaychoice(arg):
    sel =pm.ls(sl=1)
    hsv = pm.shadingNode("remapHsv",asUtility=1,name =sel[0] )
    pm.removeMultiInstance(hsv+".hue[1]",b=1)
    pm.setAttr(hsv+".color",1,0,0,type= "double3")
    pm.setAttr(hsv+".hue[0].hue_FloatValue",0.1)
    pm.connectAttr(hsv+".outColor",sel[0]+".hardwareColor",f=1)
Beispiel #2
0
def removeAliases(aovs):
    for sg in pm.ls(type='shadingEngine'):
        for aov in aovs:
            try:
                pm.removeMultiInstance(sg + '.ai_aov_' + aov.name)
            except RuntimeError, err:
                pass #print err
Beispiel #3
0
def removeAliases(aovs):
    for sg in pm.ls(type='shadingEngine'):
        for aov in aovs:
            try:
                pm.removeMultiInstance(sg + '.ai_aov_' + aov.name)
            except RuntimeError, err:
                pass  #print err
Beispiel #4
0
def xgmMakeCurvesDynamic(descHairSysName, collide):
    """
	Create nHairSystem with good name before MakeCurvesDynamic
	and without optionBox UI
	"""
    keepSele = pm.ls(sl=1)
    # find hair holding mesh for later rigid body rename
    meshPatch = []
    for dag in keepSele:
        if dag.getShape().type() == 'mesh':
            meshPatch.append(dag.name())
    # create the first time we hit a valid curve
    hsys = pm.createNode('hairSystem')
    hsys.getParent().rename(descHairSysName)
    # we want uniform stiffness because the curves
    # are initially point locked to both ends
    pm.removeMultiInstance(hsys.stiffnessScale[1], b=True)
    hsys.clumpWidth.set(0.00001)
    hsys.hairsPerClump.set(1)
    pm.connectAttr('time1.outTime', hsys.currentTime)
    nucleus = pm.mel.getActiveNucleusNode(False, True)
    pm.mel.addActiveToNSystem(hsys, nucleus)
    pm.connectAttr(nucleus + '.startFrame', hsys.startFrame)

    # select the hairSystem we just created and well named,
    # and maya won't create one when making curves dynamic
    keepSele.append(hsys)
    # re-select curves, mesh and hairSystem
    pm.select(keepSele, r=1)
    # trun on 'Collide With Mesh'
    pm.optionVar(intValue=['makeCurvesDynamicCollideWithMesh', int(collide)])
    # MakeCurvesDynamic callback
    pm.mel.eval('makeCurvesDynamic 2 { "1", "1", "1", "1", "0"}')

    return meshPatch, hsys
Beispiel #5
0
def vectorReproduce(baseMeshes, targetMeshes, outMeshes, centerFalloff, side):
    offset = centerFalloff * 0.01

    for i in xrange(len(baseMeshes)):
        baseMesh = pm.PyNode(baseMeshes[i])
        targetMesh = pm.PyNode(targetMeshes[i])
        outMesh = pm.PyNode(outMeshes[i])

        rampBS = pm.createNode('rampBlendShape')

        targetGeoBoundingBox = targetMesh.getBoundingBox(space='world')
        boundingBoxWidth = targetGeoBoundingBox.width()
        rampBS.range.set(boundingBoxWidth / 2)

        pm.removeMultiInstance(rampBS.weightCurveRamp[2], b=True)
        if side == 'left':
            rampBS.weightCurveRamp[0].weightCurveRamp_Position.set(0.5 -
                                                                   offset)
            rampBS.weightCurveRamp[1].weightCurveRamp_Position.set(0.5 +
                                                                   offset)
        elif side == 'right':
            rampBS.weightCurveRamp[0].weightCurveRamp_Position.set(0.5 +
                                                                   offset)
            rampBS.weightCurveRamp[1].weightCurveRamp_Position.set(0.5 -
                                                                   offset)

        baseMesh.getShape().worldMesh >> rampBS.baseGeo
        targetMesh.getShape().worldMesh >> rampBS.targetGeo
        rampBS.outGeo >> outMesh.inMesh

        pm.delete(outMesh, ch=True)

        pm.select(targetMesh, outMesh, r=True)
        tak_misc.copyMat()
Beispiel #6
0
def create_key_at_time(frame):
    """
    Create a key at the given time.  If a key already exists, return its index.
    """
    keys = get_singleton()

    # Find the name index for frame, if it already exists.
    idx = _get_key_index_at_frame(frame)
    if idx is not None:
        return idx

    # There's no key at the current frame.  Find an unused name index and create it.
    # We have to set the value, then set the keyframe.  If we just call setKeyframe,
    # the value won't be set correctly if it's in a character set.
    #
    # Disable auto-keyframe while we do this.  Otherwise, a keyframe will also
    # be added at the current frame (which seems like a bug).
    with maya_helpers.disable_auto_keyframe():
        idx = _get_unused_name_index()
        keys.attr('keyframes').set(idx)
        pm.setKeyframe(keys, at='keyframes', time=frame, value=idx)

    # setKeyframe can do this, but it's buggy: outTangentType='step' isn't applied if
    # we add a key before any other existing keys.
    pm.keyTangent(keys,
                  time=frame,
                  inTangentType='stepnext',
                  outTangentType='step')

    # Keyframes can be deleted by the user, which leaves behind stale entries.  Remove
    # any leftover data in the slot we're using.
    pm.removeMultiInstance(keys.attr('entries').elementByLogicalIndex(idx))

    return idx
def deleteShotSculptFrame():

    if editState == True:
        editSculptFrame()

    ssn = pm.optionMenu("selectedSSNode_menu", q=True, v=True)
    bshps = pm.getAttr(ssn + '.bshps')
    frame = pm.textScrollList("SculptLayers_tsl", q=True, si=True)

    result = pm.confirmDialog(title='Delete Sculpt-Frame',
                              message='Are you sure you want to delete ' +
                              frame[0] + "?",
                              button=['Yes', 'No'],
                              defaultButton='Yes',
                              cancelButton='No',
                              dismissString='No')

    if result == 'Yes':
        pm.deleteAttr(ssn + '.' + frame[0])

        pm.textScrollList("SculptLayers_tsl", e=True, ri=str(frame[0]))

        for bshp in bshps:
            ##mel command: blendShapeDeleteTargetGroup + bshp + index
            index = getIndexByName(bshp, frame[0])

            #remove the alias
            pm.aliasAttr(bshp + '.' + frame[0], remove=True)
            ##delete the target
            pm.removeMultiInstance(bshp + '.weight[' + str(index) + ']',
                                   b=True)
Beispiel #8
0
    def clearMutiAttr(self, attr):

        multies = pc.listAttr(self.nparticle, m=True, st=attr)

        for i in range(len(multies) - 1, 0, -1):

            pc.removeMultiInstance(
                pc.Attribute("%s.%s" % (self.nparticle.name(), multies[i])))
Beispiel #9
0
    def __setMultiAttr(self, attribute, values):

        with PreserveLocking(attribute):

            pm.removeMultiInstance(attribute, b = True)

            for index in range(len(values)):
                attribute[index].set(values[index])
def delete_blendshape_target(blendshape_name, target_index):
    pm.select(d=True)
    pm.removeMultiInstance(blendshape_name + ".weight[%s]" % target_index,
                           b=True)
    pm.removeMultiInstance(
        blendshape_name +
        ".inputTarget[0].inputTargetGroup[%s]" % target_index,
        b=True)
Beispiel #11
0
    def __setMultiMessage(self, attribute, nodes):

        with PreserveLocking(attribute):

            pm.removeMultiInstance(attribute, b = True)

            for index in range(len(nodes)):

                with PreserveLocking(nodes[index]):
                    nodes[index].message.connect(attribute[index])
Beispiel #12
0
    def createEtSTMapRE(self):

        #create etSTMapRE
        etSTMapRE = self.createRenderElement('ExtraTexElement')
        pm.rename(etSTMapRE, '{0}EtSTMap'.format(vrayGlobals.PREFIX))

        #SetAttrs on etSTMapRE
        pm.setAttr(etSTMapRE.vray_name_extratex,
                   '{0}EtSTMap'.format(vrayGlobals.PREFIX))
        pm.setAttr(etSTMapRE.vray_explicit_name_extratex,
                   '{0}EtSTMap'.format(vrayGlobals.PREFIX))
        pm.setAttr(etSTMapRE.vray_affectmattes_extratex, 0)
        pm.setAttr(etSTMapRE.vray_filtering_extratex, 0)

        #Create Red Ramp
        redRamp = self.createRamp(rampDirection=0)
        pm.rename(redRamp, '{0}STMapRedRamp'.format(vrayGlobals.PREFIX))
        #remove middle colorValue
        pm.removeMultiInstance(redRamp.colorEntryList[1], b=True)
        #set upper pos color to red
        redRamp.colorEntryList[2].color.set([1, 0, 0])
        redRamp.colorEntryList[2].position.set(1)
        #set lower pos color to black
        redRamp.colorEntryList[0].color.set([0, 0, 0])
        redRamp.colorEntryList[0].position.set(0)

        #Create Green Ramp
        greenRamp = self.createRamp(rampDirection=1)
        pm.rename(greenRamp, '{0}STMapGreenRamp'.format(vrayGlobals.PREFIX))
        #remove middle colorValue
        pm.removeMultiInstance(greenRamp.colorEntryList[1], b=True)
        #set upper pos color to green
        greenRamp.colorEntryList[2].color.set([0, 1, 0])
        greenRamp.colorEntryList[2].position.set(1)
        #set lower pos color to black
        greenRamp.colorEntryList[0].color.set([0, 0, 0])
        greenRamp.colorEntryList[0].position.set(0)

        pm.select(cl=True)

        #Connect ramps
        redRamp.outColor >> greenRamp.colorOffset

        #connect to extratex
        greenRamp.outColor >> etSTMapRE.vray_texture_extratex

        #verbose
        if (self.verbose): print('Extra Tex World Pos RE created')
Beispiel #13
0
def cMuscle_prepareRelax(mesh):
	hist = pm.listHistory(mesh, pdo=True, il=1)
	muscleSystems = pm.ls(hist, type='cMuscleSystem')
	muscleSystems = list(set(muscleSystems))
	for ms in muscleSystems:
		deformed = pm.deformer(ms, q=True, geometry=True)[0]
		
		if deformed.type() in ['nurbsSurface', 'mesh', 'subdiv']:
			ms.envelope.set(0)
			a, size = 0, 0
			for attr in ['smoothData.smoothEntry','smoothData.ptToPtEntry','relaxData.relaxSt','relaxData.relaxBd','relaxData.relaxTri']:
				for index in range(0, ms.attr(attr).get(size=True)-1):
					pm.removeMultiInstance(ms.attr(attr)[index])
			
			pm.cMuscleRelaxSetup(ms, gen=True)
			ms.envelope.set(1)
Beispiel #14
0
 def removeChild(self, child):
     """Remove the Handle as a child of this Handle."""
     children = self.children()
     children.remove(child)
     for subAttr in self.node.childHandle:
         pm.removeMultiInstance(subAttr, b=True)
     for subAttr in self.node.childHandleMatrix:
         pm.removeMultiInstance(subAttr, b=True)
     orientTarget = self.orientTarget()
     self.setOrientTarget(None)
     for handle in children:
         self.addChild(handle)
     if orientTarget != child:
         self.setOrientTarget(orientTarget)
     pm.disconnectAttr(child.node.parentHandle)
     pm.disconnectAttr(child.node.parentHandleMatrix)
	def createEtSTMapRE(self):
		
		#create etSTMapRE
		etSTMapRE = self.createRenderElement('ExtraTexElement')
		pm.rename(etSTMapRE, 'rbEtSTMap')
		
		#SetAttrs on etSTMapRE
		pm.setAttr(etSTMapRE.vray_name_extratex, 'rbEtSTMap')
		pm.setAttr(etSTMapRE.vray_explicit_name_extratex, 'rbEtSTMap')
		pm.setAttr(etSTMapRE.vray_affectmattes_extratex, 0)
		pm.setAttr(etSTMapRE.vray_filtering_extratex, 0)
		
		
		#Create Red Ramp
		redRamp = self.createRamp(rampDirection = 0)
		pm.rename(redRamp, 'rbSTMapRedRamp')
		#remove middle colorValue
		pm.removeMultiInstance (redRamp.colorEntryList[1], b=True)
		#set upper pos color to red
		redRamp.colorEntryList[2].color.set([1,0,0])
		redRamp.colorEntryList[2].position.set(1)
		#set lower pos color to black
		redRamp.colorEntryList[0].color.set([0,0,0])
		redRamp.colorEntryList[0].position.set(0)
		
		#Create Green Ramp
		greenRamp = self.createRamp(rampDirection = 1)
		pm.rename(greenRamp, 'rbSTMapGreenRamp')
		#remove middle colorValue
		pm.removeMultiInstance (greenRamp.colorEntryList[1], b=True)
		#set upper pos color to green
		greenRamp.colorEntryList[2].color.set([0,1,0])
		greenRamp.colorEntryList[2].position.set(1)
		#set lower pos color to black
		greenRamp.colorEntryList[0].color.set([0,0,0])
		greenRamp.colorEntryList[0].position.set(0)
		
		pm.select(cl = True)
		
		#Connect ramps
		redRamp.outColor >> greenRamp.colorOffset
		
		#connect to extratex
		greenRamp.outColor >> etSTMapRE.vray_texture_extratex
		
		#verbose
		if(self.verbose): print('Extra Tex World Pos RE created')
Beispiel #16
0
def deletePose(node, indexToPop):
    """gather information on node, remove desired index and reapply

    Args:
        node (str): weightDriver
        indexToPop (int): pose index to remove
    """
    node = pm.PyNode(node)
    posesInfo = getPoseInfo(node)
    poseInput = posesInfo["poseInput"]
    poseValue = posesInfo["poseValue"]
    currentLength = range(len(poseInput))
    poseInput.pop(indexToPop)
    poseValue.pop(indexToPop)
    setPosesFromInfo(node, posesInfo)
    attrPlug = "{}.poses[{}]".format(node, currentLength[-1])
    pm.removeMultiInstance(attrPlug, b=True)
Beispiel #17
0
def create_ramp_for_schlick(normal_reflectivity, max_points=100):
    """
    Create a ramp approximating Schlick's approximation.  max_points is the maximum number
    of points to place on the ramp.
    """
    remap_node = pm.shadingNode('remapValue', asUtility=True)

    sampler_info = pm.shadingNode('samplerInfo', asUtility=True)
    sampler_info.attr('facingRatio').connect(remap_node.attr('inputValue'))

    # Calculate Fresnel curve
    schlick_list = schlick_aprox(normal_reflectivity)

    # Compensate for non-linear facingRatio
    linearValues = [float(i) / 90 for i in range(91)]
    raw_values = [
        math.sin(linearValues[i] * 90 * math.pi / 180) for i in range(91)
    ]
    raw_values.reverse()

    # Keep decreasing precision until we reduce the curve to the maximum number of points.
    myline = zip(raw_values, schlick_list)
    precision = 0.00005
    simplified = None
    while simplified is None or len(simplified) > max_points:
        simplified = ramerdouglas(myline, dist=precision)
        precision *= 2

    # Remove default values
    pm.removeMultiInstance(remap_node.attr('value[0]'), b=1)
    pm.removeMultiInstance(remap_node.attr('value[1]'), b=1)

    for i in simplified:
        currentSize = pm.getAttr(remap_node.attr('value'), size=1)

        # First and last values with linear interpolation, others with spline interpolation.
        if simplified.index(i) == 0 or simplified.index(
                i) == len(simplified) - 1:
            interp = 1
        else:
            interp = 3

        attr = remap_node.attr('value[%i]' % (currentSize + 1))
        pm.setAttr(attr, i[0], i[1], interp, type='double3')

    return remap_node.attr('outValue')
Beispiel #18
0
    def set(self, attr_name, value):
        """
        Set the value of the given attribute. Attribute name must be registered in one of the attr dictionaries.
        Currently supports attributes of type message, string, bool, float, int, enum

        :param attr_name: Name of attribute to edit
        :param value: List or single value representing value of attribute to set
        """
        # Get attribute data
        attr_data = self._get_attr_data(attr_name)
        # If multi: (value should be list)
        if attr_data.get('multi', False):
            if not isinstance(value, (list, tuple)):
                raise ValueError(
                    "'{0}' is a multi attribute and must be set with a list or tuple of data"
                    .format(attr_name))
            # Data Type: MESSAGE
            if attr_data.get('at') == 'message':
                for attr_element in self.node.attr(attr_name):
                    pm.removeMultiInstance(attr_element, b=True)
                # Value should be list of PyNodes, we connect node.message to slot
                for index, item in enumerate(value):
                    pm.connectAttr(item.message,
                                   self.node.attr(attr_name)[index])
            # Data Type: STRING/BOOL/FLOAT/INT/ENUM
            else:
                for attr_element in self.node.attr(attr_name):
                    pm.removeMultiInstance(attr_element, b=True)
                for index, item in enumerate(value):
                    self.node.attr(attr_name)[index].set(item)
        # If not multi:
        else:
            # Data Type: MESSAGE
            if attr_data.get('at') == 'message':
                # Value should be a PyNode, we connect node.message to slot
                if value is not None:
                    pm.connectAttr(value.message, self.node.attr(attr_name))
                # If value is None, disconnect the current value
                else:
                    pm.disconnectAttr(self.node.attr(attr_name), inputs=True)
            # Data Type: STRING/BOOL/FLOAT/INT/ENUM
            else:
                self.node.attr(attr_name).set(value)
Beispiel #19
0
def delete_key_at_frame(frame):
    """
    Delete the key at frame.

    Note that we don't delete the underlying zKeyframeNaming node if it's empty, since it might
    be added to character sets by the user.
    """
    keys = get_singleton()

    # Run index cleanup if needed before making changes to the frame.
    cleanup_duplicate_indices()    

    all_keys = get_all_keys()

    idx = pm.keyframe(keys.attr('keyframes'), q=True, valueChange=True, t=frame)
    if not idx:
        return

    # Remove the keyframe and any associated data.
    pm.cutKey(keys.attr('keyframes'), t=frame)
    pm.removeMultiInstance(keys.attr('entries').elementByLogicalIndex(idx[0]))
Beispiel #20
0
def shader_makeBasicCloth():
	shader = pm.shadingNode('lambert', asShader=True)
	tmp2DPlace = pm.shadingNode('place2dTexture', asUtility=True)
	tmp2DTex = pm.shadingNode('cloth', asUtility=True)
	bmp = pm.shadingNode('bump2d', asUtility=True)
	
	tmp2DPlace.outUV.connect(tmp2DTex.uvCoord)
	tmp2DPlace.outUvFilterSize.connect(tmp2DTex.uvFilterSize)
	tmp2DTex.outColor.connect(shader.color)
	tmp2DTex.outAlpha.connect(bmp.bumpValue)
	tmp2DPlace.repeatU.set(10)
	tmp2DPlace.repeatV.set(10)
	
	bmp.bumpDepth.set(.05)
	bmp.bumpFilter.set(.01)
	
	ramp = pm.shadingNode('ramp', asUtility=True)
	si = pm.shadingNode('samplerInfo', asUtility=True)
	
	si.facingRatio.connect(ramp.uvCoord.vCoord)
	
	pm.removeMultiInstance(ramp.colorEntryList[1], b=True)
	ramp.colorEntryList[0].color.set((1,1,1), type='double3')
	ramp.colorEntryList[2].color.set((0,0,0), type='double3')
	
	tmp2DTex.colorGain.set((.35, .35, .35), type='double3')
	tmp2DTex.outColor.connect(ramp.colorEntryList[0].color)
	
	surflum = pm.shadingNode('surfaceLuminance', asUtility=True)
	md = pm.shadingNode('multiplyDivide', asUtility=True)
	
	surflum.outValue.connect(md.input1.input1X)
	surflum.outValue.connect(md.input1.input1Y)
	surflum.outValue.connect(md.input1.input1Z)
	ramp.outColor.connect(md.input2)
	
	md.output.connect(shader.incandescence)
	bmp.outNormal.connect(shader.normalCamera)
Beispiel #21
0
    def build(self, numOfShapes=2, centerFalloff=5):
        """
        Args:
            numOfShapes: Number of shapes
            centerFalloff: Percentage of falloff from center
        """
        self.numOfShapes = numOfShapes
        offset = centerFalloff * 0.01

        self.outGeo = self.baseGeo.duplicate(n='%s_rampBS' % self.targetGeo.name())[0]
        pm.delete(pm.parentConstraint(self.targetGeo, self.outGeo, mo=False))

        self._createRefPlanes()

        self.rampBS = pm.createNode('rampBlendShape')
        if self.numOfShapes == 2:
            pm.removeMultiInstance(self.rampBS.weightCurveRamp[2], b=True)
            self.rampBS.weightCurveRamp[0].weightCurveRamp_Position.set(0.5-offset)
            self.rampBS.weightCurveRamp[1].weightCurveRamp_Position.set(0.5+offset)

        self._connectNodes()

        self.targetGeo.hide()
Beispiel #22
0
 def removeHandle(self, index):
     """Remove and delete the handle at the given index."""
     self._consolidateSparseHandleArray()
     handle = self.handleAtIndex(index)
     # If the handle being removed has children in other guides,
     # Set those guides to have no parent
     for child in handle.children():
         if child.guideNode != self.guide:
             Guide(child.guideNode).setParentGuide(None)
     handleList = list(self.handles())
     for i in xrange(index + 1, self.handleCount()):
         # If a handle after the removal point has a child in
         # another guide, that guide needs to have its parentHandleIndex
         # decreased by 1
         h = handleList[i]
         for child in h.children():
             if child.guideNode != self.guide:
                 g = Guide(child.guideNode)
                 g.setParentGuideHandleIndex(g.parentGuideHandleIndex() - 1)
         self._changeHandleIndex(i, i - 1)
     pm.removeMultiInstance(
         self.guide.handle[self.guide.handle.numElements() - 1], b=True)
     pm.delete(handle.transform)
     self._refreshHandleHierarchicalConnections()
Beispiel #23
0
    def import_(self, deformerPath, optimized=False):
        super(SkinCluster, self).import_(deformerPath, optimized=optimized)

        initialSelection = cmds.ls(selection=True)

        # choose set of influences
        if optimized:
            influences = self.optimizedinfluences
        else:
            influences = self.influences

        for deformedNode in self.deformedNodes:
            pymel.select(clear=True)

            # Are there missing influences?
            try:
                pymel.select(influences)
            except:
                missingInfluencesString = ''
                missingInfluencesCount = 0
                duplicateNamesString = ''
                duplicateNamesCount = 0

                for each in influences:
                    if not cmds.objExists(each):
                        missingInfluencesString += '        %s\n' % each
                        missingInfluencesCount += 1

                    elif len(pymel.ls(each)) > 1:
                        for each in pymel.ls(each):
                            duplicateNamesString += '        %s\n' % str(each)
                            duplicateNamesCount += 1

                if missingInfluencesCount:
                    pymel.error(
                        '\n    SKINCLUSTER FAILED TO LOAD on %s because %s influences DO NOT EXIST in the scene:\n'
                        % (deformedObject, str(missingInfluencesCount)) +
                        missingInfluencesString)

                if duplicateNamesCount:
                    pymel.error(
                        '\n    SKINCLUSTER FAILED TO LOAD on %s because %s there are DUPLICATE NAMES for the following influences:\n'
                        % (deformedObject, str(duplicateNamesCount)) +
                        duplicateNamesString)

            # create new skin cluster
            if not self.deformer:
                pymel.select(self.deformedComponents, add=True)
                self.deformer = pymel.skinCluster(toSelectedBones=True,
                                                  removeUnusedInfluence=False,
                                                  normalizeWeights=0)
                self.deformer.rename(self.deformerName)

            # clear data from existing skinCluster
            else:
                #bindPreMatrixInputs = NOne
                for i in self.deformer.matrix.get(multiIndices=True):
                    for arrayAttr in (
                            'matrix',
                            'influenceColor',
                            'lockWeights',
                            'weightList',
                    ):
                        pymel.removeMultiInstance(
                            self.deformer.attr(arrayAttr)[i], b=True)

                    try:
                        pymel.removeMultiInstance(
                            self.deformer.bindPreMatrix[i], b=False)
                    except:
                        pass

                for i, joint in enumerate(influences):
                    joint.worldMatrix[0] >> self.deformer.matrix[i]
                    joint.objectColorRGB >> self.deformer.influenceColor[i]
                    joint.lockInfluenceWeights >> self.deformer.lockWeights[i]

                    try:
                        self.deformer.bindPreMatrix[i].set(
                            joint.worldInverseMatrix.get())

                    except:
                        pass

            self.deformer.normalizeWeights.set(0)
            pymel.skinPercent(self.deformer,
                              self.deformedComponents,
                              nrm=False,
                              prw=100)

            if optimized:
                weightsFile = os.path.join(deformerPath,
                                           'optimizedSkinWeights.txt')
            else:
                weightsFile = os.path.join(deformerPath, 'skinWeights.txt')

            self.importSkinWeights_fromFile(weightsFile)

            self.deformer.normalizeWeights.set(1)

        pymel.select(initialSelection)
Beispiel #24
0
def transferAttrs(sourceObj, targetObjs, attributes=[]):
    """Copies the value(s) of the attribute from sourceObj to targetObj. Handles multi-attributes."""
    sourceObj = pm.PyNode(sourceObj)
    
    if attributes == []:
        attributes=pm.listAttr(sourceObj, k=1, l=0)
    
    for targetObj in targetObjs:
        targetObj = pm.PyNode(targetObj)
    
        for attribute in attributes:
            sourceAttrNode = pm.PyNode('%s.%s'%(sourceObj, attribute))
            print 'sourceAttr is %s'%sourceAttrNode
            
            if pm.attributeQuery(attribute, node = targetObj.name(), exists=True): # Execute only if the entered attribute exists
                
                multiAttr = pm.attributeQuery(attribute, node=targetObj.name(), listChildren=1) # Get list of multi-attribute children, if any
        
                if multiAttr: # If the attribute is a multi-attribute
                    extraInst = set(sourceObj.getAttr(attribute, mi=1)).symmetric_difference( set(targetObj.getAttr(attribute, mi=1)) ) # Get the set of extra instances in multi-attribute
                    for ins in extraInst: # Remove these extra instances
                        pm.removeMultiInstance('{0}.{1}[{2}]'.format(targetObj.name(), attribute, ins) )
                        
                    for attrChild in multiAttr:
                        for ind in sourceObj.getAttr(attribute, mi=1):
                            attrString = '{attr}[{index}].{child}'.format( attr = attribute,
                                                                        index = ind,
                                                                        child = attrChild )
                            
                            attrVal = sourceObj.getAttr( attrString )
                            targetObj.setAttr( attrString, attrVal )
                            print( '//  {objName}.{attr} was set to {val}  //'.format(objName = targetObj.name(),
                                                                            attr = attrString,
                                                                            val = attrVal) )
                else:
                    trgtAttrNode = pm.PyNode('%s.%s'%(targetObj, attribute))
                    
                    # clear target Attr
                    if trgtAttrNode.isConnected():
                        trgtConn = trgtAttrNode.listConnections(scn=1)
                        if trgtConn[0].type() in ['expression', 'animCurveTU']: # If animCurve or Expression connected, delete it
                            pm.delete(trgtConn)
                        else:
                            pm.disconnectAttr(trgtAttrNode)

                    
                    if sourceAttrNode.isConnected():
                        conn = sourceAttrNode.listConnections(scn=1)
                        if conn[0].type() == 'expression': # If the attribute has an expression
                            dupconn = pm.duplicate(conn[0])
                            expressionstring = conn[0].getExpression().replace(sourceObj.name(), targetObj.name())
                            dupconn[0].setExpression(expressionstring)
                        elif conn[0].type() == 'animCurveTU': # If the attribute is keyed
                            pm.copyKey(sourceObj, at=attribute)
                            pm.pasteKey(targetObj, at=attribute, o='replace')
                    else: # Otherwise simple copy paste attr
                            attrVal = sourceObj.getAttr(attribute)
                            try:
                                targetObj.setAttr(attribute, attrVal)
                            except Exception as e:
                                print 'Error occurred : ' + str(e)
                                continue

                            print('//  {0}.{1} was set to {2}  //\n'.format(targetObj.name(), attribute, attrVal) )
            else:
                print('!!  {0} does not exist  !!\n'.format(attribute))
    def connect_lipSystem(self):
        self.multUpperPos = pm.shadingNode("multiplyDivide", asUtility=True)
        self.multUpperPos.renameNode(name=self.TipName,
                                     base='%sHeadUpperLipPos')
        self.multUpperPos.addTag(self.lipFollowRig)

        self.multUpperFollow = pm.shadingNode("multiplyDivide", asUtility=True)
        self.multUpperFollow.renameNode(name=self.TipName,
                                        base='HeadUpperLipFollow%s')
        self.multUpperFollow.addTag(self.lipFollowRig)

        self.multLowerPos = pm.shadingNode("multiplyDivide", asUtility=True)
        self.multLowerPos.renameNode(name=self.TipName,
                                     base='%sHeadLowerLipPos')
        self.multLowerPos.addTag(self.lipFollowRig)

        self.multLowerFollow = pm.shadingNode("multiplyDivide", asUtility=True)
        self.multLowerFollow.renameNode(name=self.TipName,
                                        base='%sHeadLowerLipFollow')
        self.multLowerFollow.addTag(self.lipFollowRig)

        self.reverseLowerPos = pm.shadingNode("reverse", asUtility=True)
        self.reverseLowerPos.renameNode(name=self.TipName,
                                        base='%sHeadLowerPos')
        self.reverseLowerPos.addTag(self.lipFollowRig)

        self.jaw.translate.connect(self.multUpperPos.input1)
        self.multUpperPos.output.connect(self.multUpperFollow.input1)
        self.multUpperFollow.output.connect(self.upperLipTrans.translate)
        self.multUpperPos.input2.set((0.5, 0.5, 0.5))

        self.jaw.translateY.connect(self.multLowerPos.input1.input1Y)
        self.multLowerPos.output.connect(self.reverseLowerPos.input)
        self.multLowerPos.outputY.connect(self.multLowerFollow.input1Y)
        self.multLowerPos.input2.set((0.5, 0.5, 0.5))

        self.jaw.translateX.connect(self.multLowerFollow.input1X)
        self.jaw.translateZ.connect(self.multLowerFollow.input1Z)
        self.reverseLowerPos.output.connect(self.multLowerFollow.input2)
        self.multLowerFollow.output.connect(self.lowerLipTrans.translate)

        #create system for side lip joints
        self.remapJawOpen = pm.shadingNode('remapColor', asUtility=True)
        self.remapJawOpen.renameNode(name=self.TipName,
                                     base='%sLowerLipJawOpenMulti')
        self.remapJawOpen.addTag(self.lipFollowRig)

        self.multJawOpen = pm.shadingNode('multiplyDivide', asUtility=True)
        self.multJawOpen.renameNode(name=self.TipName,
                                    base='%sLowerLipJawOpenMulti')
        self.multJawOpen.addTag(self.lipFollowRig)

        pm.connectAttr(self.lipFollowRig.jawOpenValue,
                       self.remapJawOpen.red[0].red_Position)
        self.remapJawOpen.red[0].red_FloatValue.set(2)
        self.remapJawOpen.red[0].red_Interp.set(1)
        self.remapJawOpen.outColorR.connect(self.multJawOpen.input2X)
        self.lowerLipJawOpenOffset.translateZ.connect(self.multJawOpen.input1X)
        self.multJawOpen.outputX.connect(self.lowerLipJawOpenMulti.translateZ)

        pm.removeMultiInstance(self.remapJawOpen.red[1], b=True)

        #set 1 to 0
        self.remapJawOpen.red[1].red_FloatValue.set(0)
        self.remapJawOpen.red[1].red_Position.set(0)
        self.remapJawOpen.red[1].red_Interp.set(1)