示例#1
0
def lucky_facial(body):
    # body est le mesh de base sur lequel on va mettre les plaques
    plaques = mc.ls(sl=True)
    recup_plaques = []
    recup_locators = []

    for ind, mesh in enumerate(plaques):
        # create locator and snap it to mesh
        locator = mc.spaceLocator(n=mesh + '_loc', p=(0, 0, 0))
        tool.snap_from_to(mesh, locator)
        recup_locators.append(locator)
        # recup name part to name ctrl
        no_ns = mesh.split(':')[1]
        recup = no_ns.split('_')[-2]
        recup_plaques.append(recup)

    # ctrlTuple est une liste de tuples
    ctrl_tuple = tool.more_ctrl(recup_plaques)
    # snap aux locs
    for i, locator in enumerate(recup_locators):
        tool.snap_from_to(locator, ctrl_tuple[i][1])

    # skin and shrinkwrap
    for ind, mesh in enumerate(plaques):
        mc.skinCluster(mesh, ctrl_tuple[ind][0], tsb=True, rui=True)
        deform = mc.deformer('shrinkWrap_facial', e=True, g=mesh)
        deform = 'shrinkWrap_facial'
        if not mc.objExists(deform):
            deform = mc.deformer(mesh, n='shrinkWrap_facial', type='shrinkWrap')[0]
            mc.setAttr(deform + '.projection', 3)
            mc.setAttr(deform + '.bidirectional', 1)
            mc.connectAttr(body + '.worldMesh[0]', deform + '.targetGeom')
        mc.polyMoveFacet(ltz=float(ind + 1) / 1000)
示例#2
0
def getGeoIndex(dfm, geo):
    """
    return index of geometry in deformer
    geo - should be a shape node
    """
    deformedGeos = mc.deformer(dfm, q=True, g=True)
    geoId = deformedGeos.index(geo)
    deformedGeosId = mc.deformer(dfm, q=True, gi=True)
    return deformedGeosId[geoId]
示例#3
0
def makeDeformerUnique(deformer, target):
    '''

    :param deformer:
    :param target:
    :return:
    '''
    copyDeformer(deformer, target)
    mc.deformer(deformer, e=1, rm=1, g=target)
示例#4
0
def getGeoIndex(dfm, geo):
    """
    return index of geometry in deformer
    geo - should be a shape node
    """
    deformedGeos = mc.deformer(dfm, q=True, g=True)
    geoId = deformedGeos.index(geo)
    deformedGeosId = mc.deformer(dfm, q=True, gi=True)
    return deformedGeosId[geoId]
示例#5
0
 def CreateDeformer(self):
     if not mc.pluginInfo('hotOceanDeformer.mll', q=True, l=True):
         mc.loadPlugin('hotOceanDeformer.mll')
     mc.polyPlane(n='OceanPreview',
                  w=20,
                  h=20,
                  sx=150,
                  sy=150,
                  ax=[0, 1, 0],
                  cuv=2,
                  ch=1)
     mc.deformer(type='hotOceanDeformer')
示例#6
0
 def __prep_mesh(self, mesh):
     mc.deformer(mesh,
                 frontOfChain=True, 
                 type='blendShape', 
                 name=self.TEMP_BS_NODE)
     history = mc.listHistory(mesh, interestLevel=1)
     history = [i for i in history if 'geometryFilter' in mc.nodeType(i, inherited=True)]
     
     self._deformers = []
     for his in history:
         if his == self.TEMP_BS_NODE:
             break
         self._deformers.append(his)
示例#7
0
def createCmd():
	"""Create node."""
	
	geo = _getGeoFromUI()
	rbsNode = geo and _getRbs(geo)
	
	if rbsNode:
		_updateUI()
		return
	
	# create the rbs
	cmds.deformer(geo, typ=_rbsNodeName, foc=True)
	
	_updateUI()
示例#8
0
	def apply_push_deformer_selection():
		if not self.__load_plugin():
			return

		objs = cmds.ls(sl=True, type='transform')
		if not len(objs):
			cmds.warning('No objects selected.')
			return

		for x in objs:
			cmds.select(x)
			name = str(x) + '_pushDeformer'
			name = mel.eval('formValidObjectName(\"{0}\");'.format(name))
			cmds.deformer(name=name, type='pushDeformer')
示例#9
0
    def apply_push_deformer_selection():
        if not self.__load_plugin():
            return

        objs = cmds.ls(sl=True, type='transform')
        if not len(objs):
            cmds.warning('No objects selected.')
            return

        for x in objs:
            cmds.select(x)
            name = str(x) + '_pushDeformer'
            name = mel.eval('formValidObjectName(\"{0}\");'.format(name))
            cmds.deformer(name=name, type='pushDeformer')
示例#10
0
def createCmd():
    """Create node."""

    geo = _getGeoFromUI()
    rbsNode = geo and _getRbs(geo)

    if rbsNode:
        _updateUI()
        return

    # create the rbs
    cmds.deformer(geo, typ=_rbsNodeName, foc=True)

    _updateUI()
示例#11
0
def transferInputHistory():
    selection = cmds.ls(sl=1)
    if selection:
        source = selection[0]
        deformers = cmds.listHistory(source, pdo=1, il=2)
        deformers.reverse()

        for target in selection[1:]:
            for e, deformer in enumerate(deformers[1:]):
                if cmds.nodeType(deformer) == 'skinCluster':
                    skinningMethod = cmds.getAttr(deformer + '.skinningMethod')
                    transferSkin([source, target], skinningMethod)
                else:
                    cmds.deformer(deformer, e=True, g=target, ex=e)
示例#12
0
def prep_mesh(mesh):
    # get the deformers before operations
    mc.deformer(mesh, frontOfChain=True, type='blendShape', name=TEMP_BS_NODE)
    history = mc.listHistory(mesh, interestLevel=1)
    history = [
        i for i in history
        if 'geometryFilter' in mc.nodeType(i, inherited=True)
    ]

    deformers = []
    for his in history:
        if his == TEMP_BS_NODE:
            break
        deformers.append(his)
    return deformers
示例#13
0
def mirrorDeformer(middleEdge, deformer, search='lf', replace='rt'):
    '''
	'''
    # Load plugin
    loadPlugin()

    # Get Mesh Data
    mesh = mc.ls(middleEdge, o=True)[0]
    vmap = mm.eval('edgeFlowMirror -task "getMapArray" -middleEdge ' +
                   middleEdge)

    # Mirror Membership
    mem = glTools.utils.deformer.getDeformerSetMemberIndices(deformer, mesh)
    if len(vmap) > len(mem): mem = sorted([vmap[i] for i in mem])
    mem = [mesh + '.vtx[' + str(i) + ']' for i in mem]

    # Create Mirror Deformer
    deformerType = mc.objectType(deformer)
    deformerName = deformer
    if deformerName.startswith(search):
        deformerName = deformerName.replace(search, replace)
    elif deformerName.startswith(replace):
        deformerName = deformerName.replace(replace, search)
    else:
        deformerName = deformerName + '_mirror'

    mDeformer = mc.deformer(mem, type=deformerType, name=deformerName)[0]

    # Mirror Deofmer Weights
    mirrorDeformerWeights(middleEdge, deformer, dstDeformer=mDeformer)

    # Return Result
    return mDeformer
示例#14
0
def initModules(src_txt, targ_txt, deformer_txt, rbf_txt, *args):
    #load geometry
    src_geo = cmds.ls(sl=1)

    #group for samples
    src_grp = cmds.group(n=src_geo[0] + '_src_sample', empty=True)
    targ_grp = cmds.group(n=src_geo[0] + '_targ_sample', empty=True)

    #first pair of space identifier
    src_k1 = cmds.spaceLocator(n='src_' + src_geo[0] + '_01')
    cmds.setAttr(src_k1[0] + '.overrideEnabled', 1)
    cmds.setAttr(src_k1[0] + '.overrideColor', 9)
    targ_k1 = cmds.spaceLocator(n='targ_' + src_geo[0] + '_01')
    cmds.setAttr(targ_k1[0] + '.overrideEnabled', 1)
    cmds.setAttr(targ_k1[0] + '.overrideColor', 14)
    cmds.parent(src_k1[0], src_grp)
    cmds.parent(targ_k1[0], targ_grp)

    #registration nodes for deforming
    cmds.select(src_geo[0])
    register_deform = cmds.deformer(type='RegistrationDeformer',
                                    n=src_geo[0] + '_register')
    rbf_solver = cmds.createNode('RBFNode', n=src_geo[0] + '_rbf')

    #update global
    cmds.textField(deformer_txt, edit=1, text=register_deform[0])
    cmds.textField(rbf_txt, edit=1, text=rbf_solver)
    cmds.textField(src_txt, edit=1, text=src_grp)
    cmds.textField(targ_txt, edit=1, text=targ_grp)
示例#15
0
def createProximityWrap(source, target):
    """
    Creates a proximity with the given source and target transforms.

    Args:
        source (pm.nodetypes.Transform): Transform with skinned mesh that will drive given target.

        target (pm.nodetypes.Transform): Transform with mesh shape that will be driven by given source.

    Returns:
        (pm.nodetypes.ProximityWrap): Proximity wrap node created.
    """
    # implementing with maya.cmds since PyMel raises the following warning for every attribute set.
    # Warning: pymel.core.general : Could not create desired MFn. Defaulting to MFnDependencyNode.
    deformer = cmds.deformer(target.name(),
                             type='proximityWrap',
                             name=target.name(stripNamespace=True) +
                             '_pWrap')[0]
    cmds.setAttr(deformer + '.maxDrivers', 1)
    cmds.setAttr(deformer + '.falloffScale', 1.4)
    cmds.setAttr(deformer + '.smoothInfluences', 5)
    cmds.setAttr(deformer + '.smoothNormals', 5)

    proximity_interface = node_interface.NodeInterface(deformer)
    proximity_interface.addDriver(
        source.getShapes()
        [-1].name())  # last shape should be the deformed shape
    return deformer
示例#16
0
 def createCmd(self, *args ):
     
     sels = cmds.ls( sl=1 )
     
     if not sels: return None
     
     targetObj = sels[0]
     
     skinNode = self._cmd.getTargetSkinCluster( targetObj )
 
     if not skinNode : return None
     
     duObjs = self._cmd.duplicateObj( targetObj, skinNode )
     
     print duObjs
     
     if duObjs: secondObj = duObjs[0]; thirdObj = duObjs[1]
     else: return None
     
     secondShape = cmds.listRelatives( secondObj, s=1 )[0]
     
     inverseSkinCluster = cmds.deformer( thirdObj, type='inverseSkinCluster' )[0]
     cmds.connectAttr( secondShape+'.outMesh', inverseSkinCluster+'.inMesh' )
     cmds.connectAttr( skinNode+'.message', inverseSkinCluster+'.targetSkinCluster' )
     cmds.connectAttr( targetObj+'.wm', inverseSkinCluster+'.geomMatrix')
     
     pos1, pos2 = self._cmd.getDuPosition( targetObj )
 
     cmds.xform( secondObj, ws=1, matrix=pos1 )
     cmds.xform( thirdObj, ws=1, matrix=pos2 )
     
     cmds.sets( secondObj, thirdObj, e=1, forceElement = "initialShadingGroup" )
     
     cmds.select( secondObj )
示例#17
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
示例#18
0
def pruneWeights(deformer, geoList=[], threshold=0.001):
    """
    Set deformer component weights to 0.0 if the original weight value is below the set threshold
    @param deformer: Deformer to removed components from
    @type deformer: str
    @param geoList: The geometry objects whose components are checked for weight pruning
    @type geoList: list
    @param threshold: The weight threshold for removal
    @type threshold: str
    """
    # Check deformer
    if not cmds.objExists(deformer):
        raise Exception('Deformer "' + deformer + '" does not exist!')

    # Check geometry
    if type(geoList) == str: geoList = [geoList]
    if not geoList: geoList = cmds.deformer(deformer, q=True, g=True)
    if not geoList: raise Exception('No geometry to prune weight for!')
    for geo in geoList:
        if not cmds.objExists(geo):
            raise Exception('Geometry "' + geo + '" does not exist!')

    # For each geometry
    for geo in geoList:
        # Get deformer member indices
        memberIndexList = getDeformerSetMemberIndices(deformer, geo)

        # Get weight list
        weightList = getWeights(deformer, geo)

        # Prune weights
        pWeightList = [wt if wt > threshold else 0.0 for wt in weightList]

        # Apply pruned weight list
        setWeights(deformer, pWeightList, geo)
示例#19
0
def makeWire( dropoffDistance ):
    
    sels = cmds.ls( sl=1 )
    
    last = sels[-1]
    lastShape = cmds.listRelatives( last, s=1 )[0]
    baseShape = getBaseShape( last )
    
    for sel in sels[:-1]:
        wireExists = False
        hists = cmds.listHistory( sel, pdo=1 )
        if not hists: hists = []
        for hist in hists:
            if cmds.nodeType( hist ) == 'wire':
                wireExists = True
                break
        if wireExists:
            wire = hist
        else:
            wire = cmds.deformer( sel, type='wire' )[0]
            cmds.connectAttr( baseShape+'.local', wire+'.baseWire[0]' )
            cmds.connectAttr( lastShape+'.local', wire+'.deformedWire[0]' )
        cmds.setAttr( wire+'.dropoffDistance[0]', dropoffDistance )

    cmds.select( sels )
示例#20
0
def importPolyMesh(name, identifier, jobInfo, parentXform=None, isConstant=False, useDynTopo=False):
	cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._import.importPolyMesh")

	# TODO: set isConstant properly elsewhere when there are no transforms but are
	# animated attributes
	isConstant = False
	try:
		reader = ""
		shape  = fnt.alembicCreateNode(name, "mesh", parentXform)
		cmds.sets(shape, e=True, forceElement="initialShadingGroup")

		topoReader = cmds.createNode("ExocortexAlembicPolyMesh")
		cmds.connectAttr(topoReader+".outMesh", shape+".inMesh")
		cmds.connectAttr(jobInfo.filenode+".outFileName", topoReader+".fileName")
		cmds.setAttr(topoReader+".identifier", identifier, type="string")
		cmds.setAttr(topoReader+".normals", jobInfo.useNormals)
		cmds.setAttr(topoReader+".uvs", jobInfo.useUVs)
		if jobInfo.useFaceSets:
			cmds.ExocortexAlembic_createFaceSets(o=shape, f=jobInfo.filename, i=identifier)

		if useDynTopo:
			cmds.connectAttr(jobInfo.timeCtrl+".outTime", topoReader+".inTime")
			reader = topoReader
		elif not isConstant:
			reader = cmds.deformer(shape, type="ExocortexAlembicPolyMeshDeform")[0]
			setupReaderAttribute(reader, identifier, isConstant, jobInfo)

		#if not useDynTopo:
		#	setupReaderAttribute(topoReader, identifier, isConstant, jobInfo)

	except:
		return [traceback.format_exc()]
	finally:
		cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._import.importPolyMesh")
	return [shape, reader]
示例#21
0
文件: _attach.py 项目: skarone/PipeL
def attachCurves(name, identifier, jobInfo, isConstant=False):
	cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._attach.attachCurves")
	if cmds.objExists( name ):
		curObj = cmds.connectionInfo(name+".visibility", sfd=True)
		if curObj and cmds.objectType(curObj) == "ExocortexAlembicCurvesDeform":
			attachTimeAndFile(curObj, jobInfo, isConstant)
			return

		# create deformer, and attach time and file
		newDform = cmds.deformer(name, type="ExocortexAlembicCurvesDeform")[0]
		cmds.setAttr(newDform+".identifier", identifier, type="string")
		attachTimeAndFile(newDform, jobInfo, isConstant)

		# get curObj new "output" attribute connection
		if cmds.objExists( curObj ):
			if curObj != None and cmds.objectType(curObj) != "ExocortexAlembicCurves":
				originalCur = cmds.connectionInfo(curObj+".output", sfd=True).split('.')[0]

				cmds.delete(curObj)
				curObj = cmds.createNode("ExocortexAlembicCurves")
				attachTimeAndFile(curObj, jobInfo, isConstant)

				cmds.connectAttr(curObj+".outCurve", originalCur+".create")
				cmds.connectAttr(jobInfo.filenode+".outFileName", curObj+".fileName")
				cmds.setAttr(curObj+".identifier", identifier, type="string")

	cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._attach.attachCurves")
	pass
def ShapeInverterCmdold(base=None, corrective=None, name=None):
    mc.undoInfo(openChunk=True)
    if not base or not corrective:
        sel = mc.ls(sl=True)
        base, corrective = sel
    shapes = mc.listRelatives(base, children=True, shapes=True)
    for s in shapes:
        if mc.getAttr("%s.intermediateObject" % s) and mc.listConnections("%s.worldMesh" % s, source=False):
            origMesh = s
            break
    deformed = mc.polyPlane(ch=False)[0]
    mc.connectAttr("%s.worldMesh" % origMesh, "%s.inMesh" % deformed)
    mc.setAttr("%s.intermediateObject" % origMesh, 0)
    mc.delete(deformed, ch=True)
    mc.setAttr("%s.intermediateObject" % origMesh, 1)
    if not name:
        name = "%s_inverted#" % corrective
    invertedShape = duplicateMesh(base, name=name)
    deformer = mc.deformer(invertedShape, type="ShapeInverter")[0]
    mc.ShapeInverterCmd(baseMesh=base, invertedShape=invertedShape, ShapeInverterdeformer=deformer, origMesh=deformed)
    # correctiveShape = duplicateMesh(base,name=corrective+"_corrective#")
    # mc.connectAttr('%s.outMesh' % getShape(correctiveShape), '%s.correctiveMesh' % deformer)
    # transferMesh(corrective,[correctiveShape])
    mc.connectAttr("%s.outMesh" % getShape(corrective), "%s.correctiveMesh" % deformer)
    mc.setAttr("%s.activate" % deformer, True)
    mc.delete(deformed)
    bdingBx = mc.polyEvaluate(corrective, boundingBox=True)
    xDifVal = bdingBx[0][1] - bdingBx[0][0]
    # mc.move(xDifVal*1.10,correctiveShape,r=True,moveX=True)
    mc.move(xDifVal * 2.20, invertedShape, r=True, moveX=True)
    mc.undoInfo(closeChunk=True)
    return invertedShape  # ,correctiveShape
示例#23
0
def makeWire(dropoffDistance):

    sels = cmds.ls(sl=1)

    last = sels[-1]
    lastShape = cmds.listRelatives(last, s=1)[0]
    baseShape = getBaseShape(last)

    for sel in sels[:-1]:
        wireExists = False
        hists = cmds.listHistory(sel, pdo=1)
        if not hists: hists = []
        for hist in hists:
            if cmds.nodeType(hist) == 'wire':
                wireExists = True
                break
        if wireExists:
            wire = hist
        else:
            wire = cmds.deformer(sel, type='wire')[0]
            cmds.connectAttr(baseShape + '.local', wire + '.baseWire[0]')
            cmds.connectAttr(lastShape + '.local', wire + '.deformedWire[0]')
        cmds.setAttr(wire + '.dropoffDistance[0]', dropoffDistance)

    cmds.select(sels)
示例#24
0
def attachCurves(name, identifier, jobInfo, isConstant=False):
    cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._attach.attachCurves")
    try:
        conX = cmds.listConnections(
            name + ".create", d=False, type="ExocortexAlembicCurvesDeform"
        ) or cmds.listConnections(name + ".create", d=False, type="ExocortexAlembicCurves")
        if conX:
            curObj = conX[0]
            attachTimeAndFile(curObj, jobInfo, isConstant)
            return [curObj]

            # create deformer, and attach time and file
        newDform = cmds.deformer(name, type="ExocortexAlembicCurvesDeform")[0]
        cmds.setAttr(newDform + ".identifier", identifier, type="string")
        attachTimeAndFile(newDform, jobInfo, isConstant)

        # get curObj new "output" attribute connection
        conX = cmds.listConnections(name + ".create", d=False, type="ExocortexAlembicCurvesDeform")
        if conX:
            curObj = conX[0]
            originalCur = cmds.connectionInfo(curObj + ".output", sfd=True).split(".")[0]

            cmds.delete(curObj)
            curObj = cmds.createNode("ExocortexAlembicCurves")
            attachTimeAndFile(curObj, jobInfo, isConstant)

            cmds.connectAttr(curObj + ".outCurve", originalCur + ".create")
            cmds.connectAttr(jobInfo.filenode + ".outFileName", curObj + ".fileName")
            cmds.setAttr(curObj + ".identifier", identifier, type="string")
    except:
        return ["!", traceback.format_exc()]
    finally:
        cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._attach.attachCurves")
    return [curObj]
示例#25
0
def connectSVGShellDeformer(svgMesh, svgTransform, svgExtruder, svgTool, svgAdjuster):
    #apply the type deformer to the mesh
    cmds.select(svgMesh)
    newTypeDeformer = cmds.deformer(type="shellDeformer")[0]
    cmds.connectAttr( svgTool+'.animationPosition', newTypeDeformer+'.animationPosition' )
    cmds.connectAttr( svgTool+'.animationRotation', newTypeDeformer+'.animationRotation' )
    cmds.connectAttr( svgTool+'.animationScale', newTypeDeformer+'.animationScale' )

    cmds.connectAttr( svgTool+'.vertsPerChar', newTypeDeformer+'.vertsPerChar' )

    #time to deformer
    cmds.connectAttr( 'time1.outTime', newTypeDeformer+'.time' )

    #these makes the deformer aware of manipulations (as they affect the pivot point of each character/ word)
    cmds.connectAttr( svgTool+'.solidsPerCharacter', newTypeDeformer+'.solidsPerCharacter' )

    #the points node is used to display the pivot points
    pointsNode = cmds.createNode ('displayPoints', n='displayPoints#')
    pointsTransform = cmds.listRelatives( pointsNode, allParents=True )[0]
    cmds.setAttr( pointsNode+'.hiddenInOutliner', 1 )
    cmds.setAttr( pointsTransform+'.hiddenInOutliner', 1 )
    cmds.connectAttr( newTypeDeformer+'.rotationPivotPointsPP', pointsNode+'.inPointPositionsPP[0]' )
    cmds.connectAttr( newTypeDeformer+'.scalePivotPointsPP', pointsNode+'.inPointPositionsPP[1]' )

    cmds.connectAttr( svgExtruder+'.vertexGroupIds', newTypeDeformer+'.vertexGroupIds' )

    #message connections
    cmds.addAttr( newTypeDeformer, hidden=True, longName='typeMessage', attributeType='message' )
    cmds.connectAttr( svgTool+'.animationMessage', newTypeDeformer+'.typeMessage'  )
示例#26
0
文件: main.py 项目: edart76/edPlugin
def testDeformers(mesh):
    """ test uberDeformer system """
    deformer = cmds.deformer(mesh, type="uberDeformer")[0]
    baseNotion = cmds.createNode("deformerNotion", n="testNotion")

    cmds.connectAttr(baseNotion + ".masterConnection",
                     deformer + ".notions[0]")
示例#27
0
def getTargetMapWeights(bs, target, default_value=0):
    """
    Get target point weight values
    :param bs: BlendShape node
    :param target: String name of target
    :param default_value: When true a -1 is returned if the weights have not been changed from the default
    :return: List if weighs exist, -1 if it is the default value
    """
    # Get point count
    source_geo = mc.deformer(bs, q=1, g=1)[0]
    pnt_count = mc.polyEvaluate(source_geo, v=1) - 1

    # Get index
    targetIndex = getTargetIndex(bs, target)

    # Define attrs
    attr = bs + '.it[0].itg[{}].tw[0:{}]'.format(targetIndex, pnt_count)
    attr_default_test = bs + '.it[0].itg[{}].tw[*]'.format(targetIndex)

    # When no values have ever been set the attribute will not exist
    if not mc.objExists(attr_default_test):
        if default_value:
            values = -1
        else:
            values = [1.0] * (pnt_count + 1)
    else:
        # Get weights
        values = mc.getAttr(attr)

    return values
示例#28
0
def fromSelection(nodes=None):
    """
    :param nodes: [driver1, ... driverN, driven]
    :return: created deformer
    """
    nodes = nodes or mc.ls(sl=True)
    if not nodes:
        return
    driven = nodes.pop()

    nodes = [
        mc.listRelatives(node, type='shape')[0]
        if mc.ls(node, type='transform')
        and mc.listRelatives(node, type='shape') else node for node in nodes
    ]

    deformer = mc.deformer(driven, type=prClosestPoint.nodeTypeName)[0]

    for driver in nodes:
        driverType = mc.ls(driver, showType=True)[1]
        driverAttr = {
            'mesh': 'worldMesh',
            'nurbsCurve': 'worldSpace',
            'nurbsSurface': 'worldSpace',
            'locator': 'worldMatrix',
            'transform': 'worldMatrix'
        }[driverType]
        outputAttr = '{0}.{1}'.format(driver, driverAttr)
        inputParentAttr = '{0}.inputTarget'.format(deformer)
        inputAttr = '{0}[{1}].target'.format(
            inputParentAttr, mc.getAttr(inputParentAttr, size=True))
        mc.connectAttr(outputAttr, inputAttr)
    return deformer
示例#29
0
def importPolyMesh(name, identifier, jobInfo, parentXform=None, isConstant=False, useDynTopo=False):
	cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._import.importPolyMesh")

	try:
		reader = ""
		shape  = fnt.alembicCreateNode(name, "mesh", parentXform)
		cmds.sets(shape, e=True, forceElement="initialShadingGroup")

		topoReader = cmds.createNode("ExocortexAlembicPolyMesh")
		cmds.connectAttr(topoReader+".outMesh", shape+".inMesh")
		cmds.connectAttr(jobInfo.filenode+".outFileName", topoReader+".fileName")
		cmds.setAttr(topoReader+".identifier", identifier, type="string")
		cmds.setAttr(topoReader+".normals", jobInfo.useNormals)
		cmds.setAttr(topoReader+".uvs", jobInfo.useUVs)
		if jobInfo.useFaceSets:
			cmds.ExocortexAlembic_createFaceSets(o=shape, f=jobInfo.filename, i=identifier)

		if useDynTopo:
			cmds.connectAttr(jobInfo.timeCtrl+".outTime", topoReader+".inTime")
			reader = topoReader
		elif not isConstant:
			reader = cmds.deformer(shape, type="ExocortexAlembicPolyMeshDeform")[0]
			setupReaderAttribute(reader, identifier, isConstant, jobInfo)

		#if not useDynTopo:
		#	setupReaderAttribute(topoReader, identifier, isConstant, jobInfo)

	except Exception as ex:
		shape = "?importPolyMesh --> exception: \"" + str(ex.args) + "\" of type " + str(type(ex));
		apix.MPxCommand.setResult(shape)
	cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._import.importPolyMesh")
	return shape
示例#30
0
def importPolyMesh(name, identifier, jobInfo, parentXform=None, isConstant=False, useDynTopo=False):
	cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._import.importPolyMesh")

	try:
		reader = ""
		shape  = fnt.alembicCreateNode(name, "mesh", parentXform)
		cmds.sets(shape, e=True, forceElement="initialShadingGroup")

		topoReader = cmds.createNode("ExocortexAlembicPolyMesh")
		cmds.connectAttr(topoReader+".outMesh", shape+".inMesh")
		cmds.connectAttr(jobInfo.filenode+".outFileName", topoReader+".fileName")
		cmds.setAttr(topoReader+".identifier", identifier, type="string")
		cmds.setAttr(topoReader+".normals", jobInfo.useNormals)
		cmds.setAttr(topoReader+".uvs", jobInfo.useUVs)
		if jobInfo.useFaceSets:
			cmds.ExocortexAlembic_createFaceSets(o=shape, f=jobInfo.filename, i=identifier)

		if useDynTopo:
			cmds.connectAttr(jobInfo.timeCtrl+".outTime", topoReader+".inTime")
			reader = topoReader
		elif not isConstant:
			reader = cmds.deformer(shape, type="ExocortexAlembicPolyMeshDeform")[0]
			setupReaderAttribute(reader, identifier, isConstant, jobInfo)

		#if not useDynTopo:
		#	setupReaderAttribute(topoReader, identifier, isConstant, jobInfo)

	except Exception as ex:
		shape = "?importPolyMesh --> exception: \"" + str(ex.args) + "\" of type " + str(type(ex));
		apix.MPxCommand.setResult(shape)
	cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._import.importPolyMesh")
	return shape
示例#31
0
def attachPolyMesh(name, identifier, jobInfo, isConstant=False):
    cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._attach.attachPolyMesh")
    try:
        if cmds.objectType(name) != "mesh":
            return ["!", "Only mesh can be attached too!"]

        conX = cmds.listConnections(name, d=False, type="ExocortexAlembicPolyMeshDeform")
        if conX:  # it's already attached to a deform, simply change the file reference
            polyObj = conX[0]
            attachTimeAndFile(polyObj, jobInfo, isConstant)
            return [polyObj]

            # create deformer, and attach time and file
        newDform = cmds.deformer(name, type="ExocortexAlembicPolyMeshDeform")[0]
        cmds.setAttr(newDform + ".identifier", identifier, type="string")
        attachTimeAndFile(newDform, jobInfo, isConstant)

        if jobInfo.useFaceSets:
            cmds.ExocortexAlembic_createFaceSets(
                f=cmds.getAttr(jobInfo.filenode + ".outFileName"), i=identifier, o=name
            )
    except:
        return ["!", traceback.format_exc()]
    finally:
        cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._attach.attachPolyMesh")
    return [newDform]
示例#32
0
def addModification( meshObjs ):
    
    import sgBFunction_attribute
    import sgBFunction_dag
    
    meshObjs = sgBFunction_dag.getChildrenMeshExists( meshObjs )
    softMod = cmds.deformer( meshObjs, type='softMod' )[0]
    
    ctlGrp = cmds.createNode( 'transform' )
    cmds.setAttr( ctlGrp+'.dh', 1 )
    dcmp   = cmds.createNode( 'decomposeMatrix' )
    ctl = cmds.sphere()[0]
    ctl = cmds.parent( ctl, ctlGrp )[0]
    sgBFunction_attribute.addAttr( ctl, ln='__________', at='enum', enumName = ':Modify Attr', cb=1 )
    sgBFunction_attribute.addAttr( ctl, ln='falloffRadius', min=0, dv=1, k=1 )
    sgBFunction_attribute.addAttr( ctl, ln='envelope', min=0, max=1, dv=1, k=1 )
    
    cmds.connectAttr( ctlGrp+'.wim', softMod+'.bindPreMatrix' )
    cmds.connectAttr( ctlGrp+'.wm', softMod+'.preMatrix' )
    cmds.connectAttr( ctl+'.wm', softMod+'.matrix' )
    cmds.connectAttr( ctl+'.m',  softMod+'.weightedMatrix' )
    
    cmds.connectAttr( ctlGrp+'.wm', dcmp+'.imat' )
    
    cmds.connectAttr( dcmp+'.ot', softMod+'.falloffCenter' )
    for i in range( len( meshObjs ) ):
        cmds.connectAttr( meshObjs[i]+'.wm', softMod+'.geomMatrix[%d]' % i )
    
    cmds.connectAttr( ctl+'.envelope', softMod+'.envelope' )
    cmds.connectAttr( ctl+'.falloffRadius', softMod+'.falloffRadius' )
    
    cmds.xform( ctlGrp, ws=1, t=cmds.getAttr( meshObjs[0]+'.wm' )[-4:-1] )
    cmds.select( ctlGrp )
示例#33
0
	def create(self,targetList,influenceList,defaultWeightVal=1.0,maxDist=0.0,name='surfaceSkin1'):
		"""
		Create surfaceSkin deformer for the given target list or selection
		@param targetList: list of shapes to bind using surfaceSkin
		@type targetList: list
		@param influenceList: list of influences to affect surfaceSkin
		@type influenceList: list
		@param defaultWeightVal: Default influence weight value assigned to components
		@type defaultWeightVal: float
		@param maxDist: Maximum distance to search for components to affect, from the influence surface
		@type maxDist: float
		@param name: Name for new surfaceSkin node
		@type name str
		"""
		# Load plugin
		if not mc.pluginInfo('isoMuscle',l=1,q=1):
			try: mc.loadPlugin('isoMuscle')
			except: raise MissingPluginError('Unable to load surfaceSkin (isoMuscle) plugin!!')
		
		# Create Deformer
		surfaceSkin = mc.deformer(targetList,type='surfaceSkin',n=name)[0]
		# Add influences
		self.addInfluence(influenceList,surfaceSkin,defaultWeightVal,maxDist,calculatePrebind=False)
		# Ensure surfaceSkin::paintWeight and surfaceSkin::weights are paintable attrs
		self.makePaintable()
		# Return result
		return surfaceSkin
示例#34
0
文件: plot.py 项目: edeglau/storage
 def matchCurveShapes_andShrinkWrap(self, getFirstGrp, getSecondGrp):
     myDict={
             ".shapePreservationEnable":1,
             ".shapePreservationSteps":72,
             ".shapePreservationReprojection":1,
             ".shapePreservationIterations":1,
             ".shapePreservationMethod":0,
             ".envelope":1,
             ".targetSmoothLevel":1,
             ".continuity":1,
             ".keepBorder":0,
             ".boundaryRule":1,
             ".keepHardEdge":0,
             ".propagateEdgeHardness":0,
             ".keepMapBorders":1,
             ".projection":4,
             ".closestIfNoIntersection":0,
             ".closestIfNoIntersection":0 ,
             ".reverse":0,
             ".bidirectional":0,
             ".boundingBoxCenter":1,
             ".axisReference":0 ,
             ".alongX":1,
             ".alongY":1,
             ".alongZ":1,
             ".offset":0,
             ".targetInflation":0,
             ".falloff":0.3021390379,
             ".falloffIterations": 1
             }        
     cmds.delete(getFirstGrp, ch=1)
     getShrink=cmds.deformer(getFirstGrp, type="shrinkWrap")
     cmds.connectAttr(getSecondGrp+".worldMesh[0]", getShrink[0]+".targetGeom", f=1)
     for key, value in myDict.items():
         cmds.setAttr(getShrink[0]+key, value)
示例#35
0
    def __init__(self, config, blendshape='blendShapeMain', anchor_weight=1.0):
        """
        init function
        :param str config: .ini file containing configuration information
        :param str blendshape: name of the blendshape node to apply the prediction
        :param float anchor_weight: how much weight should be given to anchor points for differential coordinates
                                    solve. Does nothing for local_offset prediction
        """
        super(RigPoseApplier, self).__init__(config)
        self.pose_data = None
        self.prediction_data = {}
        self.blendshape = blendshape
        self.vertex_ids = {}
        self.anchor_weight = anchor_weight
        self.error_history = error.ErrorHistory()
        self._laplacian_row = None
        self._laplacian_col = None
        self._laplacian_val = None
        self._laplacian_matrix = None
        self._valences = []
        self._cholesky_matrix = None
        self._reverse_cuthill_mckee_order = None
        self._inverse_cmo = None

        try:
            self._mesh = mc.deformer(self.blendshape,
                                     query=True,
                                     geometry=True)[0]
        except ValueError:
            self._mesh = None
示例#36
0
 def sqCreateStikyLipsDeformers(self, *args):
     baseMesh = None
     mainCurveList = [self.mainCurveA, self.mainCurveB]
     for mainCurve in mainCurveList:
         if baseMesh == None:
             baseMesh = cmds.duplicate(self.receptList[0], name=self.receptList[0]+"Base")[0]
             cmds.setAttr(baseMesh+".visibility", 0)
         
         wrapNode = cmds.deformer(mainCurve, name="StickyLips_Wrap", type="wrap")[0]
         try:
             cmds.connectAttr(self.receptList[0]+".dropoff", wrapNode+".dropoff[0]", force=True)
             cmds.connectAttr(self.receptList[0]+".inflType", wrapNode+".inflType[0]", force=True)
             cmds.connectAttr(self.receptList[0]+".smoothness", wrapNode+".smoothness[0]", force=True)
             cmds.connectAttr(self.receptList[0]+"Shape.worldMesh[0]", wrapNode+".driverPoints[0]", force=True)
         except:
             pass
         
         cmds.connectAttr(baseMesh+"Shape.worldMesh[0]", wrapNode+".basePoints[0]", force=True)
         cmds.connectAttr(mainCurve+"Shape.worldMatrix[0]", wrapNode+".geomMatrix", force=True)
         cmds.setAttr(wrapNode+".maxDistance", 1)
         cmds.setAttr(wrapNode+".autoWeightThreshold", 1)
         cmds.setAttr(wrapNode+".exclusiveBind", 1)
         
     baseCurveList = [self.baseCurveA, self.baseCurveB]
     for c, baseCurve in enumerate(baseCurveList):
         wireNode = cmds.wire(self.receptList[1], name=baseCurve+"_Wire", groupWithBase=False, crossingEffect=0, localInfluence=0)[0]
         cmds.connectAttr(mainCurveList[c]+"Shape.worldSpace[0]", wireNode+".baseWire[0]", force=True)
         cmds.connectAttr(baseCurve+"Shape.worldSpace[0]", wireNode+".deformedWire[0]", force=True)
         self.wireNodeList.append(wireNode)
         
         wireLocList = []
         for i in range(0, self.maxIter):
             wireLocList.append(baseCurve+".u["+str(i)+"]")
         cmds.dropoffLocator(1, 1, wireNode, wireLocList)
示例#37
0
def dynamic_compare(mesh, target, clamp=1, saturation=1):
    """
    Compares two meshes dynamically.
    This requires that the meshCompare plugin be compiled and available in the plugin path.

    :param mesh: The mesh you want to view the changes on.
    :param target: The mesh you are comparing against
    :param clamp: The value to clamp against. All values be scaled accordingly.
                  i.e if you clamp at 10, absolute red will be 10 units
    :param saturation: The maximum saturation value to use
    """

    loaded = mc.pluginInfo('meshCompare', query=True, loaded=True)
    if not loaded:
        try:
            mc.loadPlugin('meshCompare')
        except:
            mc.error("Could not load meshCompare plugin."
                     "Please make sure it is compiled and in your plugin path")

    mesh = get_shape(mesh)
    target = get_shape(target)

    mesh_path = mesh.fullPathName()
    target_path = target.fullPathName()

    mc.polyOptions(mesh_path, colorShadedDisplay=True)
    deformer = mc.deformer(mesh_path, type='meshCompare')[0]
    mc.polyOptions(mesh_path, colorShadedDisplay=True)

    mc.connectAttr('%s.outMesh' % target_path, '%s.target' % deformer)

    mc.setAttr('%s.saturation' % deformer, saturation)
    mc.setAttr('%s.clamp' % deformer, clamp)
示例#38
0
 def redoIt(self):
     self.deformerNode = mc.deformer(self.targetGeo,
                                     type='adbResetDeltaDeformer')[0]
     shape = pm.PyNode(self.baseGeo).getShape()
     mc.connectAttr('{}.outMesh'.format(shape),
                    '{}.blendMesh'.format(self.deformerNode))
     mc.setAttr('{}.percentage'.format(self.deformerNode), self.percentage)
示例#39
0
def attachPolyMesh(name, identifier, jobInfo, isConstant=False):
    cmds.ExocortexAlembic_profileBegin(
        f="Python.ExocortexAlembic._attach.attachPolyMesh")
    if cmds.objExists(name):
        if cmds.objectType(name) != "mesh":
            print("Only mesh can be attached too!")
            cmds.ExocortexAlembic_profileEnd(
                f="Python.ExocortexAlembic._attach.attachPolyMesh")
            return

        polyObj = cmds.connectionInfo(
            name + ".inMesh",
            sfd=True).split('.')[0]  # cmds.plugNode doesn't exist!
        if polyObj and cmds.objectType(
                polyObj
        ) == "ExocortexAlembicPolyMeshDeform":  # it's already attached to a deform, simply change the file reference
            attachTimeAndFile(polyObj, jobInfo, isConstant)
            return

        # create deformer, and attach time and file
        newDform = cmds.deformer(name,
                                 type="ExocortexAlembicPolyMeshDeform")[0]
        cmds.setAttr(newDform + ".identifier", identifier, type="string")
        attachTimeAndFile(newDform, jobInfo, isConstant)

        if jobInfo.useFaceSets:
            cmds.ExocortexAlembic_createFaceSets(
                f=cmds.getAttr(jobInfo.filenode + ".outFileName"),
                i=identifier,
                o=name)

    cmds.ExocortexAlembic_profileEnd(
        f="Python.ExocortexAlembic._attach.attachPolyMesh")
    pass
示例#40
0
def remove_from_system():
    # on selectionne une liste de mesh.
    depart = mc.ls(sl=True)
    if len(depart) == 0:
        return
    for mesh in depart:
        swName = mc.listHistory(mesh)[2]
        if mc.getAttr(swName + '.envelope') == 1:
            mc.setAttr(swName + '.envelope', 0)
            mc.deformer(e=True, rm=True, g=mesh, swName)
            #cmd =str('deformer -e -rm -g "{}" "shrinkWrap_facial"'.format(mesh))
            #mel.eval(cmd)
            mc.skinCluster(mesh, e=True, ub=True)
            cleanM = '{}.output'.format(mc.listHistory(mesh)[1])
            mc.disconnectAttr(cleanM, mesh + '.inMesh')
        mc.setAttr(swName + '.envelope', 1)
示例#41
0
def attachPolyMesh(name, identifier, jobInfo, isConstant=False):
    cmds.ExocortexAlembic_profileBegin(
        f="Python.ExocortexAlembic._attach.attachPolyMesh")
    try:
        if cmds.objectType(name) != "mesh":
            return ["!", "Only mesh can be attached too!"]

        conX = cmds.listConnections(name,
                                    d=False,
                                    type="ExocortexAlembicPolyMeshDeform")
        if conX:  # it's already attached to a deform, simply change the file reference
            polyObj = conX[0]
            attachTimeAndFile(polyObj, jobInfo, isConstant)
            return [polyObj]

        # create deformer, and attach time and file
        newDform = cmds.deformer(name,
                                 type="ExocortexAlembicPolyMeshDeform")[0]
        cmds.setAttr(newDform + ".identifier", identifier, type="string")
        attachTimeAndFile(newDform, jobInfo, isConstant)

        if jobInfo.useFaceSets:
            cmds.ExocortexAlembic_createFaceSets(
                f=cmds.getAttr(jobInfo.filenode + ".outFileName"),
                i=identifier,
                o=name)
    except:
        return ["!", traceback.format_exc()]
    finally:
        cmds.ExocortexAlembic_profileEnd(
            f="Python.ExocortexAlembic._attach.attachPolyMesh")
    return [newDform]
示例#42
0
    def create(name='psd'):

        if not cmds.pluginInfo(PLUGIN, q=1, loaded=1):
            pluginPath = os.path.join(PLUGINPATH, PLUGIN)
            cmds.loadPlugin(pluginPath)

        sel = cmds.ls(sl=1)
        if not sel:
            raise RuntimeError('Objects should be selected to create PSD')

        if cmds.nodeType(sel[0]) == 'transform':
            sel = cmds.listRelatives(sel[0], c=1)

        if cmds.nodeType(sel[0]) != 'mesh':
            raise RuntimeError('PSD can be created only on mesh')

        # Find skinCluster
        skinCluster = None
        history = cmds.listHistory(sel[0]) or []
        for h in history:
            if cmds.nodeType(h) == 'skinCluster':
                skinCluster = h

        if not skinCluster:
            raise RuntimeError(
                'PSD can only be created on mesh with skinCluster')

        name = cmds.deformer(type=NODETYPE, name=name)[0]

        cmds.connectAttr(skinCluster + '.weightList',
                         name + '.skinClusterWeightList')

        return PoseSpaceDeformer(name)
示例#43
0
def attachCurves(name, identifier, jobInfo, isConstant=False):
    cmds.ExocortexAlembic_profileBegin(
        f="Python.ExocortexAlembic._attach.attachCurves")
    if cmds.objExists(name):
        curObj = cmds.connectionInfo(name + ".visibility", sfd=True)
        if curObj and cmds.objectType(
                curObj) == "ExocortexAlembicCurvesDeform":
            attachTimeAndFile(curObj, jobInfo, isConstant)
            return

        # create deformer, and attach time and file
        newDform = cmds.deformer(name, type="ExocortexAlembicCurvesDeform")[0]
        cmds.setAttr(newDform + ".identifier", identifier, type="string")
        attachTimeAndFile(newDform, jobInfo, isConstant)

        # get curObj new "output" attribute connection
        if cmds.objExists(curObj):
            if curObj != None and cmds.objectType(
                    curObj) != "ExocortexAlembicCurves":
                originalCur = cmds.connectionInfo(curObj + ".output",
                                                  sfd=True).split('.')[0]

                cmds.delete(curObj)
                curObj = cmds.createNode("ExocortexAlembicCurves")
                attachTimeAndFile(curObj, jobInfo, isConstant)

                cmds.connectAttr(curObj + ".outCurve", originalCur + ".create")
                cmds.connectAttr(jobInfo.filenode + ".outFileName",
                                 curObj + ".fileName")
                cmds.setAttr(curObj + ".identifier", identifier, type="string")

    cmds.ExocortexAlembic_profileEnd(
        f="Python.ExocortexAlembic._attach.attachCurves")
    pass
示例#44
0
def mirrorDeformer(middleEdge,deformer,search='lf',replace='rt'):
	'''
	'''
	# Load plugin
	loadPlugin()
	
	# Get Mesh Data
	mesh = mc.ls(middleEdge,o=True)[0]
	vmap = mm.eval('edgeFlowMirror -task "getMapArray" -middleEdge '+middleEdge)
	
	# Mirror Membership
	mem = glTools.utils.deformer.getDeformerSetMemberIndices(deformer,mesh)
	if len(vmap) > len(mem): mem = sorted([vmap[i] for i in mem])
	mem = [mesh+'.vtx['+str(i)+']' for i in mem]
	
	# Create Mirror Deformer
	deformerType = mc.objectType(deformer)
	deformerName = deformer
	if deformerName.startswith(search): deformerName = deformerName.replace(search,replace)
	elif deformerName.startswith(replace): deformerName = deformerName.replace(replace,search)
	else: deformerName = deformerName+'_mirror'
	
	mDeformer = mc.deformer(mem,type=deformerType,name=deformerName)[0]
	
	# Mirror Deofmer Weights
	mirrorDeformerWeights(middleEdge,deformer,dstDeformer=mDeformer)
	
	# Return Result
	return mDeformer
示例#45
0
 def _setup_plugin(self):
     collider = cmds.polySphere()[0]
     target = cmds.polySphere(subdivisionsAxis=20, subdivisionsHeight=20)[0]
     #         target = cmds.polyCube()
     plugin = cmds.deformer(target, type=self.name)[0]
     cmds.connectAttr('%s.worldInverseMatrix' % collider,
                      '%s.volumeInverseMatrix' % plugin)
示例#46
0
    def _setup_plugin(self):
        collider = cmds.polySphere()[0]
        target = cmds.polySphere(subdivisionsAxis=20,
                                 subdivisionsHeight=20)[0]
#         target = cmds.polyCube()
        plugin = cmds.deformer(target, type=self.name)[0]
        cmds.connectAttr('%s.worldInverseMatrix' % collider,
                         '%s.volumeInverseMatrix' % plugin)
def create(mesh=None):
    _load_plugin()
    if mesh is None:
        sel = cmds.ls(sl=True, l=True)
        if not sel or len(sel) != 1:
            OpenMaya.MGlobal.displayError('Select a mesh.')
            return
        mesh = sel[0]

    return cmds.deformer(mesh, type='zMappedWrapDeformer')[0]
示例#48
0
def setKeyCurve( keyCurve, targetCurve, objBaseMatrix = None ):
    
    import sgBFunction_dag
    import sgBFunction_base
    
    sgBFunction_base.autoLoadPlugin( 'sgHair' )
    
    nodes = sgBFunction_dag.getNodeFromHistory( targetCurve, 'sgHair_keyCurve' )
    if not nodes:
        node = cmds.deformer( targetCurve, type= 'sgHair_keyCurve' )[0]
        cmds.connectAttr( 'time1.outTime', node+'.time' )
        if objBaseMatrix:
            mm = cmds.createNode( 'multMatrix' )
            cmds.connectAttr( objBaseMatrix+'.wm', mm+'.i[0]' )
            cmds.connectAttr( targetCurve+'.wim', mm+'.i[1]' )
            cmds.connectAttr( mm+'.o', node+'.baseLocalMatrix' )
    else:
        node = nodes[0]
    
    fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( node ) )
    
    cuTime   = cmds.currentTime( q=1 )
    plugKeys = fnNode.findPlug( 'keys' )
    
    targetIndex = 0
    for i in range( plugKeys.numElements() ):
        plugKey = plugKeys[i]
        
        plugFrame = plugKey.child( 0 )
        timeValue = plugFrame.asMTime().value()
        
        if cuTime == timeValue:
            targetIndex = plugKey.logicalIndex()
            break
        
        if plugKey.logicalIndex() >= targetIndex:
            targetIndex = plugKey.logicalIndex() + 1
    
    if objBaseMatrix:
        import sgBFunction_convert
        mtxObj = cmds.getAttr( objBaseMatrix+'.wm' )
        mtxInvCurve = cmds.getAttr( keyCurve+'.wim' )
        
        mMtxObj = sgBFunction_convert.convertMatrixToMMatrix( mtxObj )
        mMtxInvCurve = sgBFunction_convert.convertMatrixToMMatrix( mtxInvCurve )
        
        mMtxLocal = mMtxObj * mMtxInvCurve
        mtxLocal = sgBFunction_convert.convertMMatrixToMatrix( mMtxLocal )
        cmds.setAttr( node+'.keys[%d].baseMatrix' % targetIndex, mtxLocal, type='matrix' )
    cmds.setAttr( node+'.keys[%d].keyframe' % targetIndex, cuTime )
    keyCurveShape = sgBFunction_dag.getShape( keyCurve )
    if not cmds.isConnected( keyCurveShape+'.local', node+'.keys[%d].inputCurve' % targetIndex ):
        cmds.connectAttr( keyCurveShape+'.local', node+'.keys[%d].inputCurve' % targetIndex, f=1 )
    
    '''
 def initPlugin(self, deformerType):
     meshes = pm.selected( type="transform" )
     if len(meshes)<2:
         return
     pm.select( meshes[-1])
     deformer = cmds.deformer(type=deformerType)[0]
     shape=meshes[-2].getShapes()[0]
     cmds.connectAttr(shape+".worldMesh[0]", deformer+".cageMesh")
     # Make deformer weights paintable
     cmds.makePaintable(deformerType, 'weights', attrType='multiFloat', shapeMode='deformer')
     self.updateUI()
示例#50
0
    def _setup_plugin(self):
        points = [[n, 0, 0] for n in range(self.length)]
        crv = cmds.curve(n='C_test_CRV', p=points)
        shp = cmds.rename(cmds.listRelatives(crv, ad=True)[0], '%sShape' % crv)
#         geo = cmds.polyCylinder(n='C_test_GEO', ax=[1, 0, 0], h=points[-1][0],
#                                 sy=self.length * 2, sz=1, ch=False)[0]
        geo = cmds.polySphere(n='C_test_GEO', ch=False)[0]
        cmds.setAttr('%s.tx' % crv, - (points[-1][0] / 2.0))
        wire = cmds.deformer(geo, type=self.plugin)[0]
        cmds.connectAttr('%s.worldMatrix' % shp, '%s.inCurveMatrix' % wire)
        cmds.connectAttr('%s.worldSpace' % shp, '%s.inCurve' % wire)
示例#51
0
def pruneMembershipByWeights(deformer, geoList=[], threshold=0.001):
    """
    Remove components from a specified deformer set if there weight value is below the set threshold
    @param deformer: Deformer to removed components from
    @type deformer: str
    @param geoList: The geometry objects whose components are checked for removal
    @type geoList: list
    @param threshold: The weight threshold for removal
    @type threshold: str
    """
    # Check deformer
    if not cmds.objExists(deformer):
        raise Exception('Deformer "' + deformer + '" does not exist!')

    # Check geometry
    if type(geoList) == str: geoList = [geoList]
    if not geoList: geoList = cmds.deformer(deformer, q=True, g=True)
    if not geoList: raise Exception('No geometry to prune weight for!')
    for geo in geoList:
        if not cmds.objExists(geo):
            raise Exception('Geometry "' + geo + '" does not exist!')

    # Get deformer set
    deformerSet = getDeformerSet(deformer)

    # For each geometry
    allPruneList = []
    for geo in geoList:

        # Get Component Type
        geoType = glTools.utils.geometry.componentType(geo)

        # Get Deformer Member Indices
        memberIndexList = getDeformerSetMemberIndices(deformer, geo)

        # Get Weights
        weightList = getWeights(deformer, geo)

        # Get Prune List
        pruneList = [memberIndexList[i] for i in range(len(memberIndexList)) if weightList[i] <= threshold]
        for i in range(len(pruneList)):
            if type(pruneList[i]) == str or type(pruneList[i]) == unicode or type(pruneList[i]) == int:
                pruneList[i] = '[' + str(pruneList[i]) + ']'
            elif type(pruneList[i]) == list:
                pruneList[i] = [str(p) for p in pruneList[i]]
                pruneList[i] = '[' + ']['.join(pruneList[i]) + ']'
            pruneList[i] = geo + '.' + geoType + str(pruneList[i])
        allPruneList.extend(pruneList)

        # Prune deformer set membership
        if pruneList: cmds.sets(pruneList, rm=deformerSet)

    # Return prune list
    return allPruneList
示例#52
0
    def create(self):

        woHold = dict(self.wrapOptions)
        for wo in woHold:
            if (isinstance(self.wrapOptions[wo], basestring) and self.wrapOptions[wo] == "") or (
                isinstance(self.wrapOptions[wo], bool) and self.wrapOptions[wo] == False
            ):
                del (self.wrapOptions[wo])
        self.wrapOptions["type"] = "wrap"

        if len(self.deformed) > 0:

            self.deformed[0] = shape(self.deformed[0])

            if len(iterable(mc.listHistory(self.deformed[0]))) == 0:
                duplicateShape(self.deformed[0], ah=True)

            self[:] = mc.deformer(self.deformed[0], **self.wrapOptions)

        if len(self.deformed) > 1:

            i = 1
            for d in self.deformed[1:]:

                d = self.deformed[i] = shape(d)

                mc.deformer(self[0], e=True, g=d)

                new = mc.listConnections(self[0] + ".og[" + str(i) + "]", sh=True)[0]

                if d != new and mc.objExists(new):  # new node has been created - rename

                    mc.rename(d, d + "Orig#")
                    mc.rename(new, d)

                i += 1

        mc.setAttr(self[0] + ".maxDistance", self.maxDistance)

        if self.exclusiveBind:
            mc.setAttr(self[0] + ".exclusiveBind", True)
示例#53
0
 def shrink_intersections(self):
     myDict={
     ".alongX":0,
     ".alongY":0,
     ".alongZ":0,
     ".axisReference":0,
     ".bidirectional":0,
     ".boundaryRule":1,
     ".boundingBoxCenter":1,
     ".caching":0,
     ".closestIfNoIntersection":0,
     ".continuity":1.0,
     ".envelope":1.0,
     ".falloff":0.4185185189,
     ".falloffIterations":54,
     ".fchild1":0,
     ".fchild2":0,
     ".fchild3":0,
     ".frozen":0,
     ".innerGeom":0,
     ".innerGroupId":0,
     ".inputEnvelope":[()],
     ".isHistoricallyInteresting":2,
     ".keepBorder":0,
     ".keepHardEdge":0,
     ".keepMapBorders":1,
     ".nodeState":0,
     ".offset":0.03237410082,
     ".projection":1,
     ".propagateEdgeHardness":0,
     ".reverse":1,
     ".shapePreservationEnable":0,
     ".shapePreservationIterations":1,
     ".shapePreservationMethod":0,
     ".shapePreservationReprojection":0,
     ".shapePreservationSteps":1,
     ".smoothUVs":1,
     ".targetGeom":0,
     ".targetInflation":0.06115107902,
     ".targetSmoothLevel":1,
     }
     getSel=self.selection_grab()
     if getSel:
         pass
     else:
         return
     getShrink=cmds.deformer(getSel[0], type="shrinkWrap")
     cmds.connectAttr(getSel[1]+".worldMesh[0]", getShrink[0]+".targetGeom", f=1)
     for key, value in myDict.items():
         try:
             cmds.setAttr(getShrink[0]+key, value)        
         except:
             pass
示例#54
0
def create(geo,name=''):
	'''
	'''
	# Load Plugin
	if not mc.pluginInfo('tangentBlendDeformer',q=True,l=True): mc.loadPlugin('tangentBlendDeformer')
	
	# Create Deformer
	if not name: name = geo+'_tangentBlendDeformer'
	tangentBlend = mc.deformer(geo,type='tangentBlendDeformer',n=name)[0]
	
	# Return Result
	return tangentBlend 
示例#55
0
 def initPlugin(self, type):
     meshes = pm.selected(tr=1)
     if not meshes:
         return
     pm.select( meshes[-1])
     deformer = pm.ls(cmds.deformer(type=type)[0])[0]
     for i in range(len(meshes)-1):
         deformer.bw[i].set(0.0)
         shape=meshes[i].getShapes()[0]
         cmds.connectAttr(shape+".outMesh", deformer+".blendMesh[%s]" %(i))
         pm.aliasAttr(meshes[i].name(), deformer.bw[i].name())
     self.updateUI()
def createShadowDeformer(objs,nurbs):
    if(len(objs)>0):
        for obj in objs:
            sdNode=cmds.deformer(obj,type='shadowDeformer',name=obj+'_shadowDeformer')
            sdNode=sdNode[0]
            nurbsShape=cmds.ls(nurbs,dag=True,s=True)
            nurbsShape=nurbsShape[0]
            cmds.connectAttr(nurbsShape+'.outMesh',sdNode+'.inputSurface',f=True)
            cmds.connectAttr(nurbs+'.worldMatrix[0]',sdNode+'.inputMatrix',f=True)
            distances=getlistHight(obj,nurbs)
            for i in range(0,len(distances)):
                cmds.setAttr(sdNode+'.hights['+str(i)+']',distances[i])
示例#57
0
def deltaMush(geo):
    """
    Create a deltaMush deformer for the specifed geometry.
    @param geo: The geometry to create the deltaMush deformer for
    @type geo: str
    """
    # ==========
    # - Checks -
    # ==========

    # Check Geometry
    if not cmds.objExists(geo):
        raise Exception('Object "' + geo + '" does not exist!!')

    # Mesh Shape
    if not glTools.utils.mesh.isMesh(geo):
        raise Exception('Object "' + geo + '" is not a valid mesh!!')
    shape = cmds.listRelatives(geo, s=True, ni=True)
    if not shape:
        raise Exception('Object "' + geo + '" has no deformable geometry!!')

    # Load Plugin
    if not cmds.pluginInfo('deltaMush', q=True, l=True):

        # Load Plugin
        try:
            cmds.loadPlugin('deltaMush')
        except:
            raise Exception('Unable to load glToolsTools plugin!')

    # Get Prefix
    prefix = geo.split(':')[-1]

    # ===================
    # - Create Deformer -
    # ===================

    deltaMush = cmds.deformer(geo, type='deltaMush', n=prefix + '_deltaMush')[0]

    # Connect Ref Mesh Shape
    inputMesh = None
    try:
        inputMesh = glTools.utils.shape.findInputShape(shape[0], recursive=True)
    except:
        pass
    if inputMesh: cmds.connectAttr(inputMesh + '.outMesh', deltaMush + '.referenceMesh', f=True)

    # =================
    # - Return Result -
    # =================

    return deltaMush