예제 #1
0
파일: lattice.py 프로젝트: xtoof/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)
예제 #2
0
def myLattice():
	
	valX = cmds.intField("lValX", q=True, value=True)
	valY = cmds.intField("lValY", q=True, value=True)
	valZ = cmds.intField("lValZ", q=True, value=True)
	
	cmds.lattice( dv=(valX,valY,valZ) )
예제 #3
0
  def generate(cls, *args):
    components = []
    radius = cmds.intSliderGrp(cls.get_prefix() + Labels["radius_label"], query=True, value=True)
    height = cmds.intSliderGrp(cls.get_prefix() + Labels["height_label"], query=True, value=True)
    subdivs = cmds.intSliderGrp(cls.get_prefix() + Labels["subdivs_label"], query=True, value=True)
    rgb = cmds.colorSliderGrp(cls.get_prefix() + Labels["color_label"], query=True, rgbValue=True)
    wheel_radius = radius * Constants["wheel_radius_unit"]
    wheel_height = height * Constants["wheel_height_unit"]
    
    wheel_component = cmds.polyPipe(name=get_unique_name(cls.get_prefix(), "cylender"), sh=4, sc=subdivs, h=wheel_height, r=wheel_radius)
    wheel_extrusion_faces = []
    cmds.select(r=True)

    for i in range(0, subdivs):
      if i % 2 == 1:
        facet_title = wheel_component[0] + ".f[" + str(i) + "]"
        wheel_extrusion_faces.append(facet_title)

    #cmds.polyExtrudeFacet(wheel_extrusion_faces, ltz=Constants["wheel_ridge_depth"])
    cmds.delete(ch=1)
    cmds.lattice(wheel_component[0],divisions=[2,3,2], name=get_unique_name(cls.get_prefix(),"lattice"), cp=wheel_component[0])
    shader = cmds.shadingNode('blinn', asShader=True, name=get_unique_name(cls.get_prefix(),"mat"))
    cmds.setAttr(shader + ".color", rgb[0],rgb[1],rgb[2], type='double3')
    cmds.select(wheel_component[0], r=True)
    cmds.hyperShade(assign=shader)
예제 #4
0
파일: jimboRibbon.py 프로젝트: radvfx/py
def initializeRibbon(initWidth):
	mc.polyPlane(sx = 240, sy = 2.0, n = "ribbonTemp", w = initWidth, h = 0.165)
	mc.rename("polyPlane1", "ribbonTempHistory")
	mc.polySoftEdge( a = 180)
	mc.lattice( n = 'ribbon', cp = True, dv = (2, 4, 2), objectDentered = True, ldv = (2, 3, 2), outsideLattice = True )
        mc.hide()
	mc.select('ribbonTempHistory.vtx[1]', r=True )
	mc.ChamferVertex()
	mc.rename( "polyChamfer1", "tempChamfer" )
	mc.seAttr( 'tempChamfer.width', 1)
	mc.delete( 'ribbonTemp.vtx[72]' )
	return
예제 #5
0
파일: jimboBalloon.py 프로젝트: radvfx/py
def initializeBalloon(initRadius):
	mc.polySphere(sx = 12, sy = 8, n = "balloonTemp", r = initRadius)
	mc.rename( "polySphere1", "balloonTempHistory")
	mc.polySoftEdge( a = 180 )
	mc.lattice( n = 'balloon', cp = True, dv = (2, 4, 2), objectCentered = True,  ldv = (2, 3, 2), outsideLattice = True )
	mc.hide()
	mc.select('balloonTemp.vtx[84]', r=True)
	mc.ChamferVertex()
	mc.rename( "polyChamfer1", "tempChamfer" )
	mc.setAttr( 'tempChamfer.width', .1 )
	mc.delete( 'balloonTemp.f[72]' )
	return
예제 #6
0
파일: head.py 프로젝트: skarone/PipeL
	def __init__(self, objs = [], vertices = []):
		self.objs = objs
		self.vertices = vertices
		#lattice  -divisions 2 3 2 -objectCentered true  -ol 1;
		#mc.select( self.objs, self.vertices )
		#CREATION
		grp = mn.Node( mc.group( n = "head_toon_GRP", em = True ) )
		deGrp = mn.Node( mc.group( n = "head_toon_deformer_GRP", em = True ) )
		deGrp.parent = grp
		deGrp.a.v.v = False
		deGrp.a.v.locked = True
		latNods = mc.lattice( self.objs, self.vertices, divisions = [ 2,3,2], objectCentered = True, ol = 1, n = 'head_toon_LAT' )
		latBase = mn.Node( latNods[2] )
		latBase.parent = deGrp
		lat = mn.Node( latNods[1] )
		lat.parent = deGrp
		#mc.select( lat + ".pt[0:1][2][0]", lat + ".pt[0:1][2][1]" )
		topClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][2][0]", lat.shape.name + ".pt[0:1][2][1]", n = 'top_face_toon_CLU' )[1] )
		topClus.a.v.v = False
		topClus.a.v.locked = True
		#mc.select( lat + ".pt[0:1][1][0]", lat + ".pt[0:1][1][1]" )
		midClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][1][0]", lat.shape.name + ".pt[0:1][1][1]", n = 'mid_face_toon_CLU' )[1] )
		#mc.select( lat + ".pt[0:1][0][0]", lat + ".pt[0:1][0][1]" )
		lowClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][0][0]", lat.shape.name + ".pt[0:1][0][1]", n = 'low_face_toon_CLU' )[1] )
		ctl = crv.Curve( "head_toon_CTL" )
		ctl = ctl.create( "sphere" )
		ctl.a.t.v = topClus.worldPosition
		mc.makeIdentity( ctl.name, apply = True, t = 1, r = 1, s = 1, n = 2 )
		topClus.parent = ctl
		midClus.parent = deGrp
		lowClus.parent = deGrp
		ctl.parent = grp
		#CONSTRAINS
		midClus.a.r >> topClus.a.r
		mc.pointConstraint( topClus.name, lowClus.name, midClus.name, mo = True )
		#SCALE FOR MID CLUSTER
		dist = mn.createNode( 'distanceBetween', n = 'head_toon_DIS' )
		ctl.a.worldMatrix >> dist.a.inMatrix1
		ctl.a.rp >> dist.a.point1
		lowClus.a.worldMatrix >> dist.a.inMatrix2
		lowClus.a.rp >> dist.a.point2
		mul = mn.createNode( 'multiplyDivide', n = 'head_toon_scale_MUL' )
		mul.a.input1.v = [dist.a.distance.v]*3
		mul.a.operation.v = 2
		dist.a.distance >> mul.a.input2X
		dist.a.distance >> mul.a.input2Y
		dist.a.distance >> mul.a.input2Z
		mul.a.output >> midClus.a.s
		#AIM CONSTRAINT
		upLocGrp = mn.Node( mc.group( n = "head_upVector_GRP", em = True ) )
		upLocGrp.a.t.v = midClus.worldPosition
		mc.makeIdentity( upLocGrp.name, apply = True, t = 1, r = 1, s = 1, n = 2 )
		upLocGrp.parent = deGrp
		mc.orientConstraint( ctl.name, lowClus.name, upLocGrp.name, mo = True )
		upLoc = mn.Node( mc.spaceLocator( n = 'head_upVector_LOC' )[0] )
		upLoc.a.t.v = midClus.worldPosition
		upLoc.a.tz.v = upLoc.a.tz.v + 5
		mc.aimConstraint( topClus.name, midClus.name, mo = True, weight = 1, aimVector = [1, 0, 0], upVector = [0, 1, 0], worldUpType = "object", worldUpObject = upLoc.name )
		upLoc.parent = upLocGrp
		mc.pointConstraint( topClus.name, lowClus.name, upLoc.name, mo = True )
예제 #7
0
파일: tools_list.py 프로젝트: jonntd/Public
def setup_blendshape_lattice(side = None, 
                             blendShape = None, 
                             divisions = [2,5,2], 
                             ldv = [2,2,2],
                             parent = None):
    #--- this method setups the lattice deformer
    lat = cmds.lattice(blendShape, 
                       divisions = divisions, 
                       objectCentered = True, 
                       ldv = ldv)
    cmds.setAttr(lat[1] + '.v', 0)
    cmds.parent(lat, 'Shapes')

    points = cmds.ls(lat[1] + '.pt[*]', flatten = True)
    for point in range(len(points)):
        pos = cmds.xform(points[point], query = True, translation = True, worldSpace = True)
        cPoint = node.nControl(position = pos, 
                               color = 17, 
                               size = 1, 
                               shape = 1, 
                               side = side, 
                               description = "latPoint" + str(point), 
                               parent = parent, 
                               rotateOrder = 2)
        cmds.setAttr(cPoint.control['transform'] + '.v', lock = False)
        cmds.connectAttr('C_bedMid_CTL.latticeControls', cPoint.control['transform'] + '.v')
        cls = cmds.cluster(points[point], name = side + '_latCluster' + str(point) + '_CLS')
        for axis in 'xyz':
            cmds.connectAttr(cPoint.control['transform'] + '.t' + axis, cls[1] + '.t' + axis)
        cmds.parent(cls[1], 'Shapes')
        cmds.setAttr(cls[1] + '.v', 0)
예제 #8
0
	def rebuild(self):
		'''
		Rebuild the lattice deformer from the recorded deformerData
		'''
		# Rebuild deformer
		ffd = mc.lattice(self.getMemberList(),n=self.deformerName)
		lattice = ffd[0]
		latticeShape = ffd[1]
		latticeBase = ffd[2]
		
		# Set Deformer Attributes
		mc.setAttr(lattice+'.local',self.local)
		mc.setAttr(lattice+'.outsideLattice',self.outside)
		mc.setAttr(lattice+'.outsideFalloffDist',self.falloff)
		mc.setAttr(lattice+'.usePartialResolution',self.resolution)
		mc.setAttr(lattice+'.partialResolution',self.partialResolution)
		mc.setAttr(lattice+'.freezeGeometry',self.freeze)
		mc.setAttr(lattice+'.localInfluenceS',self.localInfluenceS)
		mc.setAttr(lattice+'.localInfluenceT',self.localInfluenceT)
		mc.setAttr(lattice+'.localInfluenceU',self.localInfluenceU)
		
		# Set Lattice Shape Attributes
		mc.setAttr(latticeShape+'.sDivisions',self.sDivisions)
		mc.setAttr(latticeShape+'.tDivisions',self.tDivisions)
		mc.setAttr(latticeShape+'.uDivisions',self.uDivisions)
		
		# Restore World Transform Data
		mc.xform(lattice,ws=True,m=self.latticeXform)
		mc.xform(latticeBase,ws=True,m=self.baseXform)
		
		# Return result
		return lattice
예제 #9
0
파일: eyes.py 프로젝트: skarone/PipeL
	def _createPerEye(self, side, geos ):
		mc.select( geos )
		clu = mn.Node( mc.cluster( n = side + '_Eye_CLU' )[1] )
		print clu.name
		mc.select( geos )
		lat = mn.Nodes( mc.lattice( n = side + '_Eye_LAT', objectCentered = True ) )
		ctl = crv.Curve( side + '_Eye_ctl' )
		ctl.create( 'circleZ' )
		print ctl.name
		par = mn.Node( mc.parentConstraint( clu, ctl, mo = False )[0])
		par.delete()
		ctl.a.tz.v = self.distance_control_sb.value() + ctl.a.tz.v
		mc.makeIdentity( ctl, a = True, t = 1, r = 1, s = 1 )
		loc = mn.createNode( 'locator' ).parent
		loc.name = side + '_Eye_Top_Loc'
		par = mn.Node( mc.aimConstraint( ctl, clu, mo = True, aimVector=[1,0,0],
										upVector=[0,1,0], worldUpType='object',
										worldUpObject=loc )[0])
		trf = mn.createNode( 'transform' )
		trf.name = side + '_Eye_Def_grp'
		lat[1].parent = trf
		lat[2].parent = trf
		clu.parent = trf
		loc.parent = trf
		return trf, ctl
예제 #10
0
    def __makeEight(self):
        side = 16
        offset = self.ui.spin_offset.value()

        eight = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), degree=3, sections=side)
        cmds.select(eight[0])
        lattice = cmds.lattice(dv = (3, 2, 3), objectCentered  = True )
        cmds.setAttr(lattice[0]+'.local', 0)


        cmds.select(lattice[1]+'.pt[2][0:1][0]',lattice[1]+'.pt[2][0:1][1]',lattice[1]+'.pt[2][0:1][2]')
        cmds.scale(1, 1, -1, pivot = (1.108194, 0 , 0), relative = True)
        cmds.select(lattice[1]+'.pt[1][0:1][0]',lattice[1]+'.pt[1][0:1][1]',lattice[1]+'.pt[1][0:1][2]')
        cmds.scale(0, 0, 0, pivot = (0, 0 , 0), relative = True)
        cmds.select(lattice[1]+'.pt[0][0:1][0]',lattice[1]+'.pt[2][0:1][2]',lattice[1]+'.pt[2][0:1][0]',lattice[1]+'.pt[0][0:1][2]')

        cmds.scale(1, 1, 1.455556, pivot = (0, 0 , 0), relative = True)
        cmds.scale(0.929167, 1, 1, pivot = (0, 0 , 0), relative = True)

        cmds.select(eight[0])
        cmds.delete(ch = True)


        cmds.rotate(0,offset,0,eight[0])
        cmds.makeIdentity(eight[0],apply = True, t = True, r = True, s = True, n = 0, pn = True)
        return eight
예제 #11
0
    def rebuild(self):
        '''
		Rebuild the lattice deformer from the recorded deformerData
		'''
        # Rebuild deformer
        ffd = mc.lattice(self.getMemberList(), n=self.deformerName)
        lattice = ffd[0]
        latticeShape = ffd[1]
        latticeBase = ffd[2]

        # Set Deformer Attributes
        mc.setAttr(lattice + '.local', self.local)
        mc.setAttr(lattice + '.outsideLattice', self.outside)
        mc.setAttr(lattice + '.outsideFalloffDist', self.falloff)
        mc.setAttr(lattice + '.usePartialResolution', self.resolution)
        mc.setAttr(lattice + '.partialResolution', self.partialResolution)
        mc.setAttr(lattice + '.freezeGeometry', self.freeze)
        mc.setAttr(lattice + '.localInfluenceS', self.localInfluenceS)
        mc.setAttr(lattice + '.localInfluenceT', self.localInfluenceT)
        mc.setAttr(lattice + '.localInfluenceU', self.localInfluenceU)

        # Set Lattice Shape Attributes
        mc.setAttr(latticeShape + '.sDivisions', self.sDivisions)
        mc.setAttr(latticeShape + '.tDivisions', self.tDivisions)
        mc.setAttr(latticeShape + '.uDivisions', self.uDivisions)

        # Restore World Transform Data
        mc.xform(lattice, ws=True, m=self.latticeXform)
        mc.xform(latticeBase, ws=True, m=self.baseXform)

        # Return result
        return lattice
예제 #12
0
    def SaveWeight(self, Unuse):
        FileFullpath = mc.fileDialog2(ff=("JSON Files (*.json)"))
        if FileFullpath == None: return
        latice = mc.ls(sl=True)
        latticePT = mc.lattice(latice[0], q=True, dv=True)

        SkinUseDt = {}
        SkinUseDt['skinNode'] = mel.eval('findRelatedSkinCluster ' + latice[0])
        SkinUseDt['skinJoints'] = mc.skinCluster(latice[0], q=True, inf=True)

        for x in range(latticePT[0]):
            for y in range(latticePT[1]):
                for z in range(latticePT[2]):
                    Pts = '%s.pt[%d][%d][%d]' % (latice[0], x, y, z)
                    weightList = mc.skinPercent(SkinUseDt['skinNode'],
                                                Pts,
                                                q=True,
                                                v=True)
                    SkinUseDt.setdefault('weightList',
                                         {})['pt[%d][%d][%d]' %
                                             (x, y, z)] = weightList

        f = open(FileFullpath[0], mode='w')
        json.dump(SkinUseDt, f, indent=2)
        f.close()
        print '# Result:  weight was saved to  ->   %s ' % FileFullpath[0],
예제 #13
0
파일: jimboBalloon.py 프로젝트: radvfx/py
def tieOff():
	global balloonRadius, balloonQuantity
	knotVals = mc.pointPosition('balloonTemp.vtx[96]', w=True)
	knotThickness = balloonRadius * .05
	endHeight = balloonRadius * .15
	knotRadius = knotVals[0]
	knotPos = ( knotVals[1] - (.5 * knotThickness))

	mc.polyCylinder( n="knotTemp", r=knotRadius, h=knotThickness, sx=12, sy=3, sz=0, rcp=0, cuv=3)
	mc.delete( 'knotTemp.f[36:37]')
	mc.setAttr( 'knotTemp.translateY', knotPos )
	mc.scale(1.25, 1.75, 1.25, 'knotTemp.vtx[12:35]', r=True )
	mc.lattice( n='knot', cp=True,  dv =(2, 2, 2), objectCentered=True, ldv=(2,2,2))
	mc.move( (.75 * knotThickness), 'knotLattice.pt[1][0][0:1]', r=True, y=True)
	mc.move( (.25 * knotThickness), 'knotLattice.pt[0][0][0:1]', r=True, y=True)

	mc.duplicate('knotTemp')
	mc.rotate(180, 'knotTemp1', z=True)

	mc.polyCone( n="endTemp", r=knotRadius*2, h=endHeight, sx=12, sy=6, sz=3, rcp=0, cuv=3)
	mc.delete( 'endTemp.f[60:83]', 'endTemp.f[96:107]')
	mc.setAttr( 'endTemp.translateY', knotPos - knotThickness/2 )	
	mc.scale( 1.15, 1, 1.15, 'endTemp.vtx[36:59]') 
	mc.move((.5 * endHeight), 'endTemp.vtx[0:11]', 'endTemp.vtx[72]', y=True, r=True)
	mc.polyUnite( 'balloonTemp', 'knotTemp', 'knotTemp1', 'endTemp', ch=True )
	mc.polySoftEdge( a = 180 )
	mc.polyMergeVertex( d=.001)

	mc.polyEditUV('polySurface1.map[0:126]', pu=0.5, pv=1, su=1, sv=0.575)
	mc.polyEditUV('polySurface1.map[127:230]', pu=0.5, pv=0.35, su=2, sv=.25)
	mc.polyEditUV('polySurface1.map[267:318]', u=0, v=-0.1, pu=0.5, pv=0, su=1, sv=.5)
	mc.polyEditUV('polySurface1.map[231:266]', 'polySurface1.map[319]', u=0, v=-.175, pu=0.5, pv=0.25, su=0.25, sv=0.25)
	mc.polyMergeUV('polySurface1.map[103:126]', d=0.5, ch=True )
	mc.polyEditUV('polySurface1.map[104]',  r=False, u=0)
	mc.polyEditUV('polySurface1.map[103]', r=False, u=1)
	mc.polySmooth('polySurface1',  mth=0, dv=1, c=1, kb=0, ksb=1, khe=0, kt=1, kmb=0, suv=0, peh=0, sl=1, dpe=1, ps=0.1 , ro=1, ch=True)

	mc.DeleteHistory()
	mc.delete( 'knotTemp1')
	mc.rename('polySurface1', 'balloon1')
	mc.select(cl=True)
	return
예제 #14
0
파일: lattice.py 프로젝트: xtoof/Tapp
def latticeAdd():

    #undo enable
    cmds.undoInfo(openChunk=True)

    #getting nodes
    sel = cmds.ls(selection=True)
    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

    #adding to lattice
    for obj in objs:
        try:
            cmds.lattice(lat, e=True, geometry=obj)
        except:
            pass

    cmds.undoInfo(closeChunk=True)
예제 #15
0
    def eyelattic(self):

        model = cmds.ls(sl=1)
        lat = cmds.lattice(dv=(10,10,10),oc=True)
        for i in lat:
            if '_L' in model[0]:
                cmds.select(i)
                a = cmds.rename(i,i+'_L')
                if 'Lattice' in a:
                    cmds.parent(a,'L_eyeBall_jnt')
                if 'Base' in a:
                    cmds.parent(a,'Eye_grp')
            if '_R' in model[0]:
                cmds.select(i)
                a = cmds.rename(i,i+'_R')
                if 'Lattice' in a:
                    cmds.parent(a,'R_eyeBall_jnt')
                if 'Base' in a:
                    cmds.parent(a,'Eye_grp')
    def SaveWeight(self, Unuse):
        FileFullpath = mc.fileDialog2(ff=("JSON Files (*.json)")) 
        if FileFullpath == None:return
        latice = mc.ls(sl=True)
        latticePT = mc.lattice(latice[0], q=True, dv=True)
        
        SkinUseDt = {}
        SkinUseDt['skinNode'] = mel.eval('findRelatedSkinCluster ' + latice[0])
        SkinUseDt['skinJoints'] = mc.skinCluster(latice[0], q=True, inf=True)


        for x in range(latticePT[0]):
            for y in range(latticePT[1]):
                for z in range(latticePT[2]):
                    Pts = '%s.pt[%d][%d][%d]' %(latice[0], x, y, z)
                    weightList = mc.skinPercent(SkinUseDt['skinNode'], Pts, q=True, v=True)
                    SkinUseDt.setdefault('weightList', {})['pt[%d][%d][%d]' %(x, y, z)] = weightList
        
        
        f = open(FileFullpath[0], mode='w')
        json.dump(SkinUseDt, f, indent=2)
        f.close()    
        print '# Result:  weight was saved to  ->   %s ' %FileFullpath[0],
예제 #17
0
파일: tools_list.py 프로젝트: jonntd/Public
def setup_blendshape_lattice(side=None,
                             blendShape=None,
                             divisions=[2, 5, 2],
                             ldv=[2, 2, 2],
                             parent=None):
    #--- this method setups the lattice deformer
    lat = cmds.lattice(blendShape,
                       divisions=divisions,
                       objectCentered=True,
                       ldv=ldv)
    cmds.setAttr(lat[1] + '.v', 0)
    cmds.parent(lat, 'Shapes')

    points = cmds.ls(lat[1] + '.pt[*]', flatten=True)
    for point in range(len(points)):
        pos = cmds.xform(points[point],
                         query=True,
                         translation=True,
                         worldSpace=True)
        cPoint = node.nControl(position=pos,
                               color=17,
                               size=1,
                               shape=1,
                               side=side,
                               description="latPoint" + str(point),
                               parent=parent,
                               rotateOrder=2)
        cmds.setAttr(cPoint.control['transform'] + '.v', lock=False)
        cmds.connectAttr('C_bedMid_CTL.latticeControls',
                         cPoint.control['transform'] + '.v')
        cls = cmds.cluster(points[point],
                           name=side + '_latCluster' + str(point) + '_CLS')
        for axis in 'xyz':
            cmds.connectAttr(cPoint.control['transform'] + '.t' + axis,
                             cls[1] + '.t' + axis)
        cmds.parent(cls[1], 'Shapes')
        cmds.setAttr(cls[1] + '.v', 0)
#GAME ENGINE AUTO RIG
예제 #19
0
def buildEyeballGeo():
    #     try:
    # create eyeball controler-----------------------------------------------------------------------------------------
    gEyeballCtrler = cmds.spaceLocator()[0]
    cmds.addAttr(longName='pupilSize', attributeType='float', keyable=True, defaultValue=gDefaultPupilValue)
    cmds.addAttr(longName='irisSize', attributeType='float', keyable=True, defaultValue=gDefaultIrisValue)
    cmds.addAttr(longName='irisConcave', attributeType='float', keyable=True, defaultValue=gDefaultIrisConcaveValue)
    cmds.addAttr(longName='corneaBulge', attributeType='float', keyable=True, defaultValue=gDefaultCorneaBulgeValue)

    # cornea-----------------------------------------------------------------------------------------
    # create eyeball base geometry and detach
    eyeballSphere = cmds.sphere(sections=20, spans=20, axis=(0, 0, 1), radius=0.5)[0]
    #     eyeballSphere=eyeballSphere[0]
    pieceNames = cmds.detachSurface(eyeballSphere, ch=1, rpo=1, parameter=(0.1, 20))
    corneaGeo = pieceNames[0];
    corneaDetach = pieceNames[2];
    cmds.parent(eyeballSphere, gEyeballCtrler, relative=True)
    cmds.parent(corneaGeo, gEyeballCtrler, relative=True)

    # rebuild corneaGeo
    cmds.rebuildSurface(corneaGeo, ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kc=0, su=36, du=3, sv=1, dv=3, tol=0.01, fr=0,
                        dir=0)

    # add lattice and deform cornea
    cmds.select(corneaGeo)
    (corneaLat, corneaLatGeo, corneaLatGeoBase) = cmds.lattice(dv=(2, 2, 6), oc=False)
    cmds.setAttr(corneaLatGeo + '.scale', 1.1, 1.1, 1.1)
    cmds.setAttr(corneaLatGeoBase + '.scale', 1.1, 1.1, 1.1)
    cmds.setAttr(corneaGeo + '.overrideEnabled', 1)
    cmds.setAttr(corneaGeo + '.overrideColor', 3)

    corneaDetachRider = cmds.createNode('transform')
    corneaDeformGrp = cmds.createNode('transform')
    corneaRadius = cmds.createNode('transform')

    cmds.parent(corneaDeformGrp, corneaDetachRider, relative=True)
    cmds.parent(corneaRadius, corneaDetachRider, relative=True)
    cmds.parent(corneaLatGeo, corneaDeformGrp, relative=True)
    cmds.parent(corneaLatGeoBase, corneaDeformGrp, relative=True)
    cmds.parent(corneaDetachRider, gEyeballCtrler, relative=True)

    cmds.hide(corneaDetachRider)

    # set opaque for Arnold render
    if gRenderer == 'mtoa':
        corneaGeoShape = cmds.listRelatives(corneaGeo, shapes=True)[0]
        cmds.setAttr(corneaGeoShape + '.aiOpaque', 0)


        # iris-----------------------------------------------------------------------------------------
    # create eyeball base geometry and detach
    eyeballSphere2 = cmds.sphere(sections=20, spans=20, axis=(0, 0, 1), radius=0.5)[0]
    pieceNames = cmds.detachSurface(eyeballSphere2, ch=1, rpo=1, parameter=(0.1, 20))
    irisGeo = pieceNames[0]
    irisDetach = pieceNames[2]
    cmds.delete(eyeballSphere2)
    cmds.parent(irisGeo, gEyeballCtrler, relative=True)

    # add lattice and deform iris
    cmds.select(irisGeo)
    (irisLat, irisLatGeo, irisLatGeoBase) = cmds.lattice(dv=(2, 2, 2), oc=False)
    cmds.setAttr(irisLatGeo + '.scale', 1.1, 1.1, -2)
    cmds.setAttr(irisLatGeoBase + '.scale', 1.1, 1.1, 2)
    cmds.setAttr(irisLatGeo + '.translateZ', -0.5)
    cmds.setAttr(irisLatGeoBase + '.translateZ', -0.5)
    cmds.setAttr(irisGeo + '.overrideEnabled', 1)
    cmds.setAttr(irisGeo + '.overrideColor', 13)

    irisDetachRider = cmds.createNode('transform')
    irisDeformGrp = cmds.createNode('transform')
    irisRadius = cmds.createNode('transform')

    cmds.parent(irisDeformGrp, irisDetachRider, relative=True)
    cmds.parent(irisRadius, irisDetachRider, relative=True)
    cmds.parent(irisLatGeo, irisDeformGrp, relative=True)
    cmds.parent(irisLatGeoBase, irisDeformGrp, relative=True)
    cmds.parent(irisDetachRider, gEyeballCtrler, relative=True)

    cmds.hide(irisDetachRider)

    # pupil-----------------------------------------------------------------------------------------
    # detach from iris geometry
    pieceNames = cmds.detachSurface(irisGeo, ch=1, rpo=1, parameter=(0.1, 20))
    pupilGeo = pieceNames[0]
    pupilDetach = pieceNames[2]
    cmds.parent(pupilGeo, gEyeballCtrler, relative=True)
    cmds.setAttr(pupilGeo + '.overrideEnabled', 1)
    cmds.setAttr(pupilGeo + '.overrideColor', 17)

    # connect attributes-----------------------------------------------------------------------------------------
    expressionStr = '''
                        //calculate cornea-related parameters
                        //cornea translate Z
                        float $cornea_tz = (cos(deg_to_rad(''' + gEyeballCtrler + '''.irisSize*9.0))) * 0.5;
                        //cornea radius
                        float $cornea_rad  = (sin(deg_to_rad(''' + gEyeballCtrler + '''.irisSize*9.0))) * 0.5;
                        //define nurbs surface cornea detach position
                        float $cornea_par  = ((1.0 - linstep( 0.0,10.0,''' + gEyeballCtrler + '''.irisSize)) * 10.0 ) + 10.0;
                        ''' + corneaDetach + '''.parameter[0] = $cornea_par;
                        ''' + corneaDetachRider + '''.translateZ = $cornea_tz;
                        ''' + corneaRadius + '''.translateX = $cornea_rad;
                        ''' + corneaDeformGrp + '''.translateZ = ( 0.5 - $cornea_tz ) * 0.5;
                        ''' + corneaDeformGrp + '''.scaleX = ''' + corneaDeformGrp + '''.scaleY = $cornea_rad * 2.0;
                        ''' + corneaDeformGrp + '''.scaleZ = ( 0.5 - $cornea_tz );
                        ''' + corneaLat + '''.envelope = (1.0 - (smoothstep(0.0,11.0,''' + gEyeballCtrler + '''.irisSize))) * (''' + gEyeballCtrler + '''.corneaBulge * 0.1);
                        
                        //calculate iris-related parameters
                        float $iris_tz   = ( cos(deg_to_rad((''' + gEyeballCtrler + '''.irisSize+0.3)*9.0)) ) * 0.485;
                        float $iris_rad  = ( sin(deg_to_rad((''' + gEyeballCtrler + '''.irisSize+0.3)*9.0)) ) * 0.485;
                        float $iris_par  = ((1.0 - ((''' + gEyeballCtrler + '''.irisSize+0.3)*0.1)) * 10.0 ) + 10.0;
                        ''' + irisDetach + '''.parameter[0] = $iris_par;
                        ''' + irisDetachRider + '''.translateZ = $iris_tz;
                        ''' + irisRadius + '''.translateX = $iris_rad;
                        ''' + irisDeformGrp + '''.translateZ = ( 0.5 - $iris_tz ) * 0.5;
                        ''' + irisDeformGrp + '''.scaleX = ''' + irisDeformGrp + '''.scaleY = $iris_rad * 2.0;
                        ''' + irisDeformGrp + '''.scaleZ = ( 0.5 - $iris_tz );
                        ''' + irisLat + '''.envelope = ''' + gEyeballCtrler + '''.irisConcave * 0.1;
                        
                        float $pupil_par = max( (((1.0 - ((''' + gEyeballCtrler + '''.pupilSize)*0.1)) * 10.0 ) + 10.0), $iris_par + 0.1 );
                        ''' + pupilDetach + '''.parameter[0] = $pupil_par;
                        '''

    cmds.expression(s=expressionStr)

    # deform latticeGeo
    for x in range(0, 2):
        for y in range(0, 2):
            for z in range(3, 6):
                pointNameStr = corneaLatGeo + '.pt[' + str(x) + '][' + str(y) + '][' + str(z) + ']'
                ptTranslateZ = cmds.getAttr(pointNameStr + '.zValue')
                cmds.setAttr(pointNameStr + '.zValue', ptTranslateZ * 2 + 0.319)
            #                     cmds.select(pointNameStr)
            #                     cmds.move(0, 0, 0.05, r=True)

            # rename objects------------------------------------
    gEyeballCtrlerName = 'eyeballCtrler'

    cmds.rename(gEyeballCtrler, gEyeballCtrlerName)
    cmds.rename(pupilGeo, 'pupilGeo')
    cmds.rename(pupilDetach, 'pupilDetach')

    cmds.rename(irisLat, 'irisLat')
    cmds.rename(irisLatGeo, 'irisLatGeo')
    cmds.rename(irisLatGeoBase, 'irisLatGeoBase')
    cmds.rename(irisGeo, 'irisGeo')
    cmds.rename(irisDetach, 'irisDetach')
    cmds.rename(irisDetachRider, 'irisDetachRider')
    cmds.rename(irisDeformGrp, 'irisDeformGrp')
    cmds.rename(irisRadius, 'irisRadius')
    cmds.rename(corneaLat, 'corneaLat')
    cmds.rename(corneaLatGeo, 'corneaLatGeo')
    cmds.rename(corneaLatGeoBase, 'corneaLatGeoBase')
    cmds.rename(eyeballSphere, 'eyeballSphere')
    cmds.rename(corneaGeo, 'corneaGeo')
    cmds.rename(corneaDetach, 'corneaDetach')
    cmds.rename(corneaDetachRider, 'corneaDetachRider')
    cmds.rename(corneaDeformGrp, 'corneaDeformGrp')
    cmds.rename(corneaRadius, 'corneaRadius')
예제 #20
0
    def testAnimNurbsPlaneWrite(self, wfg=False):

        ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3,
            u=5, v=5, ch=0)
        name = ret[0]

        MayaCmds.lattice(name, dv=(4, 5, 4), oc=True)
        MayaCmds.select('ffd1Lattice.pt[1:2][0:4][1:2]', r=True)

        MayaCmds.currentTime(1, update=True)
        MayaCmds.setKeyframe()
        MayaCmds.currentTime(24, update=True)
        MayaCmds.setKeyframe()
        MayaCmds.currentTime(12, update=True)
        MayaCmds.move(0, 0.18, 0, r=True)
        MayaCmds.scale(2.5, 1.0, 2.5, r=True)
        MayaCmds.setKeyframe()

        MayaCmds.curveOnSurface(name,
            uv=((0.597523, 0), (0.600359, 0.271782), (0.538598, 0.564218),
                (0.496932, 0.779936), (0.672153, 1)),
            k=(0, 0, 0, 0.263463, 0.530094, 0.530094, 0.530094))

        curvename = MayaCmds.curveOnSurface(name,
            uv=((0.170718, 0.565967), (0.0685088, 0.393034), (0.141997, 0.206296),
                (0.95, 0.230359), (0.36264, 0.441381), (0.251243, 0.569889)),
            k=(0, 0, 0, 0.200545, 0.404853, 0.598957, 0.598957, 0.598957))
        MayaCmds.closeCurve(curvename, ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1,
            cos=1)

        MayaCmds.trim(name, lu=0.23, lv=0.39)

        degreeU = MayaCmds.getAttr(name + '.degreeU')
        degreeV = MayaCmds.getAttr(name + '.degreeV')
        spansU = MayaCmds.getAttr(name + '.spansU')
        spansV = MayaCmds.getAttr(name + '.spansV')
        formU = MayaCmds.getAttr(name + '.formU')
        formV = MayaCmds.getAttr(name + '.formV')
        minU = MayaCmds.getAttr(name + '.minValueU')
        maxU = MayaCmds.getAttr(name + '.maxValueU')
        minV = MayaCmds.getAttr(name + '.minValueV')
        maxV = MayaCmds.getAttr(name + '.maxValueV')

        MayaCmds.createNode('surfaceInfo')
        MayaCmds.connectAttr(name + '.worldSpace', 'surfaceInfo1.inputSurface',
            force=True)

        MayaCmds.currentTime(1, update=True)
        controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]')
        knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]')
        knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]')

        MayaCmds.currentTime(12, update=True)
        controlPoints2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]')
        knotsU2 = MayaCmds.getAttr('surfaceInfo1.knotsU[*]')
        knotsV2 = MayaCmds.getAttr('surfaceInfo1.knotsV[*]')

        if wfg:
            self.__files.append(util.expandFileName('testAnimNurbsPlane.abc'))

            MayaCmds.AbcExport(j='-fr 1 24 -frs -0.25 -frs 0.0 -frs 0.25 -wfg -root %s -file %s' % (name, self.__files[-1]))

            # reading test
            MayaCmds.AbcImport(self.__files[-1], mode='open')
        else:
            self.__files.append(util.expandFileName('testAnimNurbsPlane.abc'))
            self.__files.append(util.expandFileName('testAnimNurbsPlane01_14.abc'))
            self.__files.append(util.expandFileName('testAnimNurbsPlane15_24.abc'))

            MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2]))
            MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1]))

            # use AbcStitcher to combine two files into one
            subprocess.call(self.__abcStitcher + self.__files[-3:])

            # reading test
            MayaCmds.AbcImport(self.__files[-3], mode='open')

        self.failUnlessEqual(degreeU, MayaCmds.getAttr(name + '.degreeU'))
        self.failUnlessEqual(degreeV, MayaCmds.getAttr(name + '.degreeV'))
        self.failUnlessEqual(spansU, MayaCmds.getAttr(name + '.spansU'))
        self.failUnlessEqual(spansV, MayaCmds.getAttr(name + '.spansV'))
        self.failUnlessEqual(formU, MayaCmds.getAttr(name + '.formU'))
        self.failUnlessEqual(formV, MayaCmds.getAttr(name + '.formV'))
        self.failUnlessEqual(minU, MayaCmds.getAttr(name + '.minValueU'))
        self.failUnlessEqual(maxU, MayaCmds.getAttr(name + '.maxValueU'))
        self.failUnlessEqual(minV, MayaCmds.getAttr(name + '.minValueV'))
        self.failUnlessEqual(maxV, MayaCmds.getAttr(name + '.maxValueV'))

        MayaCmds.createNode('surfaceInfo')
        MayaCmds.connectAttr(name + '.worldSpace', 'surfaceInfo1.inputSurface',
            force=True)

        MayaCmds.currentTime(1, update=True)
        errmsg = "At frame #1, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints)):
            cp1 = controlPoints[i]
            cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x'))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y'))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z'))

        errmsg = "At frame #1, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU)):
            ku1 = knotsU[i]
            ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #1, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV)):
            kv1 = knotsV[i]
            kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))

        MayaCmds.currentTime(12, update=True)
        errmsg = "At frame #12, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints2)):
            cp1 = controlPoints2[i]
            cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x'))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y'))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z'))

        errmsg = "At frame #12, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU2)):
            ku1 = knotsU2[i]
            ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #12, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV2)):
            kv1 = knotsV2[i]
            kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))

        MayaCmds.currentTime(24, update=True)
        errmsg = "At frame #24, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints)):
            cp1 = controlPoints[i]
            cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x'))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y'))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z'))

        errmsg = "At frame #24, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU)):
            ku1 = knotsU[i]
            ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #24, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV)):
            kv1 = knotsV[i]
            kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))
예제 #21
0
def rigEyes():
    # eyeBall - eyeLids intersections
    surf1 = 'LT_eyeBallIntersect_srf_0'
    surf2 = 'CT_eyeBallHeadIntersecter_srf_0'
    jntsNum = 20
    addJntsOnSurfIntersection(surf1, surf2, jntsNum)
    
    # eyeBall pop controls
    baseTangentMP = ms.addTangentMPTo('LT_eyeBase_mPt', 'LT_eyeTip_mPt', 'z', default=0.2, reverse=False)
    tipTangentMP = ms.addTangentMPTo('LT_eyeTip_mPt', 'LT_eyeBase_mPt', 'z', default=0.2, reverse=True)
    midMP = ms.addMidMP(baseTangentMP, tipTangentMP, 'LT_eyeBase_mPt', 'LT_eyeTip_mPt', (0,0,1), (0,1,0), 'LT_mid_mPt')
    crv = ms.createSplineMPs(('LT_eyeBase_mPt', baseTangentMP, midMP, tipTangentMP, 'LT_eyeTip_mPt'), 8, 'LT_eyeSpine', (0,3,0))
    
    baseTangentMP = ms.addTangentMPTo('RT_eyeBase_mPt', 'RT_eyeTip_mPt', 'z', default=0.2, reverse=False)
    tipTangentMP = ms.addTangentMPTo('RT_eyeTip_mPt', 'RT_eyeBase_mPt', 'z', default=0.2, reverse=True)
    midMP = ms.addMidMP(baseTangentMP, tipTangentMP, 'RT_eyeBase_mPt', 'RT_eyeTip_mPt', (0,0,1), (0,1,0), 'RT_mid_mPt')
    crv = ms.createSplineMPs(('RT_eyeBase_mPt', baseTangentMP, midMP, tipTangentMP, 'RT_eyeTip_mPt'), 8, 'RT_eyeSpine', (0,3,0))
    
    #===========================================================================
    # add IK offset ctrls to eyeball
    #===========================================================================
    lfMps = mc.ls(sl=True)
    ctls = []
    
    # create left controls
    for ctlId in range(0,len(lfMps)):
        ctl = cs.ctlCurve(lfMps[ctlId].replace('_MPJnt_', '_ctl_'), 'circle', 0, size=6, snap=lfMps[ctlId])
        ctl.setSpaces([lfMps[ctlId]], ['Eye'])
        ctls.append(ctl)
        
    rtMps = mc.ls(sl=True)
    ctls = []
    
    # create right controls
    for ctlId in range(0,len(rtMps)):
        ctl = cs.ctlCurve(rtMps[ctlId].replace('_MPJnt_', '_ctl_'), 'circle', 0, size=6, snap=rtMps[ctlId])
        ctl.setSpaces([rtMps[ctlId]], ['Eye'])
        ctls.append(ctl)
        
    #===========================================================================
    # Add stretchy volume for eyeBall spine
    #===========================================================================
    
    stretchAmts = {'LT_eyeSpine_ctl_0_space':10,
                'LT_eyeSpine_ctl_1_space':9,
                'LT_eyeSpine_ctl_2_space':8,
                'LT_eyeSpine_ctl_3_space':5,
                'LT_eyeSpine_ctl_4_space':3,
                'LT_eyeSpine_ctl_5_space':1.25,
                'LT_eyeSpine_ctl_6_space':0,
                'LT_eyeSpine_ctl_7_space':-1}
    
    ms.addVolume('LT_eyeSpine_uniform_crv_crv', stretchAmts)
    
    stretchAmts = {'RT_eyeSpine_ctl_0_space':10,
                'RT_eyeSpine_ctl_1_space':9,
                'RT_eyeSpine_ctl_2_space':8,
                'RT_eyeSpine_ctl_3_space':5,
                'RT_eyeSpine_ctl_4_space':3,
                'RT_eyeSpine_ctl_5_space':1.25,
                'RT_eyeSpine_ctl_6_space':0,
                'RT_eyeSpine_ctl_7_space':-1}
    
    ms.addVolume('RT_eyeSpine_uniform_crv_crv', stretchAmts)
    #===========================================================================
    # Add control lattice to eyeBall nurbs
    #===========================================================================
    
    # Create lattice - hard coded to 8 ctls in Z
    eyeSphere = 'LT_eyeBallIntersect_srf_0'
    prefix = 'LT_eyeBallIntersect_'
    ffd, lat, latBase = mc.lattice(eyeSphere, n=prefix+'ffd', oc=True, dv=(4,4,8))
    grp = abRT.groupFreeze(lat)
    rt.transferAttrValues(lat+'.s', grp+'.s', False)
    mc.setAttr(lat+'.s',1,1,1)
    mc.parent(latBase, grp)
    
    # Create lattice - hard coded to 8 ctls in Z
    eyeSphere = 'RT_eyeBallIntersect_srf_0'
    prefix = 'RT_eyeBallIntersect_'
    ffd, lat, latBase = mc.lattice(eyeSphere, n=prefix+'ffd', oc=True, dv=(4,4,8))
    grp = abRT.groupFreeze(lat)
    rt.transferAttrValues(lat+'.s', grp+'.s', False)
    mc.setAttr(lat+'.s',1,1,1)
    mc.parent(latBase, grp)
    
    # DO THIS FOR LEFT AND RIGHT SIDES
    
    # Create joints under each ctl
    ctls = mc.ls(os=True)
    jnts = []
    for eachCtl in ctls:
        mc.select(cl=True)
        jnt = mc.joint(n=eachCtl.replace('_ctl', '_jnt'))
        rt.parentSnap(jnt, eachCtl)
        jnts.append(jnt)
        mc.setAttr(jnt+'.radius', 3)
        mc.setAttr(jnt+'.jointOrient', 0,0,0)
        
    # Weight joints to lattice
    skn = mc.skinCluster(jnts, lat, name=lat+'_skn')[0]
    for jnt in jnts:
        i = jnts.index(jnt)
        mc.skinPercent(skn, lat+'.pt[*][*][%d]'%i, tv=((jnt, 1)))
예제 #22
0
    def testAnimNurbsPlaneWrite(self, wfg=False):

        ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0)
        name = ret[0]

        MayaCmds.lattice(name, dv=(4, 5, 4), oc=True)
        MayaCmds.select("ffd1Lattice.pt[1:2][0:4][1:2]", r=True)

        MayaCmds.currentTime(1, update=True)
        MayaCmds.setKeyframe()
        MayaCmds.currentTime(24, update=True)
        MayaCmds.setKeyframe()
        MayaCmds.currentTime(12, update=True)
        MayaCmds.move(0, 0.18, 0, r=True)
        MayaCmds.scale(2.5, 1.0, 2.5, r=True)
        MayaCmds.setKeyframe()

        MayaCmds.curveOnSurface(
            name,
            uv=((0.597523, 0), (0.600359, 0.271782), (0.538598, 0.564218), (0.496932, 0.779936), (0.672153, 1)),
            k=(0, 0, 0, 0.263463, 0.530094, 0.530094, 0.530094),
        )

        curvename = MayaCmds.curveOnSurface(
            name,
            uv=(
                (0.170718, 0.565967),
                (0.0685088, 0.393034),
                (0.141997, 0.206296),
                (0.95, 0.230359),
                (0.36264, 0.441381),
                (0.251243, 0.569889),
            ),
            k=(0, 0, 0, 0.200545, 0.404853, 0.598957, 0.598957, 0.598957),
        )
        MayaCmds.closeCurve(curvename, ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1, cos=1)

        MayaCmds.trim(name, lu=0.23, lv=0.39)

        degreeU = MayaCmds.getAttr(name + ".degreeU")
        degreeV = MayaCmds.getAttr(name + ".degreeV")
        spansU = MayaCmds.getAttr(name + ".spansU")
        spansV = MayaCmds.getAttr(name + ".spansV")
        formU = MayaCmds.getAttr(name + ".formU")
        formV = MayaCmds.getAttr(name + ".formV")
        minU = MayaCmds.getAttr(name + ".minValueU")
        maxU = MayaCmds.getAttr(name + ".maxValueU")
        minV = MayaCmds.getAttr(name + ".minValueV")
        maxV = MayaCmds.getAttr(name + ".maxValueV")

        MayaCmds.createNode("surfaceInfo")
        MayaCmds.connectAttr(name + ".worldSpace", "surfaceInfo1.inputSurface", force=True)

        MayaCmds.currentTime(1, update=True)
        controlPoints = MayaCmds.getAttr("surfaceInfo1.controlPoints[*]")
        knotsU = MayaCmds.getAttr("surfaceInfo1.knotsU[*]")
        knotsV = MayaCmds.getAttr("surfaceInfo1.knotsV[*]")

        MayaCmds.currentTime(12, update=True)
        controlPoints2 = MayaCmds.getAttr("surfaceInfo1.controlPoints[*]")
        knotsU2 = MayaCmds.getAttr("surfaceInfo1.knotsU[*]")
        knotsV2 = MayaCmds.getAttr("surfaceInfo1.knotsV[*]")

        if wfg:
            self.__files.append(util.expandFileName("testAnimNurbsPlane.abc"))

            MayaCmds.AbcExport(
                j="-fr 1 24 -frs -0.25 -frs 0.0 -frs 0.25 -wfg -root %s -file %s" % (name, self.__files[-1])
            )

            # reading test
            MayaCmds.AbcImport(self.__files[-1], mode="open")
        else:
            self.__files.append(util.expandFileName("testAnimNurbsPlane.abc"))
            self.__files.append(util.expandFileName("testAnimNurbsPlane01_14.abc"))
            self.__files.append(util.expandFileName("testAnimNurbsPlane15_24.abc"))

            MayaCmds.AbcExport(j="-fr 1 14 -root %s -file %s" % (name, self.__files[-2]))
            MayaCmds.AbcExport(j="-fr 15 24 -root %s -file %s" % (name, self.__files[-1]))

            # use AbcStitcher to combine two files into one
            subprocess.call(self.__abcStitcher + self.__files[-3:])

            # reading test
            MayaCmds.AbcImport(self.__files[-3], mode="open")

        self.failUnlessEqual(degreeU, MayaCmds.getAttr(name + ".degreeU"))
        self.failUnlessEqual(degreeV, MayaCmds.getAttr(name + ".degreeV"))
        self.failUnlessEqual(spansU, MayaCmds.getAttr(name + ".spansU"))
        self.failUnlessEqual(spansV, MayaCmds.getAttr(name + ".spansV"))
        self.failUnlessEqual(formU, MayaCmds.getAttr(name + ".formU"))
        self.failUnlessEqual(formV, MayaCmds.getAttr(name + ".formV"))
        self.failUnlessEqual(minU, MayaCmds.getAttr(name + ".minValueU"))
        self.failUnlessEqual(maxU, MayaCmds.getAttr(name + ".maxValueU"))
        self.failUnlessEqual(minV, MayaCmds.getAttr(name + ".minValueV"))
        self.failUnlessEqual(maxV, MayaCmds.getAttr(name + ".maxValueV"))

        MayaCmds.createNode("surfaceInfo")
        MayaCmds.connectAttr(name + ".worldSpace", "surfaceInfo1.inputSurface", force=True)

        MayaCmds.currentTime(1, update=True)
        errmsg = "At frame #1, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints)):
            cp1 = controlPoints[i]
            cp2 = MayaCmds.getAttr("surfaceInfo1.controlPoints[%d]" % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, "x"))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, "y"))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, "z"))

        errmsg = "At frame #1, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU)):
            ku1 = knotsU[i]
            ku2 = MayaCmds.getAttr("surfaceInfo1.knotsU[%d]" % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #1, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV)):
            kv1 = knotsV[i]
            kv2 = MayaCmds.getAttr("surfaceInfo1.knotsV[%d]" % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))

        MayaCmds.currentTime(12, update=True)
        errmsg = "At frame #12, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints2)):
            cp1 = controlPoints2[i]
            cp2 = MayaCmds.getAttr("surfaceInfo1.controlPoints[%d]" % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, "x"))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, "y"))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, "z"))

        errmsg = "At frame #12, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU2)):
            ku1 = knotsU2[i]
            ku2 = MayaCmds.getAttr("surfaceInfo1.knotsU[%d]" % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #12, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV2)):
            kv1 = knotsV2[i]
            kv2 = MayaCmds.getAttr("surfaceInfo1.knotsV[%d]" % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))

        MayaCmds.currentTime(24, update=True)
        errmsg = "At frame #24, Nurbs Plane's control point #%d.%s not equal"
        for i in range(0, len(controlPoints)):
            cp1 = controlPoints[i]
            cp2 = MayaCmds.getAttr("surfaceInfo1.controlPoints[%d]" % (i))
            self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, "x"))
            self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, "y"))
            self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, "z"))

        errmsg = "At frame #24, Nurbs Plane's control knotsU #%d not equal"
        for i in range(0, len(knotsU)):
            ku1 = knotsU[i]
            ku2 = MayaCmds.getAttr("surfaceInfo1.knotsU[%d]" % (i))
            self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i))

        errmsg = "At frame #24, Nurbs Plane's control knotsV #%d not equal"
        for i in range(0, len(knotsV)):
            kv1 = knotsV[i]
            kv2 = MayaCmds.getAttr("surfaceInfo1.knotsV[%d]" % (i))
            self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))
예제 #23
0
파일: animation.py 프로젝트: zewt/pymel
def lattice(*args, **kwargs):
    res = cmds.lattice(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    return res
예제 #24
0
def build(**kwargs):
    
    
    selection = cmds.ls(sl = True)
    selection.sort()
    name =  kwargs.get('name','TempName')
    vector = kwargs.get('vector',[1,0,0])
    width = kwargs.get('width',1)
    normalVector = kwargs.get('normalVector',[0,1,0])
    tangentVector = kwargs.get('tangentVector',(-1,0,0))
    close = kwargs.get('close',True)

    locators = []
    
    for obj in selection:

        try:
            cluster = cmds.cluster(obj)
            pos = cmds.xform(cluster[1],q = True, ws = True, rp = True)
            locator = cmds.spaceLocator()
            cmds.move(pos[0],pos[1],pos[2],locator[0])
            locators.append(locator[0])
            cmds.delete(cluster)
            
        except RuntimeError:
            cmds.error('selection must be polyTransforms or verts')
        

    numLocators = len(locators)
    
    if numLocators == 0:
        cmds.error('locators were not created')
    
    #create ribbon
    ribbon = MayaScripts.buildRibbonSurface(locators = locators,name = name,close = close,vector = vector,width = width)
    cmds.addAttr(ribbon[0],ln = 'minVisParam',at = 'double',min = -0.001 , max = 1,dv = -0.001)
    cmds.setAttr('%s.minVisParam'%ribbon[0],e = True,keyable = True)
    cmds.addAttr(ribbon[0],ln = 'maxVisParam',at = 'double',min = 0 , max = 1,dv = 1)
    cmds.setAttr('%s.maxVisParam'%ribbon[0],e = True,keyable = True)
    
    #args for rivets
    iterations = numLocators
    
    rivets = MayaScripts.makeRivets(iterations = iterations,surfaceName = ribbon[1],nodeNames = name,
                closedSurface = close,normalVector = normalVector,tangentVector = tangentVector)
                
    #tread anim attr
    cmds.addAttr(ribbon[0],ln = 'tread',at = 'double')
    cmds.setAttr('%s.tread'%ribbon[0],e = True,keyable = True)
    
    rivetLocators = []
    
    inc = 0
    
    for rivet in rivets:
        vValue = cmds.getAttr('%s.vValue'%rivet)
        mdNode = cmds.createNode('multiplyDivide',n = '%s_MD'%rivet)
        cmds.setAttr('%s.input1X'%mdNode,0.005)
        pmaNode = cmds.createNode('plusMinusAverage',n = '%s_PMA'%rivet)
        cmds.connectAttr('%s.tread'%ribbon[0],'%s.input2X'%mdNode)
        cmds.connectAttr('%s.outputX'%mdNode,'%s.input1D[0]'%pmaNode)
        cmds.setAttr('%s.input1D[1]'%pmaNode,vValue)
        cmds.connectAttr('%s.output1D'%pmaNode,'%s.vValue'%rivet)
        
        locator = (cmds.connectionInfo('%s.outTranslation'%rivet, dfs = True))[0].split('.')[0]
        locatorName = locator.split('_Loc')[0]
        
        cmds.addAttr(locator,ln = 'outVis',at ='bool')
        cmds.setAttr('%s.outVis'%locator,e = True , keyable = True)
        
        dmNode = cmds.createNode('decomposeMatrix',name = '%s_DM'%locatorName)
        cpsNode = cmds.createNode('closestPointOnSurface',name = '%s_CPS'%locatorName)
        
        visMinCDNode = cmds.createNode('condition',name = '%s_Vis_Min_CD'%locatorName)
        visMaxCDNode = cmds.createNode('condition',name = '%s_Vis_Max_CD'%locatorName)
        visMainCDNode = cmds.createNode('condition',name = '%s_Vis_Main_CD'%locatorName)
        
        cmds.connectAttr('%s.worldMatrix[0]'%locator,'%s.inputMatrix'%dmNode)
        cmds.connectAttr('%s.worldSpace[0]'%ribbon[1],'%s.inputSurface'%cpsNode)
        cmds.connectAttr('%s.outputTranslate'%dmNode,'%s.inPosition'%cpsNode)
        
        cmds.connectAttr('%s.minVisParam'%ribbon[0],'%s.firstTerm'%visMinCDNode)
        cmds.connectAttr('%s.maxVisParam'%ribbon[0],'%s.firstTerm'%visMaxCDNode)
        cmds.connectAttr('%s.parameterV'%cpsNode,'%s.secondTerm'%visMinCDNode)
        cmds.connectAttr('%s.parameterV'%cpsNode,'%s.secondTerm'%visMaxCDNode)
        cmds.connectAttr('%s.outColorR'%visMinCDNode,'%s.firstTerm'%visMainCDNode)
        cmds.connectAttr('%s.outColorR'%visMaxCDNode,'%s.secondTerm'%visMainCDNode)
        
        cmds.setAttr('%s.colorIfTrueR'%visMinCDNode,0)
        cmds.setAttr('%s.colorIfFalseR'%visMinCDNode,1)
        cmds.setAttr('%s.operation'%visMinCDNode,4)
        
        cmds.setAttr('%s.colorIfTrueR'%visMaxCDNode,1)
        cmds.setAttr('%s.colorIfFalseR'%visMaxCDNode,0)
        cmds.setAttr('%s.operation'%visMaxCDNode,2)
        
        cmds.setAttr('%s.colorIfTrueR'%visMainCDNode,0)
        cmds.setAttr('%s.colorIfFalseR'%visMainCDNode,1)
        cmds.setAttr('%s.operation'%visMainCDNode,0)
        
        cmds.connectAttr('%s.outColorR'%visMainCDNode,'%s.outVis'%locator)
        cmds.connectAttr('%s.outVis'%locator,'%s.visibility'%selection[inc])
        
        rivetLocators.append(locator)
        
        inc += 1
        
    joints = MayaScripts.makeFloatingJoints(locators = rivetLocators, name = name)
    latticeMainGrp = cmds.group(name = '%s_Lattice_Grp'%name,empty = True)
    
    for i in range(len(joints)):
        
        zeroString = '0'

        if i> 9:
            zeroString = '' 
               
        cmds.select(cl = True)
        jointA = joints[i]
        jointB = joints[i-1]
            
        latticeName = '%s_%s%i_Lattice'%(name,zeroString,i+1)
        latticeShape = '%s_%s%i_LatticeShape'%(name,zeroString,i+1)
        
        lattice = cmds.lattice(divisions = (2,2,2),objectCentered = True, ldv = (2,2,2))
        latticeGrp = cmds.group(lattice,name = '%s_%s%i_Lattice_Grp'%(name,zeroString,i+1))
        
        cmds.setAttr ('%s.outsideLattice'%lattice[0], 1)
        cmds.parent(latticeGrp,latticeMainGrp)
        
        cmds.rename(lattice[0],'%s_%s%i_FFD'%(name,zeroString,i+1))
        cmds.rename(lattice[1],latticeName)
        cmds.rename(lattice[2],'%s_%s%i_Lat_Base'%(name,zeroString,i+1))

        positionA = cmds.xform(jointA, q = True, ws = True, translation = True)
        positionB = cmds.xform(jointB, q = True, ws = True, translation = True)
        vectorA = om.MVector(positionA[0],positionA[1],positionA[2])
        vectorB = om.MVector(positionB[0],positionB[1],positionB[2])
        vectorC = vectorA - vectorB
        
        latticeLength = (vectorC.length()*-1)
        latticeWidth = width*2.0
        '''
        scaleUnitA = om.MVector(normalVector[0],normalVector[1],normalVector[2])
        scaleUnitB = om.MVector(tangentVector[0],tangentVector[1],tangentVector[2])
        
        scaleA = scaleUnitA * latticeLength
        scaleB = scaleUnitB * latticeWidth
        
        latticeScaleX = scaleA.x +scaleB.x
        latticeScaleY = scaleA.y +scaleB.y 
        latticeScaleZ = scaleA.z +scaleB.z 
        latticeScale = [latticeScaleX,latticeScaleY,latticeScaleZ]
        '''
        
        cmds.setAttr('%s.rotatePivotX'%latticeGrp, 0.5)
        cmds.setAttr('%s.scalePivotX'%latticeGrp,0.5)
        
        nullPosGrp = cmds.group(empty = True)
        nullPosA = cmds.group(empty = True)
        nullPosB = cmds.group(empty  = True)
        nullPosC = cmds.group(empty = True)
        cmds.parent(nullPosA,nullPosB)
        cmds.parent(nullPosA,nullPosGrp)
        cmds.parent(nullPosB,nullPosGrp)
        cmds.parent(nullPosC,nullPosGrp)
        
        jointAPos = cmds.xform(jointA,q = True,ws = True,translation = True)
        jointARotation = cmds.xform(jointA,q = True,ws = True,rotation = True)
        
        jointBPos = cmds.xform(jointB,q = True,ws = True,translation = True)
        
        cmds.move(jointAPos[0],jointAPos[1],jointAPos[2],nullPosGrp,ws = True)
        cmds.rotate(jointARotation[0],jointARotation[1],jointARotation[2],nullPosGrp,ws = True)

        aimVector = (tangentVector[0] * -1,tangentVector[1] * -1,tangentVector[2] * -1)
        upVector = normalVector
        
        cmds.move(upVector[0],upVector[1],upVector[2],nullPosC, os = True)
        
        aimConstraint = cmds.aimConstraint(jointB,nullPosA,
                                           aim = (aimVector[0],aimVector[1],aimVector[2]),
                                           u = (upVector[0],upVector[1],upVector[2]))[0]
                                           
        preBindRotate = cmds.xform(nullPosA,q = True,ws = True,rotation = True)
        
        cmds.setAttr('%s.worldUpType'%aimConstraint,1)
        cmds.connectAttr( '%s.worldMatrix[0]'%nullPosC, '%s.worldUpMatrix'%aimConstraint)
        parentConstarint = cmds.parentConstraint(nullPosA,latticeGrp)
        cmds.delete(parentConstarint)
        
        cmds.move(jointBPos[0],jointBPos[1],jointBPos[2],nullPosB,ws = True)
        
        cmds.connectAttr('%s.outVis'%rivetLocators[i],'%s.scaleX'%latticeName)
        cmds.connectAttr('%s.outVis'%rivetLocators[i],'%s.scaleY'%latticeName)
        cmds.connectAttr('%s.outVis'%rivetLocators[i],'%s.scaleZ'%latticeName)
        cmds.scale(latticeLength,latticeWidth,1,latticeGrp,r = True)
        
        parentConstraintA = cmds.parentConstraint(nullPosA,jointA,st = ['x','y','z'])
        parentConstraintB = cmds.parentConstraint(nullPosA,jointB,st = ['x','y','z'])
        
        #cmds.rotate(preBindRotate[0],preBindRotate[1],preBindRotate[2],jointA,a = True,ws = True)
        #cmds.rotate(preBindRotate[0],preBindRotate[1],preBindRotate[2],jointB,a = True,ws = True)
        
        cmds.delete(parentConstraintA,parentConstraintB)

        cmds.skinCluster(jointA,jointB,latticeShape,mi = 1)
        cmds.skinCluster(jointA,selection[i])
        
        cmds.rotate(0,0,0,jointA,os = True)
        cmds.rotate(0,0,0,jointB,os = True)
        
        cmds.delete(nullPosGrp)
        
    cmds.delete(locators)
예제 #25
0
def build(**kwargs):

    selection = cmds.ls(sl=True)
    selection.sort()
    name = kwargs.get('name', 'TempName')
    vector = kwargs.get('vector', [1, 0, 0])
    width = kwargs.get('width', 1)
    normalVector = kwargs.get('normalVector', [0, 1, 0])
    tangentVector = kwargs.get('tangentVector', (-1, 0, 0))
    close = kwargs.get('close', True)

    locators = []

    for obj in selection:

        try:
            cluster = cmds.cluster(obj)
            pos = cmds.xform(cluster[1], q=True, ws=True, rp=True)
            locator = cmds.spaceLocator()
            cmds.move(pos[0], pos[1], pos[2], locator[0])
            locators.append(locator[0])
            cmds.delete(cluster)

        except RuntimeError:
            cmds.error('selection must be polyTransforms or verts')

    numLocators = len(locators)

    if numLocators == 0:
        cmds.error('locators were not created')

    #create ribbon
    ribbon = MayaScripts.buildRibbonSurface(locators=locators,
                                            name=name,
                                            close=close,
                                            vector=vector,
                                            width=width)
    cmds.addAttr(ribbon[0],
                 ln='minVisParam',
                 at='double',
                 min=-0.001,
                 max=1,
                 dv=-0.001)
    cmds.setAttr('%s.minVisParam' % ribbon[0], e=True, keyable=True)
    cmds.addAttr(ribbon[0], ln='maxVisParam', at='double', min=0, max=1, dv=1)
    cmds.setAttr('%s.maxVisParam' % ribbon[0], e=True, keyable=True)

    #args for rivets
    iterations = numLocators

    rivets = MayaScripts.makeRivets(iterations=iterations,
                                    surfaceName=ribbon[1],
                                    nodeNames=name,
                                    closedSurface=close,
                                    normalVector=normalVector,
                                    tangentVector=tangentVector)

    #tread anim attr
    cmds.addAttr(ribbon[0], ln='tread', at='double')
    cmds.setAttr('%s.tread' % ribbon[0], e=True, keyable=True)

    rivetLocators = []

    inc = 0

    for rivet in rivets:
        vValue = cmds.getAttr('%s.vValue' % rivet)
        mdNode = cmds.createNode('multiplyDivide', n='%s_MD' % rivet)
        cmds.setAttr('%s.input1X' % mdNode, 0.005)
        pmaNode = cmds.createNode('plusMinusAverage', n='%s_PMA' % rivet)
        cmds.connectAttr('%s.tread' % ribbon[0], '%s.input2X' % mdNode)
        cmds.connectAttr('%s.outputX' % mdNode, '%s.input1D[0]' % pmaNode)
        cmds.setAttr('%s.input1D[1]' % pmaNode, vValue)
        cmds.connectAttr('%s.output1D' % pmaNode, '%s.vValue' % rivet)

        locator = (cmds.connectionInfo('%s.outTranslation' % rivet,
                                       dfs=True))[0].split('.')[0]
        locatorName = locator.split('_Loc')[0]

        cmds.addAttr(locator, ln='outVis', at='bool')
        cmds.setAttr('%s.outVis' % locator, e=True, keyable=True)

        dmNode = cmds.createNode('decomposeMatrix', name='%s_DM' % locatorName)
        cpsNode = cmds.createNode('closestPointOnSurface',
                                  name='%s_CPS' % locatorName)

        visMinCDNode = cmds.createNode('condition',
                                       name='%s_Vis_Min_CD' % locatorName)
        visMaxCDNode = cmds.createNode('condition',
                                       name='%s_Vis_Max_CD' % locatorName)
        visMainCDNode = cmds.createNode('condition',
                                        name='%s_Vis_Main_CD' % locatorName)

        cmds.connectAttr('%s.worldMatrix[0]' % locator,
                         '%s.inputMatrix' % dmNode)
        cmds.connectAttr('%s.worldSpace[0]' % ribbon[1],
                         '%s.inputSurface' % cpsNode)
        cmds.connectAttr('%s.outputTranslate' % dmNode,
                         '%s.inPosition' % cpsNode)

        cmds.connectAttr('%s.minVisParam' % ribbon[0],
                         '%s.firstTerm' % visMinCDNode)
        cmds.connectAttr('%s.maxVisParam' % ribbon[0],
                         '%s.firstTerm' % visMaxCDNode)
        cmds.connectAttr('%s.parameterV' % cpsNode,
                         '%s.secondTerm' % visMinCDNode)
        cmds.connectAttr('%s.parameterV' % cpsNode,
                         '%s.secondTerm' % visMaxCDNode)
        cmds.connectAttr('%s.outColorR' % visMinCDNode,
                         '%s.firstTerm' % visMainCDNode)
        cmds.connectAttr('%s.outColorR' % visMaxCDNode,
                         '%s.secondTerm' % visMainCDNode)

        cmds.setAttr('%s.colorIfTrueR' % visMinCDNode, 0)
        cmds.setAttr('%s.colorIfFalseR' % visMinCDNode, 1)
        cmds.setAttr('%s.operation' % visMinCDNode, 4)

        cmds.setAttr('%s.colorIfTrueR' % visMaxCDNode, 1)
        cmds.setAttr('%s.colorIfFalseR' % visMaxCDNode, 0)
        cmds.setAttr('%s.operation' % visMaxCDNode, 2)

        cmds.setAttr('%s.colorIfTrueR' % visMainCDNode, 0)
        cmds.setAttr('%s.colorIfFalseR' % visMainCDNode, 1)
        cmds.setAttr('%s.operation' % visMainCDNode, 0)

        cmds.connectAttr('%s.outColorR' % visMainCDNode, '%s.outVis' % locator)
        cmds.connectAttr('%s.outVis' % locator,
                         '%s.visibility' % selection[inc])

        rivetLocators.append(locator)

        inc += 1

    joints = MayaScripts.makeFloatingJoints(locators=rivetLocators, name=name)
    latticeMainGrp = cmds.group(name='%s_Lattice_Grp' % name, empty=True)

    for i in range(len(joints)):

        zeroString = '0'

        if i > 9:
            zeroString = ''

        cmds.select(cl=True)
        jointA = joints[i]
        jointB = joints[i - 1]

        latticeName = '%s_%s%i_Lattice' % (name, zeroString, i + 1)
        latticeShape = '%s_%s%i_LatticeShape' % (name, zeroString, i + 1)

        lattice = cmds.lattice(divisions=(2, 2, 2),
                               objectCentered=True,
                               ldv=(2, 2, 2))
        latticeGrp = cmds.group(lattice,
                                name='%s_%s%i_Lattice_Grp' %
                                (name, zeroString, i + 1))

        cmds.setAttr('%s.outsideLattice' % lattice[0], 1)
        cmds.parent(latticeGrp, latticeMainGrp)

        cmds.rename(lattice[0], '%s_%s%i_FFD' % (name, zeroString, i + 1))
        cmds.rename(lattice[1], latticeName)
        cmds.rename(lattice[2], '%s_%s%i_Lat_Base' % (name, zeroString, i + 1))

        positionA = cmds.xform(jointA, q=True, ws=True, translation=True)
        positionB = cmds.xform(jointB, q=True, ws=True, translation=True)
        vectorA = om.MVector(positionA[0], positionA[1], positionA[2])
        vectorB = om.MVector(positionB[0], positionB[1], positionB[2])
        vectorC = vectorA - vectorB

        latticeLength = (vectorC.length() * -1)
        latticeWidth = width * 2.0
        '''
        scaleUnitA = om.MVector(normalVector[0],normalVector[1],normalVector[2])
        scaleUnitB = om.MVector(tangentVector[0],tangentVector[1],tangentVector[2])
        
        scaleA = scaleUnitA * latticeLength
        scaleB = scaleUnitB * latticeWidth
        
        latticeScaleX = scaleA.x +scaleB.x
        latticeScaleY = scaleA.y +scaleB.y 
        latticeScaleZ = scaleA.z +scaleB.z 
        latticeScale = [latticeScaleX,latticeScaleY,latticeScaleZ]
        '''

        cmds.setAttr('%s.rotatePivotX' % latticeGrp, 0.5)
        cmds.setAttr('%s.scalePivotX' % latticeGrp, 0.5)

        nullPosGrp = cmds.group(empty=True)
        nullPosA = cmds.group(empty=True)
        nullPosB = cmds.group(empty=True)
        nullPosC = cmds.group(empty=True)
        cmds.parent(nullPosA, nullPosB)
        cmds.parent(nullPosA, nullPosGrp)
        cmds.parent(nullPosB, nullPosGrp)
        cmds.parent(nullPosC, nullPosGrp)

        jointAPos = cmds.xform(jointA, q=True, ws=True, translation=True)
        jointARotation = cmds.xform(jointA, q=True, ws=True, rotation=True)

        jointBPos = cmds.xform(jointB, q=True, ws=True, translation=True)

        cmds.move(jointAPos[0],
                  jointAPos[1],
                  jointAPos[2],
                  nullPosGrp,
                  ws=True)
        cmds.rotate(jointARotation[0],
                    jointARotation[1],
                    jointARotation[2],
                    nullPosGrp,
                    ws=True)

        aimVector = (tangentVector[0] * -1, tangentVector[1] * -1,
                     tangentVector[2] * -1)
        upVector = normalVector

        cmds.move(upVector[0], upVector[1], upVector[2], nullPosC, os=True)

        aimConstraint = cmds.aimConstraint(jointB,
                                           nullPosA,
                                           aim=(aimVector[0], aimVector[1],
                                                aimVector[2]),
                                           u=(upVector[0], upVector[1],
                                              upVector[2]))[0]

        preBindRotate = cmds.xform(nullPosA, q=True, ws=True, rotation=True)

        cmds.setAttr('%s.worldUpType' % aimConstraint, 1)
        cmds.connectAttr('%s.worldMatrix[0]' % nullPosC,
                         '%s.worldUpMatrix' % aimConstraint)
        parentConstarint = cmds.parentConstraint(nullPosA, latticeGrp)
        cmds.delete(parentConstarint)

        cmds.move(jointBPos[0], jointBPos[1], jointBPos[2], nullPosB, ws=True)

        cmds.connectAttr('%s.outVis' % rivetLocators[i],
                         '%s.scaleX' % latticeName)
        cmds.connectAttr('%s.outVis' % rivetLocators[i],
                         '%s.scaleY' % latticeName)
        cmds.connectAttr('%s.outVis' % rivetLocators[i],
                         '%s.scaleZ' % latticeName)
        cmds.scale(latticeLength, latticeWidth, 1, latticeGrp, r=True)

        parentConstraintA = cmds.parentConstraint(nullPosA,
                                                  jointA,
                                                  st=['x', 'y', 'z'])
        parentConstraintB = cmds.parentConstraint(nullPosA,
                                                  jointB,
                                                  st=['x', 'y', 'z'])

        #cmds.rotate(preBindRotate[0],preBindRotate[1],preBindRotate[2],jointA,a = True,ws = True)
        #cmds.rotate(preBindRotate[0],preBindRotate[1],preBindRotate[2],jointB,a = True,ws = True)

        cmds.delete(parentConstraintA, parentConstraintB)

        cmds.skinCluster(jointA, jointB, latticeShape, mi=1)
        cmds.skinCluster(jointA, selection[i])

        cmds.rotate(0, 0, 0, jointA, os=True)
        cmds.rotate(0, 0, 0, jointB, os=True)

        cmds.delete(nullPosGrp)

    cmds.delete(locators)
예제 #26
0
[email protected]
Description     : select lattice and run the script
Input           : mesh > lattice > skincluster
Maya version    : Maya 2016
'''

import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
import maya.cmds as cmds

#cmds.select ('ffd1Lattice', r=1)
selectList = cmds.ls(sl=1)
latticeShape = cmds.listRelatives(selectList[0], type='lattice')[0]
ffd = cmds.listConnections(latticeShape, type='ffd')[0]
skincluster = cmds.listConnections(latticeShape, type='skinCluster')[0]
geometry = cmds.lattice(latticeShape, q=1, g=1)[0]
jointList = cmds.skinCluster(skincluster, q=1, inf=1)

#Geometry to Dag Path
meshMSelection = om.MSelectionList()
meshMSelection.add(geometry)
meshDagPath = meshMSelection.getDagPath(0)

#Get the mesh orgin position
mFnMesh = om.MFnMesh(meshDagPath)
geoPosition = mFnMesh.getPoints(om.MSpace.kObject)

#Get the weight from each joint
weightList = []
for index in range(len(jointList)):
    jntParent = cmds.listRelatives(jointList[index], p=1)
예제 #27
0
    def eyelattic(self):

        model = cmds.ls(sl=1)
        cmds.lattice(n=model[0],dv=(10,10,10),oc=1)
        cmds.parent(model[0]+'1Lattice','L_eyeBall_jnt')
        cmds.parent(model[0]+'1Base','Eye_grp')
예제 #28
0
 def buildSpineControls(self, pivotJoint, name):
     
     #create lattice
     lattice = cmds.lattice(divisions = (2,2,2), objectCentered = True, ldv = (2,2,2))[1]
     
     #find lattice point positions in world space
     
     frontTopRight = cmds.xform((lattice + ".pt[0][0][1]"), q = True, ws = True, t = True)
     backTopRight = cmds.xform((lattice + ".pt[0][1][1]"), q = True, ws = True, t = True)
     frontTopLeft = cmds.xform((lattice + ".pt[1][0][1]"), q = True, ws = True, t = True)
     backTopLeft = cmds.xform((lattice + ".pt[1][1][1]"), q = True, ws = True, t = True)
     frontBottomRight = cmds.xform((lattice + ".pt[0][0][0]"), q = True, ws = True, t = True)
     backBottomRight = cmds.xform((lattice + ".pt[0][1][0]"), q = True, ws = True, t = True)
     frontBottomLeft = cmds.xform((lattice + ".pt[1][0][0]"), q = True, ws = True, t = True)
     backBottomLeft = cmds.xform((lattice + ".pt[1][1][0]"), q = True, ws = True, t = True)
     
     #create a curve (cube) using the positions of the lattice points
     globalMoverControl = cmds.curve(name = (name + "_mover"), d = 1, p=[(frontBottomRight), (frontTopRight), (frontTopLeft), (frontBottomLeft), (frontBottomRight), (frontTopRight), (backTopRight), (backBottomRight), (backBottomLeft), (frontBottomLeft), (frontTopLeft), (backTopLeft), (backBottomLeft), (backBottomRight), (backTopRight), (backTopLeft)])
     
     #make correct pivot for global control
     pivot = cmds.xform(pivotJoint, q = True, ws = True, t = True)
     cmds.xform(globalMoverControl, piv = pivot)
     
     #create global mover group
     globalMoverGroup = cmds.group(empty = True, name = (name + "_mover_grp"))
     constraint = cmds.parentConstraint(pivotJoint, globalMoverGroup)[0]
     cmds.delete(constraint)
     
     cmds.parent(globalMoverControl, globalMoverGroup)
     cmds.setAttr(globalMoverControl + ".overrideEnabled", 1)
     cmds.setAttr(globalMoverControl + ".overrideColor", 17)
     
     #duplicate the globalMoverControl and scale it down
     offsetMoverControl = cmds.duplicate(globalMoverControl, name = (name + "_mover_offset"))[0]
     cmds.setAttr(offsetMoverControl + ".scaleX", .85)
     cmds.setAttr(offsetMoverControl + ".scaleY", .85)
     cmds.setAttr(offsetMoverControl + ".scaleZ", .85)
     
     cmds.xform(offsetMoverControl, piv = pivot)
     
     cmds.parent(offsetMoverControl, globalMoverControl)
     cmds.setAttr(offsetMoverControl + ".overrideEnabled", 1)
     cmds.setAttr(offsetMoverControl + ".overrideColor", 18)
     
     
     #freeze transforms
     cmds.makeIdentity(globalMoverControl, apply = True, t = True, r = True, s = True)
     
     
     #create the geo mover control
     geoMover = cmds.duplicate("geo_mover", name = (name + "_geo_mover"))[0]
     shapeNode = cmds.listRelatives(geoMover, children = True, shapes = True)[0]
     cmds.setAttr(geoMover + "|" + shapeNode + ".visibility", 0)
     
     constraint = cmds.pointConstraint(lattice, geoMover)[0]
     cmds.delete(constraint)
     
     cmds.parent(geoMover, offsetMoverControl)
     cmds.makeIdentity(geoMover, apply = True, t = True, r = True, s = True)
 
     
     #create lra controls
     lraGroup = cmds.group(empty = True, name = (name + "_lra_grp"))
     constraint = cmds.parentConstraint(pivotJoint, lraGroup)[0]
     cmds.delete(constraint)
     cmds.parent(lraGroup, offsetMoverControl)
     
     lraCtrl = cmds.duplicate("lra", name = (name + "_lra"))[0]
     cmds.setAttr(lraCtrl + ".v", 1)
     constraint = cmds.parentConstraint(lraGroup, lraCtrl)[0]
     cmds.delete(constraint)
     cmds.parent(lraCtrl, lraGroup)
     cmds.makeIdentity(lraCtrl, apply = True, t = True, r = True, s = True)
     
     #lock translations and rotations on lra controls
     cmds.setAttr(lraCtrl + ".tx", lock = True, k = False)
     cmds.setAttr(lraCtrl + ".ty", lock = True, k = False)
     cmds.setAttr(lraCtrl + ".tz", lock = True, k = False)
     cmds.setAttr(lraCtrl + ".rx", lock = True, k = False)
     cmds.setAttr(lraCtrl + ".ry", lock = True, k = False)
     cmds.setAttr(lraCtrl + ".rz", lock = True, k = False)
     
     
     #delete lattice
     cmds.delete(lattice)
     
     cmds.container("JointMover", edit = True, addNode = globalMoverGroup, includeNetwork=True,includeHierarchyBelow=True)
     return [globalMoverGroup, globalMoverControl, offsetMoverControl, geoMover]
예제 #29
0
파일: rivet.py 프로젝트: jonntd/zentools
	def create(self):

		worldMatrixNode=mc.createNode('fourByFourMatrix')
		wm=\
		[
			[1,0,0,0],
			[0,1,0,0],
			[0,0,1,0],
			[0,0,0,1]
		]
		for a in range(0,4):
			for b in range(0,4):
				mc.setAttr( worldMatrixNode+'.in'+str(a)+str(b), wm[a][b] )

		self.worldMatrix=worldMatrixNode+'.o'

		wsMatrices=[]

		cleanup=[]

		lattices=[]
		uvPos=[]
		antipodes=[]

		cpos=mc.createNode('closestPointOnSurface')

		if 'surfaceAttr' not in self.__dict__ or len(self.surfaceAttr)==0 and len(self.edges)>0:
			mc.select(self.edges)
			rebuildNode,surfaceNodeTr=mel.eval('zenLoftBetweenEdgeLoopPathRings(2)')[:2]
			self.surfaceAttr=rebuildNode+'.outputSurface'

			children=mc.listRelatives(surfaceNodeTr,c=True,s=True,ni=True,type='nurbsSurface')
			if isIterable(children) and len(children)>0:
				self.uSpans=mc.getAttr(children[0]+'.spansU')
				self.vSpans=mc.getAttr(children[0]+'.spansV')

			mc.disconnectAttr(self.surfaceAttr,surfaceNodeTr+'.create')
			mc.delete(surfaceNodeTr)


		if self.uSpans<0 or self.vSpans<0:
			tempTr=mc.createNode('transform')
			tempCurve=mc.createNode('nurbsCurve',p=tempTr)
			mc.connectAttr(self.surfaceAttr,tempCurve+'.create')
			self.uSpans=mc.getAttr(tempCurve+'.spansU')
			self.vSpans=mc.getAttr(tempCurve+'.spansV')
			mc.disconnectAttr(self.surfaceAttr,tempCurve+'.create')
			mc.delete(tempTr)

		orderedTrs=[]
		orderedCtrls=[]

		if self.distribute not in ['u','v']: #calculate the axis of distribution
			if len(self.trs)!=0:
				mc.connectAttr(self.surfaceAttr,cpos+'.inputSurface')
				uMin=100
				vMin=100
				uMax=0
				vMax=0
				uPosList=[]
				vPosList=[]

				for i in range(0,self.number):

					orderedTrs.append('')
					orderedCtrls.append('')
					t=self.trs[i]

					if mc.objExists(t): # find the closest point
						if self.hasGeometry:
							center=mc.objectCenter(t)
							mc.setAttr(cpos+'.ip',*center)
							posCenter,uCenter,vCenter=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

						rp=mc.xform(t,ws=True,q=True,rp=True)
						mc.setAttr(cpos+'.ip',*rp)
						posRP,uRP,vRP=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

						# see which is closer - object center or rotate pivot
						if self.hasGeometry:
							distCenter=distanceBetween(posCenter,center)
							distRP=distanceBetween(posRP,rp)

						if self.hasGeometry==False or abs(distCenter)>abs(distRP) :
							uPosList.append(uRP)
							vPosList.append(vRP)
							if uRP<uMin: uMin=uRP
							if uRP>uMax: uMax=uRP
							if vRP<vMin: vMin=vRP
							if vRP>vMax: vMax=vRP
						else:
							uPosList.append(uCenter)
							vPosList.append(vCenter)
							if uCenter<uMin: uMin=uCenter
							if uCenter>uMax: uMax=uCenter
							if vCenter<vMin: vMin=vCenter
							if vCenter>vMax: vMax=vCenter

			cfsi=mc.createNode('curveFromSurfaceIso')

			mc.connectAttr(self.surfaceAttr,cfsi+'.is')
			mc.setAttr(cfsi+'.idr',0)
			mc.setAttr(cfsi+'.iv',.5)
			mc.setAttr(cfsi+'.r',True)
			mc.setAttr(cfsi+'.rv',True)

			if len(self.trs)!=0:
				mc.setAttr(cfsi+'.min',uMin)
				mc.setAttr(cfsi+'.max',uMax)

			ci=mc.createNode('curveInfo')
			mc.connectAttr(cfsi+'.oc',ci+'.ic')
			uLength=mc.getAttr(ci+'.al')

			mc.setAttr(cfsi+'.idr',1)

			if len(self.trs)!=0:
				mc.setAttr(cfsi+'.min',vMin)
				mc.setAttr(cfsi+'.max',vMax)

			vLength=mc.getAttr(ci+'.al')

			mc.delete(cfsi,ci)

			if uLength>vLength:
				self.distribute='u'

				if len(self.trs)!=0:
					searchList=uPosList
					orderedList=uPosList[:]
					orderedList.sort()
			else:
				self.distribute='v'

				if len(self.trs)!=0:
					searchList=vPosList
					orderedList=vPosList[:]
					orderedList.sort()

			reverseTrs=False

			orderIDList=[]
			for n in range(0,self.number):
				s=searchList[n]
				for i in range(0,self.number):
					if s==orderedList[i] and i not in orderIDList:
						orderIDList.append(i)
						orderedTrs[i]=self.trs[n]
						orderedCtrls[i]=self.ctrls[n]
						if n==0 and i>len(self.trs)/2:
							reverseTrs=True
						break

			if reverseTrs:
				orderedTrs.reverse()
				self.trs=orderedTrs
				orderedCtrls.reverse()
				self.ctrls=orderedCtrls
			else:
				self.trs=orderedTrs
				self.ctrls=orderedCtrls

		if self.rebuild: # interactive rebuild, maintains even parameterization over the rivet surface, use with caution

			if self.distribute=='u':
				self.surfaceAttr=mel.eval('zenUniformSurfaceRebuild("'+self.surfaceAttr+'",'+str(self.uSpans*2)+',-1)')+'.outputSurface'
			else:
				self.surfaceAttr=mel.eval('zenUniformSurfaceRebuild("'+self.surfaceAttr+'",-1,'+str(self.vSpans*2)+')')+'.outputSurface'

		if not mc.isConnected(self.surfaceAttr,cpos+'.inputSurface'):
			mc.connectAttr(self.surfaceAttr,cpos+'.inputSurface',f=True)

		if self.taper=='distance' or self.createAimCurve or self.closestPoint=='geometry': # find the closest points ( and antipodes )

			for i in range(0,self.number):
				t=self.trs[i]
				cp=ClosestPoints(self.surfaceAttr,t)
				self.ClosestPoints.append(cp)

				if self.taper=='distance' or self.createAimCurve: # antipodes are used for lattice allignment and curve calculations
					antipodes.append(cp.getAntipodes(1))

		if self.taper!='none' or self.scale!='none': # measures scale with scaling

			cfsiLength=mc.createNode('curveFromSurfaceIso')
			ciLength=mc.createNode('curveInfo')
			lengthMultiplierNode=mc.createNode('multDoubleLinear')

			mc.setAttr(cfsiLength+'.relative',True)
			mc.setAttr(cfsiLength+'.relativeValue',True)

			if self.distribute=='u':
				mc.setAttr(cfsiLength+'.isoparmDirection',0)
			else:
				mc.setAttr(cfsiLength+'.isoparmDirection',1)

			mc.setAttr(cfsiLength+'.minValue',0)
			mc.setAttr(cfsiLength+'.maxValue',1)

			mc.setAttr(cfsiLength+".isoparmValue",.5)

			mc.connectAttr(self.surfaceAttr,cfsiLength+'.inputSurface')

			if mc.objExists(self.spaceTr):

				lengthCurve=mc.createNode('nurbsCurve',p=self.spaceTr)
				lengthCurveTG=mc.createNode('transformGeometry')

				mc.connectAttr(self.spaceTr+'.worldMatrix[0]',lengthCurveTG+'.txf')
				mc.connectAttr(cfsiLength+'.outputCurve',lengthCurveTG+'.ig')
				mc.connectAttr(lengthCurveTG+'.og',lengthCurve+'.create')
				mc.connectAttr(lengthCurve+'.worldSpace',ciLength+'.inputCurve')
				mc.setAttr(lengthCurve+'.intermediateObject',True)

				cleanup.extend([lengthCurveTG,cfsiLength])

			else:

				mc.connectAttr(cfsiLength+'.outputCurve',ciLength+'.inputCurve')

			mc.connectAttr(ciLength+'.al',lengthMultiplierNode+'.i1')
			mc.setAttr(lengthMultiplierNode+'.i2',1.0/float(mc.getAttr(ciLength+'.al')))

			lengthMultiplier=lengthMultiplierNode+'.o'


		uvPos=[]
		closestDistanceToCenter=Decimal('infinity')
		centerMostRivetID=0
		closestDistancesToCenter=[Decimal('infinity'),Decimal('infinity')]
		centerMostRivetIDs=[0,0]

		uvMultipliers=[]
		aimGroups=[]

		for i in range(0,self.number):

			pTrs=mc.listRelatives(self.trs[i],p=True)
			parentTr=''
			if len(iterable(pTrs))>0:
				parentTr=pTrs[0]

			t=self.trs[i]
			c=self.ctrls[i]
			r=mc.createNode('transform',n='Rivet#')

			wsMatrices.append(mc.xform(t,q=True,ws=True,m=True))

			if self.constraint: mc.setAttr(r+'.inheritsTransform',False)

			if not mc.objExists(c):
				c=t
				if not mc.objExists(t):
					c=r

			if not mc.objExists(c+'.zenRivet'):
				mc.addAttr(c,at='message',ln='zenRivet',sn='zriv')

			mc.connectAttr(r+'.message',c+'.zriv',f=True)

			if not mc.objExists(c+'.uPos'):
				mc.addAttr(c,k=True,at='double',ln='uPos',dv=50)
			if not mc.objExists(c+'.vPos'):
				mc.addAttr(c,k=True,at='double',ln='vPos',dv=50)

			if self.closestPoint=='geometry':
				up,vp=self.ClosestPoints[i].uvs[0]
			else:
				if mc.objExists(t):
					if self.hasGeometry:
						center=mc.objectCenter(t)
						mc.setAttr(cpos+'.ip',*center)
						posCenter,uCenter,vCenter=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

					rp=mc.xform(t,ws=True,q=True,rp=True)
					mc.setAttr(cpos+'.ip',*rp)
					posRP,uRP,vRP=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

					if self.hasGeometry:
						distCenter=distanceBetween(posCenter,center)
						distRP=distanceBetween(posRP,rp)

					if self.hasGeometry==False or abs(distCenter)>abs(distRP):
						up=uRP
						vp=vRP
					else:
						up=uCenter
						vp=vCenter

				elif len(distribute)>0:

					if self.distribute=='u':
						up=(i+1)/self.number
						vp=.5
					else:
						up=.5
						vp=(i+1)/self.number

			if up>float(self.uSpans)-.01: up=float(self.uSpans)-.01
			if vp>float(self.vSpans)-.01: vp=float(self.vSpans)-.01
			if up<.01: up=.01
			if vp<.01: vp=.01

			uvPos.append((up,vp))

			if up<.5 and self.distribute=='u' and Decimal(str(abs(.5-up)))<Decimal(str(closestDistancesToCenter[0])):
				closestDistancesToCenter[0]=abs(.5-up)
				centerMostRivetIDs[0]=i

			if up>.5 and self.distribute=='u' and Decimal(str(abs(.5-up)))<Decimal(str(closestDistancesToCenter[1])):
				closestDistancesToCenter[1]=abs(.5-up)
				centerMostRivetIDs[1]=i

			if up<.5 and self.distribute=='v' and Decimal(str(abs(.5-vp)))<Decimal(str(closestDistancesToCenter[0])):
				closestDistancesToCenter[0]=abs(.5-vp)
				centerMostRivetIDs[0]=i

			if up>.5 and self.distribute=='v' and Decimal(str(abs(.5-vp)))<Decimal(str(closestDistancesToCenter[1])):
				closestDistancesToCenter[1]=abs(.5-vp)
				centerMostRivetIDs[1]=i

			mc.setAttr(c+'.uPos',up*100)
			mc.setAttr(c+'.vPos',vp*100)

			posi=mc.createNode('pointOnSurfaceInfo')
			mc.setAttr((posi+".caching"),True)
			#mc.setAttr((posi+".top"),True)

			multiplyU=mc.createNode('multDoubleLinear')
			mc.connectAttr(c+".uPos",multiplyU+".i1")
			mc.setAttr(multiplyU+'.i2',.01)
			multiplyV=mc.createNode('multDoubleLinear')
			mc.connectAttr(c+".vPos",multiplyV+".i1")
			mc.setAttr(multiplyV+'.i2',.01)

			uvMultipliers.append([multiplyU,multiplyV])

			mc.connectAttr(self.surfaceAttr,posi+".inputSurface");
			mc.connectAttr(multiplyU+".o",posi+".parameterU")
			mc.connectAttr(multiplyV+".o",posi+".parameterV")

			dm=mc.createNode('decomposeMatrix')
			mc.setAttr(dm+'.caching',True)
			fbfm=mc.createNode('fourByFourMatrix')
			mc.setAttr(fbfm+'.caching',True)

			mc.connectAttr(posi+'.nnx',fbfm+'.in00')
			mc.connectAttr(posi+'.nny',fbfm+'.in01')
			mc.connectAttr(posi+'.nnz',fbfm+'.in02')
			mc.connectAttr(posi+'.nux',fbfm+'.in10')
			mc.connectAttr(posi+'.nuy',fbfm+'.in11')
			mc.connectAttr(posi+'.nuz',fbfm+'.in12')
			mc.connectAttr(posi+'.nvx',fbfm+'.in20')
			mc.connectAttr(posi+'.nvy',fbfm+'.in21')
			mc.connectAttr(posi+'.nvz',fbfm+'.in22')
			mc.connectAttr(posi+'.px',fbfm+'.in30')
			mc.connectAttr(posi+'.py',fbfm+'.in31')
			mc.connectAttr(posi+'.pz',fbfm+'.in32')

			if self.constraint:# and not self.parent:
				mc.connectAttr(fbfm+'.output',dm+'.inputMatrix')
			else:
				multMatrix=mc.createNode('multMatrix')
				mc.connectAttr(r+'.parentInverseMatrix',multMatrix+'.i[1]')
				mc.connectAttr(fbfm+'.output',multMatrix+'.i[0]')
				mc.connectAttr(multMatrix+'.o',dm+'.inputMatrix')

			mc.connectAttr(dm+'.outputTranslate',r+'.t')
			mc.connectAttr(dm+'.outputRotate',r+'.r')

			if t!=r:

				if self.createAimCurve:
					aimGroup=mc.createNode('transform',n='rivetAimGrp#')
					mc.parent(aimGroup,t,r=True)
					mc.parent(aimGroup,r)
					if self.keepPivot or self.closestPoint=='pivot':
						mc.xform(aimGroup,ws=True,piv=mc.xform(t,q=True,ws=True,rp=True))
					else:
						mc.xform(aimGroup,ws=True,piv=self.ClosestPoints[i][1])
					self.aimGroups.append(aimGroup)

				if self.constraint:

					if self.parent: # parent and constraint == ParentSpace

						self.parentSpaces.append(ParentSpace(t,r))
						pc=self.parentSpaces[i].parentConstraint

						sc=self.parentSpaces[i].scaleConstraint

						skip=['x']
						if\
						(
							(self.distribute=='v' and 'length' in self.scaleDirection) or
							(self.distribute=='u' and 'width' in self.scaleDirection) or
							t in self.skipScaleObjects
						):
							skip.append('y')
						if\
						(
							(self.distribute=='u' and 'length' in self.scaleDirection) or
							(self.distribute=='v' and 'width' in self.scaleDirection) or
							t in self.skipScaleObjects
						):
							skip.append('z')

						mc.scaleConstraint(sc,e=True,sk=skip)

						if t in self.skipRotateObjects:
							mc.parentConstraint(pc,e=True,sr=('x','y','z'))
						if t in self.skipTranslateObjects:
							mc.parentConstraint(pc,e=True,st=('x','y','z'))

					else: #just constraint

						if t in self.skipRotateObjects:
							pc=mc.parentConstraint(r,t,sr=('x','y','z'),mo=True)[0]#
						if t in self.skipTranslateObjects:
							pc=mc.parentConstraint(r,t,st=('x','y','z'),mo=self.mo)[0]
						if t not in self.skipRotateObjects and t not in self.skipTranslateObjects:
							pc=mc.parentConstraint(r,t,mo=self.mo)[0]



					pcTargets=mc.parentConstraint(pc,q=True,tl=True)

					pcIDs=[]

					nsc=listNodeConnections(r,pc,s=False,d=True)

					for n in range(0,len(nsc)):
						if len(nsc[n])==2 and mc.objExists(nsc[n][-1]):
							pcID=getIDs(nsc[n][-1])
							if isinstance(pcID,int):
								pcIDs.append(pcID)

					pcIDs=removeDuplicates(pcIDs)

					for pcID in pcIDs:
						mc.connectAttr(self.worldMatrix,pc+'.tg['+str(pcID)+'].tpm',f=True)
						mc.connectAttr(dm+'.outputTranslate',pc+'.tg['+str(pcID)+'].tt',f=True)
						mc.connectAttr(dm+'.outputRotate',pc+'.tg['+str(pcID)+'].tr',f=True)

					cleanup.append(r)

					if self.parent:

						scTargets=mc.scaleConstraint(sc,q=True,tl=True)

						scIDs=[]

						nsc=listNodeConnections(r,sc,s=False,d=True)

						for n in range(0,len(nsc)):
							if len(nsc[n])==2 and mc.objExists(nsc[n][-1]):
								scIDs.append(getIDs(nsc[n][-1]))

						scIDs=removeDuplicates(scIDs)

						scMD=mc.createNode('multiplyDivide')
						mc.setAttr(scMD+'.i1',1,1,1)
						mc.setAttr(scMD+'.i2',1,1,1)

						for scID in scIDs:

							mc.connectAttr(self.worldMatrix,sc+'.tg['+str(scID)+'].tpm',f=True)
							#mc.connectAttr(scMD+'.o',sc+'.tg['+str(scID)+'].ts',f=True)
							mc.connectAttr(scMD+'.ox',sc+'.tg['+str(scID)+'].tsx',f=True)
							mc.connectAttr(scMD+'.oy',sc+'.tg['+str(scID)+'].tsy',f=True)
							mc.connectAttr(scMD+'.oz',sc+'.tg['+str(scID)+'].tsz',f=True)

						r=self.parentSpaces[i][0]
						#xfm=mc.xform(r,q=True,ws=True,m=True)
						#mc.setAttr(r+'.inheritsTransform',False)
						#mc.xform(r,m=xfm)
						#mc.connectAttr(self.surfaceMatrix,multMatrix+'.i[1]',f=True)#self.parentSpaces[i][0]+'.parentInverseMatrix'

				elif self.createAimCurve:
					mc.parent(t,w=True)
					mc.setAttr(t+'.inheritsTransform',False)
					mc.parent(t,r,r=True)
				else:
					mc.parent(t,r)

				if mc.objExists(parentTr) and (self.parent or self.createAimCurve) and not self.constraint:

					if not (parentTr in iterable(mc.listRelatives(r,p=True))):

						if mc.getAttr(r+'.inheritsTransform')==True:
							mc.parent(r,parentTr,r=True)
						else:
							mc.parent(r,parentTr)

					if mc.getAttr(r+'.inheritsTransform')==False:

						dm=mc.createNode('decomposeMatrix')
						mc.connectAttr(parentTr+'.worldMatrix',dm+'.inputMatrix')
						mc.connectAttr(dm+'.os',t+'.s',f=True)

			if self.taper!='none' or self.scale!='none':

				cfsiU=mc.createNode('curveFromSurfaceIso')

				mc.setAttr(cfsiU+'.relative',True)
				mc.setAttr(cfsiU+'.relativeValue',True)
				mc.setAttr(cfsiU+'.isoparmDirection',0)
				mc.setAttr(cfsiU+'.minValue',0)
				mc.setAttr(cfsiU+'.maxValue',1)

				mc.connectAttr(multiplyV+".o",cfsiU+".isoparmValue")
				mc.connectAttr(self.surfaceAttr,cfsiU+'.inputSurface')

				cfsiV=mc.createNode('curveFromSurfaceIso')

				mc.setAttr(cfsiV+'.relative',True)
				mc.setAttr(cfsiV+'.relativeValue',True)
				mc.setAttr(cfsiV+'.isoparmDirection',1)
				mc.setAttr(cfsiV+'.minValue',0)
				mc.setAttr(cfsiV+'.maxValue',1)

				mc.connectAttr(multiplyV+".o",cfsiV+".isoparmValue")
				mc.connectAttr(self.surfaceAttr,cfsiV+'.inputSurface')

				subtractNode=mc.createNode('addDoubleLinear')
				mc.setAttr(subtractNode+'.i1',-(1/(self.number*2)))
				addNode=mc.createNode('addDoubleLinear')
				mc.setAttr(addNode+'.i1',1/(self.number*2))
				addSubClampNode=mc.createNode('clamp')
				mc.setAttr(addSubClampNode+'.min',0,0,0)
				mc.setAttr(addSubClampNode+'.max',1,1,1)
				mc.connectAttr(subtractNode+'.o',addSubClampNode+'.inputR')
				mc.connectAttr(addNode+'.o',addSubClampNode+'.inputG')

				if self.distribute=='u':
					mc.connectAttr(multiplyU+".o",subtractNode+".i2")
					mc.connectAttr(multiplyU+".o",addNode+".i2")
					mc.connectAttr(addSubClampNode+'.outputR',cfsiU+'.minValue')
					mc.connectAttr(addSubClampNode+'.outputG',cfsiU+'.maxValue')
				else:
					mc.connectAttr(multiplyV+".o",subtractNode+".i2")
					mc.connectAttr(multiplyV+".o",addNode+".i2")
					mc.connectAttr(addSubClampNode+'.outputR',cfsiV+'.minValue')
					mc.connectAttr(addSubClampNode+'.outputG',cfsiV+'.maxValue')

				ciU=mc.createNode('curveInfo')
				mc.connectAttr(cfsiU+'.outputCurve',ciU+'.inputCurve')

				ciV=mc.createNode('curveInfo')
				mc.connectAttr(cfsiV+'.outputCurve',ciV+'.inputCurve')

				mdlU=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciU+'.al',mdlU+'.i1')
				mc.setAttr(mdlU+'.i2',1/float(mc.getAttr(ciU+'.al')))

				mdlV=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciV+'.al',mdlV+'.i1')
				mc.setAttr(mdlV+'.i2',1/float(mc.getAttr(ciV+'.al')))

				if not mc.objExists(c+'.minScaleWidth'): mc.addAttr(c,ln='minScaleWidth',at='double',k=True,min=0,dv=self.minScaleWidth)
				if not mc.objExists(c+'.maxScaleWidth'): mc.addAttr(c,ln='maxScaleWidth',at='double',k=True,min=0,dv=self.maxScaleWidth)
				if not mc.objExists(c+'.minScaleLength'): mc.addAttr(c,ln='minScaleLength',at='double',k=True,min=0,dv=self.minScaleLength)
				if not mc.objExists(c+'.maxScaleLength'): mc.addAttr(c,ln='maxScaleLength',at='double',k=True,min=0,dv=self.maxScaleLength)

				clampNode=mc.createNode('clamp')

				minScaleLengthNode=mc.createNode('multDoubleLinear')
				maxScaleLengthNode=mc.createNode('multDoubleLinear')
				minScaleWidthNode=mc.createNode('multDoubleLinear')
				maxScaleWidthNode=mc.createNode('multDoubleLinear')

				mc.connectAttr(c+'.minScaleLength',minScaleLengthNode+'.i1')
				mc.connectAttr(lengthMultiplier,minScaleLengthNode+'.i2')

				mc.connectAttr(c+'.maxScaleLength',maxScaleLengthNode+'.i1')
				mc.connectAttr(lengthMultiplier,maxScaleLengthNode+'.i2')

				mc.connectAttr(c+'.minScaleWidth',minScaleWidthNode+'.i1')
				mc.connectAttr(lengthMultiplier,minScaleWidthNode+'.i2')

				mc.connectAttr(c+'.maxScaleWidth',maxScaleWidthNode+'.i1')
				mc.connectAttr(lengthMultiplier,maxScaleWidthNode+'.i2')

				if self.distribute=='u':
					mc.connectAttr(minScaleLengthNode+'.o',clampNode+'.minR')
					mc.connectAttr(maxScaleLengthNode+'.o',clampNode+'.maxR')
					mc.connectAttr(minScaleWidthNode+'.o',clampNode+'.minG')
					mc.connectAttr(maxScaleWidthNode+'.o',clampNode+'.maxG')
				else:
					mc.connectAttr(minScaleWidthNode+'.o',clampNode+'.minR')
					mc.connectAttr(maxScaleWidthNode+'.o',clampNode+'.maxR')
					mc.connectAttr(minScaleLengthNode+'.o',clampNode+'.minG')
					mc.connectAttr(maxScaleLengthNode+'.o',clampNode+'.maxG')

				mc.connectAttr(mdlU+'.o',clampNode+'.ipr')
				mc.connectAttr(mdlV+'.o',clampNode+'.ipg')

				if self.scale=='relative' and self.parent:#or len(self.scaleDirection)<2:#

					if\
					(
						(self.distribute=='u' and 'length' in self.scaleDirection) or
						(self.distribute=='v' and 'width' in self.scaleDirection)
					):
						if self.constraint:
							mc.connectAttr(clampNode+'.opr',scMD+'.i1y')
						else:
							mc.connectAttr(clampNode+'.opr',r+'.sy',f=True)
					if\
					(
						(self.distribute=='v' and 'length' in self.scaleDirection) or
						(self.distribute=='u' and 'width' in self.scaleDirection)
					):
						if self.constraint:
							mc.connectAttr(clampNode+'.opg',scMD+'.i1z')
						else:
							mc.connectAttr(clampNode+'.opg',r+'.sz',f=True)


				elif self.taper!='none' and self.parent:

					#self.autoFlexGroups

					mc.setAttr(t+'.sx',lock=True)
					mc.setAttr(t+'.sy',lock=True)
					mc.setAttr(t+'.sz',lock=True)
					mc.setAttr(t+'.tx',lock=True)
					mc.setAttr(t+'.ty',lock=True)
					mc.setAttr(t+'.tz',lock=True)
					mc.setAttr(t+'.rx',lock=True)
					mc.setAttr(t+'.ry',lock=True)
					mc.setAttr(t+'.rz',lock=True)

					aimTr=mc.createNode('transform',p=t)
					mc.xform(aimTr,ws=True,t=antipodes[i])

					#mc.setAttr(db+'.p1',*self.ClosestPoints[i][0])
					#mc.setAttr(db+'.p2',*antipodes[i])
					axisLength=distanceBetween(self.ClosestPoints[i][0],antipodes[i])#mc.getAttr(db+'.d')

					ffd,lattice,latticeBase=mc.lattice(t,divisions=(2,2,2),objectCentered=True,ol=1)
					latticeLowEndPoints=mc.ls(lattice+'.pt[0:1][0:0][0:1]',fl=True)
					latticeHighEndPoints=mc.ls(lattice+'.pt[0:1][1:1][0:1]',fl=True)

					mc.parent(latticeBase,lattice)

					mc.setAttr(lattice+'.sy',axisLength)

					lattices.append([ffd,lattice,latticeBase])

					mc.parent(lattice,t)
					mc.xform(lattice,ws=True,a=True,t=mc.xform(r,q=True,ws=True,a=True,rp=True))
					mc.xform(lattice,os=True,a=True,ro=(0,0,0))
					mc.move(0,axisLength/2,0,lattice,r=True,os=True,wd=True)

					xSum,ySum,zSum=0,0,0
					for p in latticeLowEndPoints:
						px,py,pz=mc.pointPosition(p,w=True)
						xSum+=px
						ySum+=py
						zSum+=pz

					mc.xform(lattice,ws=True,piv=(xSum/len(latticeLowEndPoints),ySum/len(latticeLowEndPoints),zSum/len(latticeLowEndPoints)))
					mc.xform(latticeBase,ws=True,piv=(xSum/len(latticeLowEndPoints),ySum/len(latticeLowEndPoints),zSum/len(latticeLowEndPoints)))

					ac=mc.aimConstraint(aimTr,lattice,aim=(0,1,0),wut='objectrotation',wuo=r,u=(0,0,1),mo=False)
					mc.delete(ac)

					ac=mc.aimConstraint(aimTr,aimGroup,aim=(0,1,0),wut='objectrotation',wuo=r,u=(0,0,1),mo=False)
					mc.delete(ac,aimTr)

					lowEndCluster,lowEndClusterHandle=mc.cluster(latticeLowEndPoints)[:2]
					highEndCluster,highEndClusterHandle=mc.cluster(latticeHighEndPoints)[:2]

					lowEndClusterHandleShape=mc.listRelatives(lowEndClusterHandle,c=True)[0]
					highEndClusterHandleShape=mc.listRelatives(highEndClusterHandle,c=True)[0]

					#mc.parent(highEndClusterHandle,t)

					if mc.isConnected(lowEndClusterHandleShape+'.clusterTransforms[0]',lowEndCluster+'.clusterXforms'):
						mc.disconnectAttr(lowEndClusterHandleShape+'.clusterTransforms[0]',lowEndCluster+'.clusterXforms')
					if mc.isConnected(highEndClusterHandleShape+'.clusterTransforms[0]',highEndCluster+'.clusterXforms'):
						mc.disconnectAttr(highEndClusterHandleShape+'.clusterTransforms[0]',highEndCluster+'.clusterXforms')

					self.autoFlexGroups.append\
					(
						(
							mc.createNode('transform',n='rivetBaseAutoFlex#',p=r),
							mc.createNode('transform',n='rivetEndAutoFlex#',p=aimGroup)
						)
					)

					self.handles.append\
					(
						(
							mc.createNode('transform',n='rivetBaseCtrl#',p=self.autoFlexGroups[i][0]),
							mc.createNode('transform',n='rivetEndCtrl#',p=self.autoFlexGroups[i][1])
						)
					)

					self.handleShapes.append\
					(
						(
							mc.createNode('locator',p=self.handles[i][0]),
							mc.createNode('locator',p=self.handles[i][1])
						)
					)

					mc.setAttr(self.handleShapes[i][0]+'.los',.5,.5,.5)
					mc.setAttr(self.handleShapes[i][1]+'.los',.5,.5,.5)

					mc.xform(self.autoFlexGroups[i][0],ws=True,a=True,t=mc.xform(t,q=True,ws=True,rp=True))
					mc.xform(self.autoFlexGroups[i][0],ws=True,a=True,piv=mc.xform(t,q=True,ws=True,rp=True))

					for bp in self.bindPoses: mc.dagPose((self.handles[i][0],self.handles[i][1]),a=True,n=bp)

					mc.xform(self.autoFlexGroups[i][1],ws=True,t=antipodes[i])

					mc.hide(lattice)

					mc.connectAttr(self.handles[i][0]+'.worldInverseMatrix[0]',lowEndCluster+'.bindPreMatrix',f=True)
					mc.disconnectAttr(self.handles[i][0]+'.worldInverseMatrix[0]',lowEndCluster+'.bindPreMatrix')

					mc.connectAttr(self.handles[i][0]+'.worldMatrix[0]',lowEndCluster+'.matrix',f=True)

					mc.connectAttr(self.handles[i][1]+'.worldInverseMatrix[0]',highEndCluster+'.bindPreMatrix',f=True)
					mc.disconnectAttr(self.handles[i][1]+'.worldInverseMatrix[0]',highEndCluster+'.bindPreMatrix')

					mc.connectAttr(self.handles[i][1]+'.worldMatrix[0]',highEndCluster+'.matrix',f=True)

					aimGroups.append(aimGroup)

					if self.distribute=='u':
						mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][0]+'.sy')
					else:
						mc.connectAttr(clampNode+'.opg',self.autoFlexGroups[i][0]+'.sz')

					mc.delete([lowEndClusterHandle,highEndClusterHandle])

				self.rivets.append(r)

		if self.createAimCurve and self.parent:

			pmm=mc.createNode('pointMatrixMult')
			arcPoints=[]
			ids=[0,centerMostRivetIDs[0],centerMostRivetIDs[1],-1]

			for id in ids:

				measureTr=mc.createNode('transform')
				aimTr=mc.createNode('transform',p=self.trs[id])
				mc.parent(measureTr,self.trs[id])

				mc.xform(aimTr,ws=True,t=antipodes[id])
				mc.xform(measureTr,ws=True,t=mc.xform(self.rivets[id],q=True,ws=True,a=True,rp=True))
				#mc.xform(measureTr,os=True,a=True,ro=(0,0,0),s=(1,1,1))

				ac=mc.aimConstraint(aimTr,measureTr,aim=(0,1,0),wut='objectrotation',wuo=self.rivets[id],u=(0,0,1),mo=False)
				mc.delete(ac,aimTr)

				mc.connectAttr(measureTr+'.worldInverseMatrix',pmm+'.inMatrix',f=True)

				maxYID=-1
				maxY=0.0
				yVal=0.0

				for i in range(0,self.number):

					mc.setAttr(pmm+'.ip',*antipodes[i])
					yVal=mc.getAttr(pmm+'.oy')
					if yVal>maxY:
						maxY=yVal
						maxYID=i

				mc.setAttr(pmm+'.ip',*antipodes[maxYID])

				oy=mc.getAttr(pmm+'.oy')

				mc.setAttr(pmm+'.ip',*antipodes[id])

				ox=mc.getAttr(pmm+'.ox')
				oz=mc.getAttr(pmm+'.oz')

				mc.connectAttr(measureTr+'.worldMatrix',pmm+'.inMatrix',f=True)
				mc.setAttr(pmm+'.ip',ox,oy,oz)

				ap=mc.getAttr(pmm+'.o')[0]

				arcPoints.append(ap)

				mc.disconnectAttr(measureTr+'.worldMatrix',pmm+'.inMatrix')

				mc.delete(measureTr)

			mc.delete(pmm)

			arcCtrlArg=arcPoints
			arcCtrlKeys={'arcWeight':self.arcWeight,'p':self.parents,'sp':self.softParents}

			for k in arcCtrlKeys:
				if type(arcCtrlKeys[k]).__name__=='NoneType':
					del(arcCtrlKeys[k])

			self.ArcCtrl=ArcCtrl(*arcCtrlArg,**arcCtrlKeys)

			mc.addAttr(self.ArcCtrl[0],at='bool',ln='showHandles',k=True,dv=False)
			mc.setAttr(self.ArcCtrl[0]+'.showHandles',k=False,cb=True)
			mc.setAttr(self.ArcCtrl[0]+'.v',k=False,cb=True)
			mc.setAttr(self.ArcCtrl[1]+'.v',k=False,cb=True)

			for h in self.handles:
				mc.connectAttr(self.ArcCtrl[0]+'.showHandles',h[0]+'.v')
				mc.connectAttr(self.ArcCtrl[0]+'.showHandles',h[1]+'.v')

			for bp in self.bindPoses: mc.dagPose(self.ArcCtrl,a=True,n=bp)

			cpoc=mc.createNode('closestPointOnCurve')
			mc.connectAttr(self.ArcCtrl.outputCurve,cpoc+'.inCurve')

			for i in range(0,self.number):

				aimTr=mc.createNode('transform')
				poci=mc.createNode('pointOnCurveInfo')
				dm=mc.createNode('decomposeMatrix')
				fbfm=mc.createNode('fourByFourMatrix')

				mc.connectAttr(poci+'.nnx',fbfm+'.in00')
				mc.connectAttr(poci+'.nny',fbfm+'.in01')
				mc.connectAttr(poci+'.nnz',fbfm+'.in02')
				mc.connectAttr(poci+'.ntx',fbfm+'.in10')
				mc.connectAttr(poci+'.nty',fbfm+'.in11')
				mc.connectAttr(poci+'.ntz',fbfm+'.in12')

				mc.connectAttr(self.ArcCtrl.outputNormal+'X',fbfm+'.in20')
				mc.connectAttr(self.ArcCtrl.outputNormal+'Y',fbfm+'.in21')
				mc.connectAttr(self.ArcCtrl.outputNormal+'Z',fbfm+'.in22')

				mc.connectAttr(poci+'.px',fbfm+'.in30')
				mc.connectAttr(poci+'.py',fbfm+'.in31')
				mc.connectAttr(poci+'.pz',fbfm+'.in32')

				mc.connectAttr(fbfm+'.output',dm+'.inputMatrix')
				mc.connectAttr(dm+'.outputTranslate',aimTr+'.t')
				mc.connectAttr(dm+'.outputRotate',aimTr+'.r')

				mc.setAttr(cpoc+'.ip',*antipodes[i])
				cpu=mc.getAttr(cpoc+'.u')
				mc.setAttr(poci+'.parameter',cpu)

				mc.connectAttr(self.ArcCtrl.outputCurve,poci+'.inputCurve')

				ac=mc.aimConstraint(aimTr,self.aimGroups[i],aim=(0,1,0),wut='objectrotation',wuo=aimTr,u=(0,0,1),mo=not(self.realign))[0]

				disconnectNodes(aimTr,ac)

				mc.connectAttr(fbfm+'.output',ac+'.worldUpMatrix',f=True)
				mc.connectAttr(dm+'.ot',ac+'.target[0].targetTranslate',f=True)

				mc.delete(aimTr)

				sc=mc.createNode('subCurve')

				mc.setAttr(sc+'.relative',True)
				mc.setAttr(sc+'.minValue',0)
				mc.setAttr(sc+'.maxValue',1)

				mc.connectAttr(self.ArcCtrl.outputCurve,sc+'.ic')

				if self.distribute=='u':
					uMultAttr=uvMultipliers[i][0]+".o"
				else:
					uMultAttr=uvMultipliers[i][1]+".o"

				#adjust for offset

				multOffsetCalc=mc.createNode('multDoubleLinear')
				mc.setAttr(multOffsetCalc+'.i1',1/mc.getAttr(uMultAttr))
				mc.connectAttr(uMultAttr,multOffsetCalc+'.i2')

				multOffset=mc.createNode('multDoubleLinear')
				mc.setAttr(multOffset+'.i1',cpu)
				mc.connectAttr(multOffsetCalc+'.o',multOffset+'.i2')

				mc.connectAttr(multOffset+'.o',poci+'.parameter',f=True)

				subtractNode=mc.createNode('addDoubleLinear')
				mc.setAttr(subtractNode+'.i1',-(1.0/(self.number*2)))
				addNode=mc.createNode('addDoubleLinear')
				mc.setAttr(addNode+'.i1',1.0/(self.number*2))
				addSubClampNode=mc.createNode('clamp')
				mc.setAttr(addSubClampNode+'.min',0,0,0)
				mc.setAttr(addSubClampNode+'.max',1,1,1)
				mc.connectAttr(subtractNode+'.o',addSubClampNode+'.inputR')
				mc.connectAttr(addNode+'.o',addSubClampNode+'.inputG')

				mc.connectAttr(multOffset+".o",subtractNode+".i2")
				mc.connectAttr(multOffset+".o",addNode+".i2")
				mc.connectAttr(addSubClampNode+'.outputR',sc+'.minValue')
				mc.connectAttr(addSubClampNode+'.outputG',sc+'.maxValue')

				ciU=mc.createNode('curveInfo')
				mc.connectAttr(sc+'.outputCurve',ciU+'.inputCurve')

				mdlU=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciU+'.al',mdlU+'.i1')
				mc.setAttr(mdlU+'.i2',1/float(mc.getAttr(ciU+'.al')))

				clampNode=mc.createNode('clamp')

				if not mc.objExists(c+'.minScaleEnd'): mc.addAttr(self.ctrls[i],ln='minScaleEnd',at='double',k=True,min=0,max=1,dv=0)
				if not mc.objExists(c+'.maxScaleEnd'): mc.addAttr(self.ctrls[i],ln='maxScaleEnd',at='double',k=True,min=0,dv=1)

				mc.connectAttr(self.ctrls[i]+'.minScaleEnd',clampNode+'.minR')
				mc.connectAttr(self.ctrls[i]+'.maxScaleEnd',clampNode+'.maxR')

				mc.connectAttr(mdlU+'.o',clampNode+'.ipr')

				if self.distribute=='u':
					mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][1]+'.sz')
				else:
					mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][1]+'.sy')

			mc.delete(cpoc)

		if self.parent:
			self[:]=self.rivets
		else:
			self[:]=self.trs
		#if self.mo:
		#	#for i in len(self.trs):
		#		#try: mc.xform(t,q=True,ws=True,m=wsMatrices[i]))
		#		#except: pass

		cleanup.append(cpos)

		for c in cleanup:
			if mc.objExists(c):
				disconnectNodes(c)
				mc.delete(c)

		if self.snapToSurface:
			if self.createAimCurve or self.taper:
				for i in range(0,self.number):
					mc.xform(self.handles[i][0],ws=True,t=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
					mc.xform(self.trs[i],ws=True,rp=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
			else:
				for i in range(0,self.number):
					mc.xform(self.trs[i],ws=True,t=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
					mc.xform(self.trs[i],ws=True,ro=mc.xform(self.rivets[i],q=True,ws=True,ro=True))
예제 #30
0
import maya.cmds as cmds

sels = cmds.ls(sl=1)

source = sels[0]
targets = sels[1:]

hists = cmds.listHistory(source, pdo=1)
hists.reverse()

for hist in hists:
    print hist, cmds.nodeType(hist)
    if cmds.nodeType(hist) == 'nonLinear':
        for target in targets:
            cmds.nonLinear(hist, e=1, geometry=target)
    elif cmds.nodeType(hist) == 'wire':
        for target in targets:
            cmds.wire(hist, e=1, geometry=target)
    elif cmds.nodeType(hist) == 'ffd':
        for target in targets:
            cmds.lattice(hist, e=1, geometry=target)
import maya.cmds as cmds

sels = cmds.ls( sl=1 )

source = sels[0]
targets = sels[1:]

hists = cmds.listHistory( source, pdo=1 )
hists.reverse()

for hist in hists:
    print hist, cmds.nodeType( hist )
    if cmds.nodeType( hist ) == 'nonLinear':
        for target in targets:
            cmds.nonLinear( hist, e=1, geometry=target )
    elif cmds.nodeType( hist ) == 'wire':
        for target in targets:
            cmds.wire( hist, e=1, geometry=target )
    elif cmds.nodeType( hist ) == 'ffd':
        for target in targets:
            cmds.lattice( hist, e=1, geometry=target )
예제 #32
0
                pos=(0, 0, 0),
                att=0.0,
                f=1,
                mxd=0,
                nsl=8)
x = 1
lat = 1

for i in range(109):
    cmds.select('grass_grass' + str(i))  #select object
    cmds.polyUnite(muv=1, n='grass' + str(i))  #Combine and rename
    cmds.delete(ch=True)
    cmds.select('grass' + str(i))  #slect new shape

    ################################ Create FX ###########################
    cmds.lattice(dv=(7, 7, 7), oc=True)
    cmds.select("ffd" + str(x) + "Lattice")
    cmds.duplicate(n="ffd" + str(x) + "Lattice_goal")
    cmds.select("ffd" + str(x) + "Base")
    cmds.duplicate(n="ffd" + str(x) + "Base_goal")

    cmds.select("ffd" + str(x) + "Lattice")
    cmds.soft("ffd" + str(x) + "Lattice", c=True)
    cmds.goal("ffd" + str(x) + "LatticeParticle",
              g="ffd" + str(x) + "Lattice_goal",
              w=0.5)
    cmds.connectDynamic("ffd" + str(x) + "LatticeParticle", f='Grass_wind_FX')
    cmds.select('grass' + str(i), "ffd" + str(x) + "Lattice",
                "ffd" + str(x) + "Base", "ffd" + str(x) + "Lattice_goal",
                "ffd" + str(x) + "Base1", "ffd" + str(x) + "Base_goal")
    cmds.group(n='Dynamic_grass' + str(i))
예제 #33
0
def latt(*args):
	cmds.lattice(divisions=[2,2,2], objectCentered=True, ldv=[2,2,2])
예제 #34
0
def main(*args):
    mmSelectedInScene = cmds.ls(sl = 1)

    mmOverallBoundingBoxList = cmds.exactWorldBoundingBox( )
    print "mmOverallBoundingBoxList", mmOverallBoundingBoxList

    mmOverallXMin = mmOverallBoundingBoxList[0]
    mmOverallYMin = mmOverallBoundingBoxList[1]
    mmOverallZMin = mmOverallBoundingBoxList[2]
    mmOverallXMax = mmOverallBoundingBoxList[3]
    mmOverallYMax = mmOverallBoundingBoxList[4]
    mmOverallZMax = mmOverallBoundingBoxList[5]

    #Find size user wants
    #Find total size
    mmOverallXTotal = abs(mmOverallXMax - mmOverallXMin)
    mmOverallYTotal = abs(mmOverallYMax - mmOverallYMin)
    mmOverallZTotal = abs(mmOverallZMax - mmOverallZMin)
    '''
    print "mmBoundingBoxList[5]", mmBoundingBoxList[5]
    print "mmOverallZMax", mmOverallZMax
    print "mmOverallZMin", mmOverallZMin
    print "mmOverallZTotal", mmOverallZTotal
    '''

    #Find halfway point (i.e. center of object)
    mmOverallXMidPoint = mmOverallXMax - mmOverallXTotal/2
    mmOverallYMidPoint = mmOverallYMax - mmOverallYTotal/2
    mmOverallZMidPoint = mmOverallZMax - mmOverallZTotal/2
    '''
    print "mmOverallZMidPoint", mmOverallZMidPoint
    '''

    for mmItem in mmSelectedInScene:
        
        cmds.select(mmItem, r = 1)
        
        mmScaleGrowValueOverall = 0.01
        mmScaleRateOfShrink = 1.05 #Must be higher than 1
        mmCheckerValue = 5
        mmLatticeSize = 10
        
        mmNewLattice = cmds.lattice(  divisions = (mmLatticeSize, mmLatticeSize, mmLatticeSize), objectCentered = True, ldv = ( 2, 2, 2) )

        mmLatticeMax = mmLatticeSize

        mmLatticeHigh = mmLatticeMax-1
        mmLatticeLow = 0

        
        
        mmBoundingBoxList = cmds.exactWorldBoundingBox( )
        #print "mmBoundingBoxList", mmBoundingBoxList

        mmXMin = mmBoundingBoxList[0]
        mmYMin = mmBoundingBoxList[1]
        mmZMin = mmBoundingBoxList[2]
        mmXMax = mmBoundingBoxList[3]
        mmYMax = mmBoundingBoxList[4]
        mmZMax = mmBoundingBoxList[5]

        #Find size user wants
        #Find total size
        mmXTotal = abs(mmXMax - mmXMin)
        mmYTotal = abs(mmYMax - mmYMin)
        mmZTotal = abs(mmZMax - mmZMin)

        #Find halfway point (i.e. center of object)
        mmXMidPoint = mmXMax - mmXTotal/2
        mmYMidPoint = mmYMax - mmYTotal/2
        mmZMidPoint = mmZMax - mmZTotal/2
        
        #print "mmNewLattice[1]", mmNewLattice[1]

        #mmPivot = [ mmXMidPoint, mmYMidPoint, mmZMidPoint ]
        mmCheckFunction = mmOverallZMidPoint - mmZMidPoint
        #print "mmCheckFunction", mmCheckFunction
        #print "mmOverallZMidPoint", mmOverallZMidPoint
        #print "mmZMidPoint", mmZMidPoint
        

        #Modify the pivot point based on various information
        mmXFinalValue = mmXMidPoint
        mmYFinalValue = mmYMidPoint
        mmZFinalValue = mmZMidPoint

        #if the bounding box Ymin of the current selection equates to the bounding box Ymin of the all selections
        if ( mmYMin == mmOverallYMin ):
            
            mmYFinalValue = mmYMin
        
        #if the mmCheckFunction is greater than the mmCheckerValue, than move the pivot to the mmZMax
        if ( mmCheckFunction > mmCheckerValue ):
            
            mmZFinalValue = mmZMax
            
        #if the mmCheckFunction is less than the mmCheckerValue, than move the pivot to the mmZMin
        elif ( mmCheckFunction < mmCheckerValue  ):

            mmZFinalValue = mmZMin
            



        #Setting final values
        mmPivot = [ mmXFinalValue, mmYFinalValue, mmZFinalValue ]        
        
        mmListX = [1]
        mmListY = [0]
        mmListZ = [0]
        
        #print mmListX
        
        #Pass 1 - in X
        mmScaleGrowValue = mmScaleGrowValueOverall
        mmLatticeLow = mmLatticeMax/2-1
        mmLatticeHigh = mmLatticeMax/2
        
        mmScaleGrowValue = mmScaleGrowValueOverall
        
        while ( mmLatticeLow != 0 ):
            #cmds.select( mmNewLattice[1] + ".pt" + str(mmListX) + str(mmListY) + str(mmListZ), r = 1 )
            #print mmNewLattice[1] + ".pt[" + str(mmLatticeLow) +" : " + str(mmLatticeHigh) + "][0:" + str(mmLatticeMax) + "][0:" + str(mmLatticeMax) + "]"
            
            cmds.select( mmNewLattice[1] + ".pt[" + str(mmLatticeLow) +" : " + str(mmLatticeHigh) + "][0:" + str(mmLatticeMax) + "][0:" + str(mmLatticeMax) + "]", r = 1 )
            
            cmds.scale( 1, 1 + mmScaleGrowValue, 1 + mmScaleGrowValue, pivot = mmPivot )
            mmScaleGrowValue = mmScaleGrowValue*mmScaleRateOfShrink
            mmLatticeHigh += 1
            mmLatticeLow -= 1


        #Pass 2new - in Y
        
        #Reset Values        
        mmScaleGrowValue = mmScaleGrowValueOverall
        mmLatticeLow = mmLatticeMax/2-1
        mmLatticeHigh = mmLatticeMax/2
        
        while ( mmLatticeLow != 0 ):
            #cmds.select( mmNewLattice[1] + ".pt" + str(mmListX) + str(mmListY) + str(mmListZ), r = 1 )
            
            cmds.select( mmNewLattice[1] + ".pt[0:" + str(mmLatticeMax) + "][" + str(mmLatticeLow) +" : " + str(mmLatticeHigh) + "][0:" + str(mmLatticeMax) + "]", r = 1 )
            
            cmds.scale( 1 + mmScaleGrowValue, 1, 1+ mmScaleGrowValue, pivot = mmPivot )
            mmScaleGrowValue = mmScaleGrowValue*mmScaleRateOfShrink
            mmLatticeHigh += 1
            mmLatticeLow -= 1


        #Pass 3new - in Z
        
        #Reset Values        
        mmScaleGrowValue = mmScaleGrowValueOverall
        mmLatticeLow = mmLatticeMax/2-1
        mmLatticeHigh = mmLatticeMax/2

        while ( mmLatticeLow != 0 ):
            #cmds.select( mmNewLattice[1] + ".pt" + str(mmListX) + str(mmListY) + str(mmListZ), r = 1 )
            
            cmds.select( mmNewLattice[1] + ".pt[0:" + str(mmLatticeMax) + "][0:" + str(mmLatticeMax) + "][" + str(mmLatticeLow) +" : " + str(mmLatticeHigh) + "]", r = 1 )
            
            cmds.scale( 1 + mmScaleGrowValue, 1+ mmScaleGrowValue, 1, pivot = mmPivot )
            mmScaleGrowValue = mmScaleGrowValue*mmScaleRateOfShrink
            mmLatticeHigh += 1
            mmLatticeLow -= 1



        cmds.select(mmNewLattice, r = 1)
        
        cmds.HideSelectedObjects()
예제 #35
0
파일: deformer.py 프로젝트: jonntd/Public
 def lattice(self,
              character = None,
              mod = None,
              side = None,
              name = None,
              suffix = None,
              geometry = None,
              position = [0,0,0],
              rotation = [0,0,0],
              envelope = 1,
              divisions = [2,5,2],
              objectCentered = True,
              localInfluences = [2,2,2],
              outsideLattice = 'inside',
              outsideFalloffDist = 1,
              resolution = 'full',
              partialResolution = 0.01,
              freezeGeometry = False,
              parent = None,
              show = True,
              lockAttr = None,
              ihi = True):
     #--- this method creates a lattice deformer
     #--- select the specified geometry
     cmds.select(geometry)
     #--- create a lattice deformer
     node = cmds.lattice(divisions = divisions,
                         objectCentered = objectCentered,
                         ldivisions = localInfluences)
     #--- filter the name
     filter_lat = name + 'Lattice' + node[0].split('ffd')[-1]
     filter_bas = name + 'Base' + node[0].split('ffd')[-1]
     #--- create a group on top and parent the deformer under the group
     node_grp = cmds.createNode('transform')
     #--- rename the node group
     node_grp = self.__rename_node(mod = mod,
                                   side = side,
                                   name = filter_lat,
                                   suffix = 'GRP',
                                   obj = node_grp)
     #--- rename the lattice deformer
     lat = self.__rename_node(mod = mod,
                              side = side,
                              name = filter_lat,
                              suffix = suffix,
                              obj = node)
     #--- rename the base deformer
     base = self.__rename_node(mod = mod,
                               side = side,
                               name = filter_bas,
                               suffix = suffix,
                               obj = node[-1])
     cmds.parent(node_grp, lat[0])
     cmds.parent(node_grp, world = True)
     cmds.parent(lat[0], base[0], node_grp)
     node = lat
     #--- reposition the transform of the deformer locally
     cmds.xform(node_grp, translation = position, worldSpace = False)
     cmds.xform(node_grp, rotation = rotation, worldSpace = False)
     #--- take care of the node's settings
     #--- envelope
     cmds.setAttr(node[-1] + '.envelope', envelope)
     #--- outsideLattice
     if outsideLattice == 'inside':
         cmds.setAttr(node[-1] + '.outsideLattice', 0)
     elif outsideLattice == 'all':
         cmds.setAttr(node[-1] + '.outsideLattice', 1)
     elif outsideLattice == 'falloff':
         cmds.setAttr(node[-1] + '.outsideLattice', 2)
     #--- outsideFalloffDist
     if outsideLattice == 'falloff':
         cmds.setAttr(node[-1] + '.outsideFalloffDist', outsideFalloffDist)
     #--- resolution
     if resolution == 'full':
         cmds.setAttr(node[-1] + '.usePartialResolution', 0)
     elif resolution == 'partial':
         cmds.setAttr(node[-1] + '.usePartialResolution', 1)
     #--- partialResolution
     if resolution == 'partial':
         cmds.setAttr(node[-1] + '.partialResolution', partialResolution)
     #--- freezeGeometry
     cmds.setAttr(node[-1] + '.freezeGeometry', freezeGeometry)
     #--- parent the group under the specified parent
     if parent:
         if not isinstance(parent, list):
             cmds.parent(node_grp, parent)
         else:
             raise Exception("Specified parent: " + parent + 'is not a valid')
     #--- show or hide transform
     if not show:
         cmds.setAttr(node_grp + '.v', 0)
     #--- lock specified attributes
     if lockAttr:
         if node[-1]:
             cmds.setAttr(node[-1] + '.' + lockAttr, lock = True)
     #--- set isHistoricalInteresting attribute
     if not ihi:
         for n in node:
             cmds.setAttr(n + '.ihi', 0)
         for b in base:
             cmds.setAttr(b + '.ihi', 0)
     node.insert(-1, base[0])
     #--- return node
     return node
예제 #36
0
 def lattice(self,
             character=None,
             mod=None,
             side=None,
             name=None,
             suffix=None,
             geometry=None,
             position=[0, 0, 0],
             rotation=[0, 0, 0],
             envelope=1,
             divisions=[2, 5, 2],
             objectCentered=True,
             localInfluences=[2, 2, 2],
             outsideLattice='inside',
             outsideFalloffDist=1,
             resolution='full',
             partialResolution=0.01,
             freezeGeometry=False,
             parent=None,
             show=True,
             lockAttr=None,
             ihi=True):
     #--- this method creates a lattice deformer
     #--- select the specified geometry
     cmds.select(geometry)
     #--- create a lattice deformer
     node = cmds.lattice(divisions=divisions,
                         objectCentered=objectCentered,
                         ldivisions=localInfluences)
     #--- filter the name
     filter_lat = name + 'Lattice' + node[0].split('ffd')[-1]
     filter_bas = name + 'Base' + node[0].split('ffd')[-1]
     #--- create a group on top and parent the deformer under the group
     node_grp = cmds.createNode('transform')
     #--- rename the node group
     node_grp = self.__rename_node(mod=mod,
                                   side=side,
                                   name=filter_lat,
                                   suffix='GRP',
                                   obj=node_grp)
     #--- rename the lattice deformer
     lat = self.__rename_node(mod=mod,
                              side=side,
                              name=filter_lat,
                              suffix=suffix,
                              obj=node)
     #--- rename the base deformer
     base = self.__rename_node(mod=mod,
                               side=side,
                               name=filter_bas,
                               suffix=suffix,
                               obj=node[-1])
     cmds.parent(node_grp, lat[0])
     cmds.parent(node_grp, world=True)
     cmds.parent(lat[0], base[0], node_grp)
     node = lat
     #--- reposition the transform of the deformer locally
     cmds.xform(node_grp, translation=position, worldSpace=False)
     cmds.xform(node_grp, rotation=rotation, worldSpace=False)
     #--- take care of the node's settings
     #--- envelope
     cmds.setAttr(node[-1] + '.envelope', envelope)
     #--- outsideLattice
     if outsideLattice == 'inside':
         cmds.setAttr(node[-1] + '.outsideLattice', 0)
     elif outsideLattice == 'all':
         cmds.setAttr(node[-1] + '.outsideLattice', 1)
     elif outsideLattice == 'falloff':
         cmds.setAttr(node[-1] + '.outsideLattice', 2)
     #--- outsideFalloffDist
     if outsideLattice == 'falloff':
         cmds.setAttr(node[-1] + '.outsideFalloffDist', outsideFalloffDist)
     #--- resolution
     if resolution == 'full':
         cmds.setAttr(node[-1] + '.usePartialResolution', 0)
     elif resolution == 'partial':
         cmds.setAttr(node[-1] + '.usePartialResolution', 1)
     #--- partialResolution
     if resolution == 'partial':
         cmds.setAttr(node[-1] + '.partialResolution', partialResolution)
     #--- freezeGeometry
     cmds.setAttr(node[-1] + '.freezeGeometry', freezeGeometry)
     #--- parent the group under the specified parent
     if parent:
         if not isinstance(parent, list):
             cmds.parent(node_grp, parent)
         else:
             raise Exception("Specified parent: " + parent +
                             'is not a valid')
     #--- show or hide transform
     if not show:
         cmds.setAttr(node_grp + '.v', 0)
     #--- lock specified attributes
     if lockAttr:
         if node[-1]:
             cmds.setAttr(node[-1] + '.' + lockAttr, lock=True)
     #--- set isHistoricalInteresting attribute
     if not ihi:
         for n in node:
             cmds.setAttr(n + '.ihi', 0)
         for b in base:
             cmds.setAttr(b + '.ihi', 0)
     node.insert(-1, base[0])
     #--- return node
     return node
예제 #37
0
def build( side = None, jntFoot = None, ctrlFoot = None, ikHandleLeg = None, mesh = None, stretchLoc = None, cleanUp = 0 ):
	'''
	builds a reverse foot!
	creates roll pivots, adds attributes to foot control and sets up the contact lattice.
	
	function requires the side, foot joint (in richards limb module the extra_jnt),
	foot control and ik handle to be supplied.
	The character's mesh is needed for contact lattice deformer and will be used for getting
	the pivot locations from a set of specific vertices.
	
	DO NOT FORGET: If the rig is build before there is a skincluster attached to the mesh
	you will need to reorder the deformers.
	
	returns a dictionary containing corresponding objects for these keys: 
	joints, pivots, ikHandles, lattice, systemsGrp, ctrls
	'''
	
		
	# abort if not all arguments were supplied
	if not jntFoot or not ctrlFoot or not ikHandleLeg or not mesh or not stretchLoc:
		return cmds.warning( 'Argument Error: Please supply all arguments (side, joint_footExtraEnd, control, ikHandle, mesh).' )
	
	
	# vertex indices for left / right
	pivotVertsLeft = [196, 199, 29, 28]
	latticeVertIdsLeft = ['0:1', '8:9', '28:29', '39:42', '47:48', '51:52', '55:58', '63:64', '67:70', '196', '199', '206:207', '211:212', '241:242', '253', '264:265', '268:273', '278:279', '282:285', '290:291', '294:297', '302:303', '409', '414', '418', '434', '437:438', '447:448']
	pivotVertsRight = [219, 230, 36, 35]
	latticeVertIdsRight = ['14:15', '24:25', '35:36', '43:46', '49:50', '53:54', '59:62', '65:66', '71:74', '219', '230:232', '237:238', '248:249', '258', '261:262', '266:267', '274:277', '280:281', '286:289', '292:293', '298:301', '304:305', '424:426', '430:431', '441:443']
	
	# set side relevant data, abort if no side specified
	if side in ['lf', 'left', 'lft']:
		pivotVerts = pivotVertsLeft
		latticeVertIds = latticeVertIdsLeft
		sideColor = 'blue'

	elif side in ['rt', 'right', 'rgt']:
		pivotVerts = pivotVertsRight
		latticeVertIds = latticeVertIdsRight
		sideColor = 'red'
	
	else:
		return cmds.warning( 'No valid side specified' )
	
	
	# create output dictionary
	outDict = {}
	
	
	# add attributes to foot control, if attribute already exists skip it
	attrs = ['roll', 'rollBreak', 'side', 'toeTap', 'toeRaise', 'toeTwist', 'heelTwist', 'squashGroundContact']
	for attr in attrs:
		if ( cmds.attributeQuery( attr, node=ctrlFoot, exists=True ) ) == True:
			print( 'Attribute %s already exists on %s.' % ( attr, ctrlFoot ) )
		else:
			cmds.addAttr( ctrlFoot, longName=attr, attributeType='float', keyable = True )
			
	
	useDefaultPivots = False
	
	# create pivot locators
	if useDefaultPivots == True:
	
		# set default pivot positions
		pivotOffset = 0.5
		jntFootPos = cmds.xform( jntFoot, q = True, translation = True, ws = True )
		pivotFrontPos = [ jntFootPos[0], jntFootPos[1], jntFootPos[2] + pivotOffset ]
		pivotRearPos = [ jntFootPos[0], jntFootPos[1], jntFootPos[2] - pivotOffset ]
		pivotLeftPos = [ jntFootPos[0] + pivotOffset, jntFootPos[1], jntFootPos[2] ]
		pivotRightPos = [ jntFootPos[0] - pivotOffset, jntFootPos[1], jntFootPos[2] ]
	
	else:
	
		# get pivot positions from vertices
		pivotFrontPos = cmds.xform( mesh + '.vtx[%s]' % pivotVerts[0], q = True, ws = True, t = True )
		pivotRearPos = cmds.xform( mesh + '.vtx[%s]' % pivotVerts[1], q = True, ws = True, t = True )
		pivotLeftPos = cmds.xform( mesh + '.vtx[%s]' % pivotVerts[2], q = True, ws = True, t = True )
		pivotRightPos = cmds.xform( mesh + '.vtx[%s]' % pivotVerts[3], q = True, ws = True, t = True )
	
	pivotFront = cmds.spaceLocator()[0]
	pivotFront = cmds.rename( pivotFront, common.getName( node=pivotFront, side=side, rigPart='foot', function='front_piv', nodeType='loc') )
	cmds.xform( translation = pivotFrontPos )
	
	pivotRear = cmds.spaceLocator()[0]
	pivotRear = cmds.rename( pivotRear, common.getName( node=pivotRear, side=side, rigPart='foot', function='rear_piv', nodeType='loc') )
	cmds.xform( translation = pivotRearPos )
	
	pivotLeft = cmds.spaceLocator()[0]
	pivotLeft = cmds.rename( pivotLeft, common.getName( node=pivotLeft, side=side, rigPart='foot', function='left_piv', nodeType='loc') )
	cmds.xform( translation = pivotLeftPos )
	
	pivotRight = cmds.spaceLocator()[0]
	pivotRight = cmds.rename( pivotRight, common.getName( node=pivotRight, side=side, rigPart='foot', function='right_piv', nodeType='loc') )
	cmds.xform( translation = pivotRightPos )
	
	cmds.parent( pivotFront, pivotRear )
	cmds.parent( pivotRear, pivotLeft )
	cmds.parent( pivotLeft, pivotRight )
	
	pivotLocs = [pivotFront, pivotRear, pivotLeft, pivotRight]
	for pivotLoc in pivotLocs: cmds.setAttr( cmds.listRelatives( pivotLoc )[0] + '.localScale', .1, .1, .1 ) # reduce local scale
	
	#outDict['pivots'] = pivotLocs | done after creating ball locator
	
	
	# create ball and toe joint
	cmds.select( clear = True )
	
	jntAnkle = cmds.joint()
	jntAnkle = cmds.rename(jntAnkle, common.getName( node=jntAnkle, side=side, rigPart='ankle', function='driven', nodeType='jnt'))
	cmds.xform( jntAnkle, ws = True, translation = ( cmds.xform( ikHandleLeg, q = True, t = True, ws = True ) ) )
	cmds.setAttr( jntAnkle + '.radius', .75 * cmds.getAttr( jntFoot + '.radius' ) )	
	
	jntBall = cmds.joint()
	jntBall = cmds.rename(jntBall, common.getName( node=jntBall, side=side, rigPart='ball', function='driven', nodeType='jnt'))
	cmds.xform( jntBall, ws = True, t = ( cmds.xform( jntFoot, q = True, ws = True, t = True ) ) )
	cmds.xform( jntBall, ws = True, relative = True, t = ( 0, 0, .5 * cmds.xform( pivotFront, q = True, t = True, ws = True )[2] ) )
	cmds.setAttr( jntBall + '.radius', .75 * cmds.getAttr( jntFoot + '.radius' ) )
	
	jntToe = cmds.joint()
	jntToe = cmds.rename(jntToe, common.getName( node=jntToe, side=side, rigPart='toe', function='driven', nodeType='jnt'))
	cmds.xform( jntToe, t = ( 0, 0, .5 * cmds.xform( pivotFront, q = True, t = True, ws = True )[2] ), relative = True, ws = True )
	cmds.setAttr( jntToe + '.radius', cmds.getAttr( jntBall + '.radius' ) )
	
	grpBufJnt = cmds.group ( empty = True )
	grpBufJnt = cmds.rename( grpBufJnt, common.getName( node=grpBufJnt, side=side, rigPart='foot', function='jnt_buf', nodeType='grp' ) )
	common.align( grpBufJnt, jntFoot, translate = True, orient = False )
	cmds.parentConstraint( jntFoot, grpBufJnt, mo = False )
	cmds.parent( jntAnkle, grpBufJnt )
	
	grpJnts = cmds.group( empty = True )
	grpJnts = cmds.rename( grpJnts, common.getName( node=grpJnts, side=side, rigPart='foot', function='jnts', nodeType='grp' ) )
	common.align( grpJnts, ctrlFoot, translate = True, orient = False )
	cmds.parent( grpBufJnt, grpJnts )
	
	outDict['joints'] = [ jntAnkle, jntBall, jntToe ]
	
	
	# create toe IK handles
	ikHandleBall, ikEffectorBall = cmds.ikHandle( startJoint = jntAnkle, endEffector = jntBall, solver = 'ikSCsolver', name = '%s_ball_ikHandle' % side )
	ikHandleToe, ikEffectorToe = cmds.ikHandle( startJoint = jntBall, endEffector = jntToe, solver = 'ikSCsolver', name = '%s_toe_ikHandle' % side )
	cmds.parent( ikHandleBall, pivotRear )
	cmds.parent( ikHandleToe, pivotFront )
	
	outDict['ikHandles'] = [ ikHandleLeg, ikHandleBall, ikHandleToe ]
	
	
	# create ball pivot locator
	pivotBall = cmds.spaceLocator( name = common.getName( side=side, rigPart='foot', function='ball_piv', nodeType='loc') )[0]
	cmds.xform( pivotBall, ws = True, translation = cmds.xform( jntBall, q = True, ws = True, t = True ) )
	pivotBall = cmds.parent( pivotBall, pivotFront )[0]
	pivotLocs.insert( 0, pivotBall ) 
	
	outDict['pivots'] = pivotLocs
	
	
	# create simple clamps and connect roll, side attribute to pivot locators
	rollLimit = 180.0
	cmds.addAttr( ctrlFoot + '.side', edit = True, min = -1 * rollLimit, max = rollLimit )
	
	clampRollRear = cmds.shadingNode( 'clamp', asUtility = True )
	clampRollRear = cmds.rename( clampRollRear, common.getName( node=clampRollRear, side=side, rigPart='rear', function='roll', nodeType='clamp') )
	cmds.setAttr( clampRollRear + '.minR', -rollLimit )
	cmds.connectAttr( ctrlFoot + '.roll', clampRollRear + '.inputR' )
	cmds.connectAttr( clampRollRear + '.outputR', pivotRear + '.rotateX' )
	
	clampRollLeft = cmds.shadingNode( 'clamp', asUtility = True )
	clampRollLeft = cmds.rename( clampRollLeft, common.getName( node=clampRollLeft, side=side, rigPart='left', function='side', nodeType='clamp') )
	cmds.setAttr( clampRollLeft + '.minR', -rollLimit )
	cmds.connectAttr( ctrlFoot + '.side', clampRollLeft + '.inputR' )
	cmds.connectAttr( clampRollLeft + '.outputR', pivotLeft + '.rotateZ' )
	
	clampRollRight = cmds.shadingNode( 'clamp', asUtility = True )
	clampRollRight = cmds.rename( clampRollRight, common.getName( node=clampRollRight, side=side, rigPart='right', function='side', nodeType='clamp') )
	cmds.setAttr( clampRollRight + '.maxR', rollLimit )
	cmds.connectAttr( ctrlFoot + '.side', clampRollRight + '.inputR' )
	cmds.connectAttr( clampRollRight + '.outputR', pivotRight + '.rotateZ' )
	
	# setup foot roll
	cmds.setAttr( ctrlFoot + '.rollBreak', 30.0 )
	cmds.addAttr( ctrlFoot + '.rollBreak', edit = True, min = 0.0, max = rollLimit )
	cmds.addAttr( ctrlFoot + '.roll', edit = True, min = -rollLimit, max = rollLimit )

	clampRollBall = cmds.shadingNode( 'clamp', asUtility = True )
	clampRollBall = cmds.rename( clampRollBall, common.getName( node=clampRollBall, side=side, rigPart='ball', function='roll', nodeType='clamp') )
	cmds.connectAttr( ctrlFoot + '.rollBreak', clampRollBall + '.maxR' )
	cmds.connectAttr( ctrlFoot + '.roll', clampRollBall + '.inputR' )

	pmaRollBall = cmds.shadingNode( 'plusMinusAverage', asUtility = True )
	cmds.setAttr( pmaRollBall + '.operation', 2 )
	cmds.setAttr( pmaRollBall + '.input1D[0]', 180 )
	cmds.connectAttr( ctrlFoot + '.rollBreak', pmaRollBall + '.input1D[1]' )

	remapRollBall = cmds.shadingNode( 'remapValue', asUtility = True )
	cmds.setAttr( remapRollBall + '.outputMin', -1 )
	cmds.setAttr( remapRollBall + '.outputMax', 1 )
	cmds.setAttr( remapRollBall + '.value[0].value_Position', 0 )
	cmds.setAttr( remapRollBall + '.value[0].value_FloatValue', 1 )
	cmds.setAttr( remapRollBall + '.value[1].value_Position', 1 )
	cmds.setAttr( remapRollBall + '.value[1].value_FloatValue', 0 )
	cmds.connectAttr( ctrlFoot + '.rollBreak', remapRollBall + '.inputMin' )
	cmds.connectAttr( pmaRollBall + '.output1D', remapRollBall + '.inputMax' )

	multRollBall = cmds.shadingNode( 'multiplyDivide', asUtility = True )
	cmds.connectAttr( clampRollBall + '.outputR', multRollBall + '.input1X' )
	cmds.connectAttr( remapRollBall + '.outValue', multRollBall + '.input2X' )
	cmds.connectAttr( multRollBall + '.outputX', pivotBall + '.rotateX' )
			
	clampRollFront = cmds.shadingNode( 'clamp', asUtility = True )
	clampRollFront = cmds.rename( clampRollFront, common.getName( node=clampRollFront, side=side, rigPart='toe', function='roll', nodeType='clamp') )
	pmaRollFront = cmds.shadingNode( 'plusMinusAverage', asUtility = True )
	pmaRollFront = cmds.rename( pmaRollFront, common.getName( node=pmaRollFront, side=side, rigPart='toe', function='roll', nodeType='pma') )

	cmds.connectAttr( ctrlFoot + '.rollBreak', clampRollFront + '.minR' )
	cmds.connectAttr( ctrlFoot + '.roll', clampRollFront + '.inputR' )
	cmds.setAttr( clampRollFront + '.maxR', rollLimit )
	cmds.connectAttr( clampRollFront + '.outputR', pmaRollFront + '.input1D[0]' )
	
	cmds.setAttr( pmaRollFront + '.operation', 2 )
	cmds.connectAttr( ctrlFoot + '.rollBreak', pmaRollFront + '.input1D[1]' )
	cmds.connectAttr( pmaRollFront + '.output1D', pivotFront + '.rotateX' )
	
	# connect twist attributes
	cmds.connectAttr( ctrlFoot + '.toeTwist', pivotFront + '.rotateY' )
	cmds.connectAttr( ctrlFoot + '.heelTwist', pivotRear + '.rotateY' )
	
	# create pivot for toe raise, parent ball ikHandle and connect
	pivToeRaise = common.insertGroup( pivotFront )
	pivToeRaise = cmds.rename( pivToeRaise, common.getName( node=pivToeRaise, side=side, rigPart='toe', function='raise_piv', nodeType='grp') )
	cmds.parent( ikHandleBall, pivotFront )
	cmds.connectAttr( ctrlFoot + '.toeRaise', pivToeRaise + '.rotateX' )
	
	# create pivot for toe tap and connect
	pivToeTap = cmds.group( ikHandleToe )
	pivToeTap = cmds.rename( pivToeTap, common.getName( node=pivToeTap, side=side, rigPart='toe', function='tap_piv', nodeType='grp') )
	cmds.xform( pivToeTap, preserve = True, ws = True, piv = cmds.xform( jntBall, q = True, translation = True, ws = True) )
	cmds.connectAttr( ctrlFoot + '.toeTap', pivToeTap + '.rotateX' )
	
	
	# create lattice deformer
	latticeVerts = []
	for vertId in latticeVertIds:
		latticeVerts.append( '%s.vtx[%s]' % (mesh, vertId) )
	cmds.select( latticeVerts )
	
	ffd, ffdLattice, ffdBase = cmds.lattice( divisions =(3, 2, 4), objectCentered = True, outsideLattice = 2, ofd = 0.25 )
	ffd = cmds.rename( ffd, common.getName( node=ffd, side=side, rigPart='foot', function='contact', nodeType='ffd') )
	ffdLattice = cmds.rename( ffdLattice, common.getName( node=ffdLattice, side=side, rigPart='foot', function='contact', nodeType='ffdlattice') )
	ffdBase = cmds.rename( ffdBase, common.getName( node=ffdBase, side=side, rigPart='foot', function='contact', nodeType='ffdbase') )
	cmds.addAttr( ctrlFoot + '.squashGroundContact', edit = True, min = 0.0 ) #, max = 1.0
	cmds.setAttr( ctrlFoot + '.squashGroundContact',  1.0 )
	cmds.connectAttr( ctrlFoot + '.squashGroundContact', ffd + '.envelope' )
	
	
	outDict['lattice'] = ffd, ffdLattice, ffdBase
	
	
	# set up ground contact control
	ctrlGround = controls.Control( side = side, rigPart = "foot", function = "contact", nodeType = "ctrl", size = 1.5, color = sideColor, aimAxis = "x" )
	ctrlGround.squareCtrl()
	cmds.rotate( 0, 45, 0, ctrlGround.control + '.cv[0:4]', relative = True, objectSpace = True )
	cmds.xform( ctrlGround.control, ws = True, t = cmds.xform( jntFoot, q = True, ws = True , t = True ) )
	
	cmds.addAttr( ctrlFoot, longName = 'showGroundCtrl', attributeType = 'bool', keyable = True )
	cmds.connectAttr( ctrlFoot + '.showGroundCtrl', ctrlGround.control + '.visibility' )
	cmds.setAttr( ctrlGround.control + '.scaleX', lock = True, keyable = False, channelBox = False )
	cmds.setAttr( ctrlGround.control + '.scaleY', lock = True, keyable = False, channelBox = False )
	cmds.setAttr( ctrlGround.control + '.scaleZ', lock = True, keyable = False, channelBox = False )
	cmds.setAttr( ctrlGround.control + '.visibility', keyable = False, channelBox = False )
	cmds.addAttr( ctrlGround.control, longName = 'followFoot', attributeType = 'float', keyable = True, min = 0.0, max = 1.0, dv = 1.0 )
	
	ctrlGrpGround = common.insertGroup( ctrlGround.control )
	constGrpGround = cmds.pointConstraint( ctrlFoot, ctrlGrpGround, mo = False, skip = 'y' )[0]
	cmds.setAttr( constGrpGround + '.enableRestPosition', 0 )
	cmds.connectAttr( ctrlGround.control + '.followFoot', constGrpGround + '.' + cmds.pointConstraint( constGrpGround, q = True, weightAliasList = True )[0] )
	
	
	# create base and top lattice ctrl joints
	topLatticePoints =  ['[1][1][3]', '[0][1][2]', '[0][1][1]', '[1][1][0]', '[2][1][1]', '[2][1][2]']
	baseLatticePoints = ['[1][0][3]', '[0][0][2]', '[0][0][1]', '[1][0][0]', '[2][0][1]', '[2][0][2]']
	centerLatticePoints = [ '[1][0][1]', '[1][0][2]' ]
	latticeJntRotations = [0, -65, -115, -180, -245, -295] 
	
	grpLatticeJnts = cmds.group( empty = True )
	grpLatticeJnts = cmds.rename( grpLatticeJnts, common.getName( node=grpLatticeJnts, side=side, rigPart='foot', function='ffd_jnts', nodeType='grp' ) )
	common.align( grpLatticeJnts, ctrlFoot, translate = True, orient = False )
	
	topLatticeJnts = []
	baseLatticeJnts = []
	for latticePoints in [ baseLatticePoints, topLatticePoints ]:
		i = 0
		if latticePoints == topLatticePoints: pos = 'top'
		if latticePoints == baseLatticePoints: pos = 'base'
		for latticePoint in latticePoints:
			i += 1
			cmds.select( clear = True )
			latticeJnt = cmds.joint()
			latticeJnt = cmds.rename( latticeJnt, common.getName( node=latticeJnt, side=side, rigPart='foot', function='ffd_%s%s' % ( pos,i ), nodeType='jnt' ) )
			cmds.xform( latticeJnt, ws = True, t = cmds.xform( '%s.pt%s' % ( ffdLattice, latticePoint ), q = True, ws = True, t = True ) )
			cmds.setAttr( latticeJnt + '.radius', .5 )
			cmds.setAttr( latticeJnt + '.rotateY', latticeJntRotations[i-1] )
			latticeJnt = cmds.parent( latticeJnt, grpLatticeJnts )[0]
			common.insertGroup( latticeJnt )
			if pos == 'top': topLatticeJnts.append( latticeJnt )
			if pos == 'base': baseLatticeJnts.append( latticeJnt )
	
	# center lattice joint
	cmds.select( clear = True )
	centerLatticeJnt = cmds.joint()
	centerLatticeJnt = cmds.rename( centerLatticeJnt, common.getName( node=centerLatticeJnt, side=side, rigPart='foot', function='ffd_center', nodeType='jnt' ) )
	cmds.setAttr( centerLatticeJnt + '.radius', .5 )
	clpPos1 = cmds.xform( '%s.pt%s' % ( ffdLattice, centerLatticePoints[0] ), q = True, ws = True, t = True )
	clpPos2 = cmds.xform( '%s.pt%s' % ( ffdLattice, centerLatticePoints[1] ), q = True, ws = True, t = True )
	clpPos = [0,0,0]
	clpPos[0] = clpPos1[0] + 0.5 * ( clpPos2[0] - clpPos1[0] )
	clpPos[1] = clpPos1[1] + 0.5 * ( clpPos2[1] - clpPos1[1] )
	clpPos[2] = clpPos1[2] + 0.5 * ( clpPos2[2] - clpPos1[2] )
	cmds.xform( centerLatticeJnt, ws = True, t = clpPos)
	centerLatticeJnt = cmds.parent( centerLatticeJnt, grpLatticeJnts)[0]
	common.insertGroup( centerLatticeJnt )
	baseLatticeJnts.append( centerLatticeJnt )
	
	# create ground reader locators
	grpReadLocs = cmds.group( empty = True )
	grpReadLocs = cmds.rename( grpReadLocs, common.getName( node=grpReadLocs, side=side, rigPart='foot', function='read_locs', nodeType='grp' ) )
	
	i = 0
	for latticeJnt in baseLatticeJnts:
		i += 1
		
		locBase = cmds.spaceLocator()
		cmds.setAttr( cmds.listRelatives( locBase )[0] + '.localScale', .2, .2, .2  )
		locBase = cmds.rename( locBase, common.getName( node=locBase, side=side, rigPart='ground', function='base%s' % i, nodeType='loc' ) )
		cmds.setAttr( locBase + '.visibility', 0 )
		
		locReader = cmds.spaceLocator()
		cmds.setAttr( cmds.listRelatives( locReader )[0] + '.localScale', .2, .2, .2  )
		locReader = cmds.rename( locReader, common.getName( node=locReader, side=side, rigPart='ground', function='read%s' % i, nodeType='loc' ) )
		
		locTop = cmds.spaceLocator()
		cmds.setAttr( cmds.listRelatives( locTop )[0] + '.localScale', .2, .2, .2  )
		locTop = cmds.rename( locTop, common.getName( node=locTop, side=side, rigPart='ground', function='top%s' % i, nodeType='loc' ) )
	
		locReader = cmds.parent( locReader, locBase )[0]
		constRead = cmds.pointConstraint( locTop, locReader, mo = False )
		locBase = cmds.parent( locBase, ctrlGround.control )[0]
		
		locTop = cmds.parent( locTop, grpReadLocs )[0]
	
		cmds.xform( locTop, ws = True, t = cmds.xform( latticeJnt, q = True, ws = True , t = True ) )
		constBase = cmds.pointConstraint( locTop, locBase, mo = False, skip = 'y' )
	
	
		# remap reader output and connect to lattice joint
		remapRead = cmds.shadingNode( 'remapValue', asUtility = True )
		remapRead = cmds.rename( remapRead, common.getName( node=remapRead, side=side, rigPart='ground', function='read%s' % i, nodeType='rmv') )
		cmds.setAttr( remapRead + '.inputMax', -1)
		cmds.setAttr( remapRead + '.outputMax', 1)
		cmds.connectAttr( locReader + '.translateY', remapRead + '.inputValue', f = True )
		cmds.connectAttr( remapRead + '.outValue', latticeJnt + '.translateY', f = True )
		
		if latticeJnt == centerLatticeJnt: # set min max on center remap to enable center drag
			remapRead = cmds.rename( remapRead, common.getName( node=remapRead, side=side, rigPart='ground', function='read_center', nodeType='rmv') )
		
			cmds.setAttr( remapRead + '.inputMin', 0 )
			cmds.setAttr( remapRead + '.outputMin', 0 )
			cmds.setAttr( remapRead + '.inputMax', 1 )
			cmds.setAttr( remapRead + '.outputMax', 1 )
			
			cmds.setAttr( remapRead + '.value[0].value_FloatValue', 0 )	
			cmds.setAttr( remapRead + '.value[0].value_Position', -0.02 )
			cmds.setAttr( remapRead + '.value[0].value_Interp', 1 )
			
			cmds.setAttr( remapRead + '.value[1].value_FloatValue', -1 )	
			cmds.setAttr( remapRead + '.value[1].value_Position', 0.25 )	
			cmds.setAttr( remapRead + '.value[1].value_Interp', 1 )	
					
			cmds.setAttr( remapRead + '.value[2].value_FloatValue', 1 )	
			cmds.setAttr( remapRead + '.value[2].value_Position', -0.25 )	
			cmds.setAttr( remapRead + '.value[2].value_Interp', 1 )			
			
		else: # connect remap output to top joints tz to enhance squishyness
			cmds.connectAttr( remapRead + '.outValue', topLatticeJnts[i-1] + '.translateZ', f = True )
	
	# bind lattice
	clusterLattice = cmds.skinCluster( topLatticeJnts + baseLatticeJnts, ffdLattice ,tsb=True, skinMethod = 0, nw = 1)
	clusterLattice = cmds.rename( clusterLattice, common.getName( node=clusterLattice, side=side, rigPart='foot', function='lattice', nodeType='skinCluster') )
	
	
	# create system and const groups
	grpConst = cmds.group( empty = True, name = side + '_foot_const_grp' )
	common.align( grpConst, ctrlFoot, translate = True, orient = False )
	cmds.parentConstraint( ctrlFoot, grpConst, mo = True )
	
	grpSystem = cmds.group( empty = True, name = side + '_foot_grp' )
	common.align( grpSystem, ctrlFoot, translate = True, orient = False )
	
	# grouping
	grpConst = cmds.parent( grpConst, grpSystem )[0]
	grpJnts = cmds.parent( grpJnts, grpSystem )[0]
	ctrlGrpGround = cmds.parent( ctrlGrpGround, grpSystem )[0]
	grpReadLocs = cmds.parent( grpReadLocs, pivotBall )[0]
	grpLatticeJnts = cmds.parent( grpLatticeJnts, pivotBall )[0]
	pivotRight = cmds.parent( pivotRight, grpConst )[0]
	
	cmds.setAttr( ffdLattice + '.inheritsTransform', 0 )
	ffdLattice, ffdBase = cmds.parent( ffdLattice, ffdBase, pivotBall )
	
	# group ik handle
	cmds.parent( ikHandleLeg, pivotBall )
	for each in cmds.listRelatives( ikHandleLeg ):
		if cmds.nodeType( each ) == 'pointConstraint':
			cmds.delete( each )
	
	# constrain stretch locator
	for each in cmds.listRelatives( stretchLoc ):
		if cmds.nodeType( each ) == 'pointConstraint':
			cmds.delete( each )
	cmds.parentConstraint( pivotBall , stretchLoc, mo = True, weight = 1 )
	
	# constrain low curve jnt grp
	lowCurveGrp = None
	systemGrpLimb = cmds.listRelatives( cmds.listRelatives( stretchLoc, p = True ), p = True )
	for each in cmds.listRelatives( systemGrpLimb ):
		if ( ( side + '_leg_low_curve' ) in each ) and ( cmds.nodeType( each ) == 'transform' ):
			lowCurveGrp = each

	if lowCurveGrp:
		for each in cmds.listRelatives( lowCurveGrp ):
			if cmds.nodeType( each ) == 'parentConstraint':
				cmds.delete( each )
		cmds.parentConstraint( pivotBall, lowCurveGrp, mo = True )
	else: print( 'Could not find leg_low_curve_#_jnt_grp, please constrain manually to ball pivot locator.' )
	
	# hide const / utility grp
	if cleanUp == 1:
		cmds.setAttr( grpConst + '.visibility', 0 )
		cmds.setAttr( grpJnts + '.visibility', 0 )
	
	
	outDict['systemsGrp'] = grpSystem
		
	
	cmds.select( ctrlFoot )
	print('DO NOT FORGET: If the rig is build before there is a skincluster attached to the mesh you will need to reorder the deformers.')
	print('Reverse Foot %s created.' % side)
	return outDict
예제 #38
0
def rigEyes():
    # eyeBall - eyeLids intersections
    surf1 = 'LT_eyeBallIntersect_srf_0'
    surf2 = 'CT_eyeBallHeadIntersecter_srf_0'
    jntsNum = 20
    addJntsOnSurfIntersection(surf1, surf2, jntsNum)

    # eyeBall pop controls
    baseTangentMP = ms.addTangentMPTo('LT_eyeBase_mPt',
                                      'LT_eyeTip_mPt',
                                      'z',
                                      default=0.2,
                                      reverse=False)
    tipTangentMP = ms.addTangentMPTo('LT_eyeTip_mPt',
                                     'LT_eyeBase_mPt',
                                     'z',
                                     default=0.2,
                                     reverse=True)
    midMP = ms.addMidMP(baseTangentMP, tipTangentMP, 'LT_eyeBase_mPt',
                        'LT_eyeTip_mPt', (0, 0, 1), (0, 1, 0), 'LT_mid_mPt')
    crv = ms.createSplineMPs(('LT_eyeBase_mPt', baseTangentMP, midMP,
                              tipTangentMP, 'LT_eyeTip_mPt'), 8, 'LT_eyeSpine',
                             (0, 3, 0))

    baseTangentMP = ms.addTangentMPTo('RT_eyeBase_mPt',
                                      'RT_eyeTip_mPt',
                                      'z',
                                      default=0.2,
                                      reverse=False)
    tipTangentMP = ms.addTangentMPTo('RT_eyeTip_mPt',
                                     'RT_eyeBase_mPt',
                                     'z',
                                     default=0.2,
                                     reverse=True)
    midMP = ms.addMidMP(baseTangentMP, tipTangentMP, 'RT_eyeBase_mPt',
                        'RT_eyeTip_mPt', (0, 0, 1), (0, 1, 0), 'RT_mid_mPt')
    crv = ms.createSplineMPs(('RT_eyeBase_mPt', baseTangentMP, midMP,
                              tipTangentMP, 'RT_eyeTip_mPt'), 8, 'RT_eyeSpine',
                             (0, 3, 0))

    #===========================================================================
    # add IK offset ctrls to eyeball
    #===========================================================================
    lfMps = mc.ls(sl=True)
    ctls = []

    # create left controls
    for ctlId in range(0, len(lfMps)):
        ctl = cs.ctlCurve(lfMps[ctlId].replace('_MPJnt_', '_ctl_'),
                          'circle',
                          0,
                          size=6,
                          snap=lfMps[ctlId])
        ctl.setSpaces([lfMps[ctlId]], ['Eye'])
        ctls.append(ctl)

    rtMps = mc.ls(sl=True)
    ctls = []

    # create right controls
    for ctlId in range(0, len(rtMps)):
        ctl = cs.ctlCurve(rtMps[ctlId].replace('_MPJnt_', '_ctl_'),
                          'circle',
                          0,
                          size=6,
                          snap=rtMps[ctlId])
        ctl.setSpaces([rtMps[ctlId]], ['Eye'])
        ctls.append(ctl)

    #===========================================================================
    # Add stretchy volume for eyeBall spine
    #===========================================================================

    stretchAmts = {
        'LT_eyeSpine_ctl_0_space': 10,
        'LT_eyeSpine_ctl_1_space': 9,
        'LT_eyeSpine_ctl_2_space': 8,
        'LT_eyeSpine_ctl_3_space': 5,
        'LT_eyeSpine_ctl_4_space': 3,
        'LT_eyeSpine_ctl_5_space': 1.25,
        'LT_eyeSpine_ctl_6_space': 0,
        'LT_eyeSpine_ctl_7_space': -1
    }

    ms.addVolume('LT_eyeSpine_uniform_crv_crv', stretchAmts)

    stretchAmts = {
        'RT_eyeSpine_ctl_0_space': 10,
        'RT_eyeSpine_ctl_1_space': 9,
        'RT_eyeSpine_ctl_2_space': 8,
        'RT_eyeSpine_ctl_3_space': 5,
        'RT_eyeSpine_ctl_4_space': 3,
        'RT_eyeSpine_ctl_5_space': 1.25,
        'RT_eyeSpine_ctl_6_space': 0,
        'RT_eyeSpine_ctl_7_space': -1
    }

    ms.addVolume('RT_eyeSpine_uniform_crv_crv', stretchAmts)
    #===========================================================================
    # Add control lattice to eyeBall nurbs
    #===========================================================================

    # Create lattice - hard coded to 8 ctls in Z
    eyeSphere = 'LT_eyeBallIntersect_srf_0'
    prefix = 'LT_eyeBallIntersect_'
    ffd, lat, latBase = mc.lattice(eyeSphere,
                                   n=prefix + 'ffd',
                                   oc=True,
                                   dv=(4, 4, 8))
    grp = abRT.groupFreeze(lat)
    rt.transferAttrValues(lat + '.s', grp + '.s', False)
    mc.setAttr(lat + '.s', 1, 1, 1)
    mc.parent(latBase, grp)

    # Create lattice - hard coded to 8 ctls in Z
    eyeSphere = 'RT_eyeBallIntersect_srf_0'
    prefix = 'RT_eyeBallIntersect_'
    ffd, lat, latBase = mc.lattice(eyeSphere,
                                   n=prefix + 'ffd',
                                   oc=True,
                                   dv=(4, 4, 8))
    grp = abRT.groupFreeze(lat)
    rt.transferAttrValues(lat + '.s', grp + '.s', False)
    mc.setAttr(lat + '.s', 1, 1, 1)
    mc.parent(latBase, grp)

    # DO THIS FOR LEFT AND RIGHT SIDES

    # Create joints under each ctl
    ctls = mc.ls(os=True)
    jnts = []
    for eachCtl in ctls:
        mc.select(cl=True)
        jnt = mc.joint(n=eachCtl.replace('_ctl', '_jnt'))
        rt.parentSnap(jnt, eachCtl)
        jnts.append(jnt)
        mc.setAttr(jnt + '.radius', 3)
        mc.setAttr(jnt + '.jointOrient', 0, 0, 0)

    # Weight joints to lattice
    skn = mc.skinCluster(jnts, lat, name=lat + '_skn')[0]
    for jnt in jnts:
        i = jnts.index(jnt)
        mc.skinPercent(skn, lat + '.pt[*][*][%d]' % i, tv=((jnt, 1)))
예제 #39
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB',
                                           query=True,
                                           value=True)
            except:
                hideJoints = 1
            # declare lists to store names and attributes:
            self.mainCtrlList, self.wheelCtrlList, self.steeringGrpList, self.ctrlHookGrpList = [], [], [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [
                    self.mirrorNames[0] + '_',
                    self.mirrorNames[len(self.mirrorNames) - 1] + '_'
                ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(
                        self.moduleGrp,
                        name=side + self.userGuideName + '_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated,
                                                      allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item,
                                    side + self.userGuideName + "_" + item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                                empty=True)
                    cmds.parent(side + self.userGuideName + '_Guide_Base',
                                self.mirrorGrp,
                                absolute=True)
                    # re-rename grp:
                    cmds.rename(
                        self.mirrorGrp,
                        side + self.userGuideName + '_' + self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        if cmds.getAttr(self.moduleGrp + ".flip") == 0:
                            for axis in self.mirrorAxis:
                                gotValue = cmds.getAttr(
                                    side + self.userGuideName +
                                    "_Guide_Base.translate" + axis)
                                flipedValue = gotValue * (-2)
                                cmds.setAttr(
                                    side + self.userGuideName + '_' +
                                    self.mirrorGrp + '.translate' + axis,
                                    flipedValue)
                        else:
                            for axis in self.mirrorAxis:
                                cmds.setAttr(
                                    side + self.userGuideName + '_' +
                                    self.mirrorGrp + '.scale' + axis, -1)
                # joint labelling:
                jointLabelAdd = 1
            else:  # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp,
                                            name=self.userGuideName +
                                            '_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated,
                                                  allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName + "_" + item)
                self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                            name="Guide_Base_Grp",
                                            relative=True)
                #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
                # re-rename grp:
                cmds.rename(self.mirrorGrp,
                            self.userGuideName + '_' + self.mirrorGrp)
                # joint labelling:
                jointLabelAdd = 0
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                    "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # declare guides:
                self.base = side + self.userGuideName + '_Guide_Base'
                self.cvCenterLoc = side + self.userGuideName + "_Guide_CenterLoc"
                self.cvFrontLoc = side + self.userGuideName + "_Guide_FrontLoc"
                self.cvInsideLoc = side + self.userGuideName + "_Guide_InsideLoc"
                self.cvOutsideLoc = side + self.userGuideName + "_Guide_OutsideLoc"

                # create a joint:
                cmds.select(clear=True)
                self.centerJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Jnt",
                    scaleCompensate=False)
                cmds.addAttr(self.centerJoint,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                # joint labelling:
                utils.setJointLabel(
                    self.centerJoint, s + jointLabelAdd, 18,
                    self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'])
                # create end joint:
                self.endJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_JEnd")

                # create controls:
                self.wheelCtrl = self.ctrls.cvControl(
                    "id_060_WheelCenter",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Ctrl",
                    r=self.ctrlRadius,
                    d=self.curveDegree)
                self.mainCtrl = self.ctrls.cvControl(
                    "id_061_WheelMain",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c058_main'] + "_Ctrl",
                    r=self.ctrlRadius * 0.4,
                    d=self.curveDegree)
                self.insideCtrl = self.ctrls.cvControl(
                    "id_062_WheelPivot",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c011_RevFoot_B'].capitalize()
                    + "_Ctrl",
                    r=self.ctrlRadius * 0.2,
                    d=self.curveDegree,
                    rot=(0, 90, 0))
                self.outsideCtrl = self.ctrls.cvControl(
                    "id_062_WheelPivot",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c010_RevFoot_A'].capitalize()
                    + "_Ctrl",
                    r=self.ctrlRadius * 0.2,
                    d=self.curveDegree,
                    rot=(0, 90, 0))
                self.mainCtrlList.append(self.mainCtrl)
                self.wheelCtrlList.append(self.wheelCtrl)

                # origined from attributes:
                utils.originedFrom(objName=self.mainCtrl,
                                   attrString=self.base + ";" +
                                   self.cvCenterLoc + ";" + self.cvFrontLoc +
                                   ";" + self.cvInsideLoc + ";" +
                                   self.cvOutsideLoc)
                #utils.originedFrom(objName=self.wheelCtrl, attrString=self.cvCenterLoc)

                # prepare group to receive steering wheel connection:
                self.toSteeringGrp = cmds.group(
                    self.insideCtrl,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'].capitalize() +
                    "_Grp")
                cmds.addAttr(
                    self.toSteeringGrp,
                    longName=self.langDic[self.langName]['c070_steering'],
                    attributeType='bool',
                    keyable=True)
                cmds.addAttr(
                    self.toSteeringGrp,
                    longName=self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['m151_invert'],
                    attributeType='bool',
                    keyable=True)
                cmds.setAttr(
                    self.toSteeringGrp + "." +
                    self.langDic[self.langName]['c070_steering'], 1)
                self.steeringGrpList.append(self.toSteeringGrp)

                # position and orientation of joint and control:
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.centerJoint,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.endJoint,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.wheelCtrl,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.mainCtrl,
                                          maintainOffset=False))
                if s == 1 and cmds.getAttr(self.moduleGrp + ".flip") == 1:
                    cmds.move(self.ctrlRadius,
                              self.mainCtrl,
                              moveY=True,
                              relative=True,
                              objectSpace=True,
                              worldSpaceDistance=True)
                else:
                    cmds.move(-self.ctrlRadius,
                              self.mainCtrl,
                              moveY=True,
                              relative=True,
                              objectSpace=True,
                              worldSpaceDistance=True)
                cmds.delete(
                    cmds.parentConstraint(self.cvInsideLoc,
                                          self.toSteeringGrp,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvOutsideLoc,
                                          self.outsideCtrl,
                                          maintainOffset=False))

                # zeroOut controls:
                zeroGrpList = utils.zeroOut([
                    self.mainCtrl, self.wheelCtrl, self.toSteeringGrp,
                    self.outsideCtrl
                ])
                wheelAutoGrp = utils.zeroOut([self.wheelCtrl])
                wheelAutoGrp = cmds.rename(
                    wheelAutoGrp, side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Auto_Grp")

                # fixing flip mirror:
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        for zeroOutGrp in zeroGrpList:
                            cmds.setAttr(zeroOutGrp + ".scaleX", -1)
                            cmds.setAttr(zeroOutGrp + ".scaleY", -1)
                            cmds.setAttr(zeroOutGrp + ".scaleZ", -1)

                cmds.addAttr(self.wheelCtrl,
                             longName='scaleCompensate',
                             attributeType="bool",
                             keyable=False)
                cmds.setAttr(self.wheelCtrl + ".scaleCompensate",
                             1,
                             channelBox=True)
                cmds.connectAttr(self.wheelCtrl + ".scaleCompensate",
                                 self.centerJoint + ".segmentScaleCompensate",
                                 force=True)
                # hide visibility attributes:
                self.ctrls.setLockHide(
                    [self.mainCtrl, self.insideCtrl, self.outsideCtrl], ['v'])
                self.ctrls.setLockHide(
                    [self.wheelCtrl],
                    ['tx', 'ty', 'tz', 'rx', 'ry', 'sx', 'sy', 'sz', 'v'])

                # grouping:
                cmds.parentConstraint(self.wheelCtrl,
                                      self.centerJoint,
                                      maintainOffset=False,
                                      name=self.centerJoint +
                                      "_ParentConstraint")
                cmds.scaleConstraint(self.wheelCtrl,
                                     self.centerJoint,
                                     maintainOffset=True,
                                     name=self.centerJoint +
                                     "_ScaleConstraint")
                cmds.parent(zeroGrpList[1], self.mainCtrl, absolute=True)
                cmds.parent(zeroGrpList[0], self.outsideCtrl, absolute=True)
                cmds.parent(zeroGrpList[3], self.insideCtrl, absolute=True)

                # add attributes:
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c047_autoRotate'],
                    attributeType="bool",
                    defaultValue=1,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c068_startFrame'],
                    attributeType="long",
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c067_radius'],
                    attributeType="float",
                    min=0.01,
                    defaultValue=self.ctrlRadius,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c069_radiusScale'],
                    attributeType="float",
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c021_showControls'],
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=0,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c070_steering'],
                    attributeType="bool",
                    defaultValue=0,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['i037_to'] +
                    self.langDic[self.langName]['c070_steering'].capitalize(),
                    attributeType="float",
                    defaultValue=0,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c093_tryKeepUndo'],
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=1,
                    keyable=False)

                # get stored values by user:
                startFrameValue = cmds.getAttr(self.moduleGrp + ".startFrame")
                steeringValue = cmds.getAttr(self.moduleGrp + ".steering")
                showControlsValue = cmds.getAttr(self.moduleGrp +
                                                 ".showControls")
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c068_startFrame'],
                             startFrameValue,
                             channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c070_steering'],
                             steeringValue,
                             channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c021_showControls'],
                             showControlsValue,
                             channelBox=True)
                cmds.setAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    1,
                    channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c093_tryKeepUndo'],
                             1,
                             channelBox=True)
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        cmds.setAttr(
                            self.wheelCtrl + "." +
                            self.langDic[self.langName]['c070_steering'] +
                            self.langDic[
                                self.langName]['c053_invert'].capitalize(), 0)

                # automatic rotation wheel setup:
                receptSteeringMD = cmds.createNode(
                    'multiplyDivide',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_MD")
                inverseSteeringMD = cmds.createNode(
                    'multiplyDivide',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_Inv_MD")
                steeringInvCnd = cmds.createNode(
                    'condition',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_Inv_Cnd")
                cmds.setAttr(steeringInvCnd + ".colorIfTrueR", 1)
                cmds.setAttr(steeringInvCnd + ".colorIfFalseR", -1)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['i037_to'] +
                    self.langDic[self.langName]['c070_steering'].capitalize(),
                    receptSteeringMD + ".input1X",
                    force=True)
                cmds.connectAttr(self.wheelCtrl + "." +
                                 self.langDic[self.langName]['c070_steering'],
                                 receptSteeringMD + ".input2X",
                                 force=True)
                cmds.connectAttr(receptSteeringMD + ".outputX",
                                 inverseSteeringMD + ".input1X",
                                 force=True)
                cmds.connectAttr(steeringInvCnd + ".outColorR",
                                 inverseSteeringMD + ".input2X",
                                 force=True)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    steeringInvCnd + ".firstTerm",
                    force=True)
                cmds.connectAttr(inverseSteeringMD + ".outputX",
                                 self.toSteeringGrp + ".rotateY",
                                 force=True)
                # create locators (frontLoc to get direction and oldLoc to store wheel old position):
                self.frontLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] +
                    "_Front_Loc")[0]
                self.oldLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Old_Loc")[0]
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.frontLoc,
                                          maintainOffset=False))
                cmds.parent(self.frontLoc, self.mainCtrl)
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.oldLoc,
                                          maintainOffset=False))
                cmds.setAttr(self.frontLoc + ".visibility", 0, lock=True)
                cmds.setAttr(self.oldLoc + ".visibility", 0, lock=True)
                # this wheel auto group locator could be replaced by a decomposeMatrix to get the translation in world space of the Wheel_Auto_Ctrl_Grp instead:
                self.wheelAutoGrpLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Auto_Loc")[0]
                cmds.pointConstraint(wheelAutoGrp,
                                     self.wheelAutoGrpLoc,
                                     maintainOffset=False,
                                     name=self.wheelAutoGrpLoc +
                                     "_PointConstraint")
                cmds.setAttr(self.wheelAutoGrpLoc + ".visibility",
                             0,
                             lock=True)
                expString = "if ("+self.wheelCtrl+"."+self.langDic[self.langName]['c047_autoRotate']+" == 1) {"+\
                        "\nif ("+self.wheelCtrl+"."+self.langDic[self.langName]['c093_tryKeepUndo']+" == 1) { undoInfo -stateWithoutFlush 0; };"+\
                        "\nfloat $radius = "+self.wheelCtrl+"."+self.langDic[self.langName]['c067_radius']+" * "+self.wheelCtrl+"."+self.langDic[self.langName]['c069_radiusScale']+\
                        ";\nvector $moveVectorOld = `xform -q -ws -t \""+self.oldLoc+\
                        "\"`;\nvector $moveVector = << "+self.wheelAutoGrpLoc+".translateX, "+self.wheelAutoGrpLoc+".translateY, "+self.wheelAutoGrpLoc+".translateZ >>;"+\
                        "\nvector $dirVector = `xform -q -ws -t \""+self.frontLoc+\
                        "\"`;\nvector $wheelVector = ($dirVector - $moveVector);"+\
                        "\nvector $motionVector = ($moveVector - $moveVectorOld);"+\
                        "\nfloat $distance = mag($motionVector);"+\
                        "\n$dot = dotProduct($motionVector, $wheelVector, 1);\n"+\
                        wheelAutoGrp+".rotateZ = "+wheelAutoGrp+".rotateZ - 360 / (6.283*$radius) * ($dot*$distance);"+\
                        "\nxform -t ($moveVector.x) ($moveVector.y) ($moveVector.z) "+self.oldLoc+\
                        ";\nif (frame == "+self.wheelCtrl+"."+self.langDic[self.langName]['c068_startFrame']+") { "+wheelAutoGrp+".rotateZ = 0; };"+\
                        "\nif ("+self.wheelCtrl+"."+self.langDic[self.langName]['c093_tryKeepUndo']+" == 1) { undoInfo -stateWithoutFlush 1; };};"
                # expression:
                cmds.expression(name=side + self.userGuideName + "_" +
                                self.langDic[self.langName]['m156_wheel'] +
                                "_Exp",
                                object=self.frontLoc,
                                string=expString)
                self.ctrls.setLockHide([self.frontLoc, self.wheelAutoGrpLoc], [
                    'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
                ])

                # deformers:
                self.loadedGeo = cmds.getAttr(self.moduleGrp + ".geo")

                # geometry holder:
                self.geoHolder = cmds.polyCube(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c046_holder'] + "_Geo",
                    constructionHistory=False)[0]
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.geoHolder,
                                          maintainOffset=False))
                cmds.setAttr(self.geoHolder + ".visibility", 0, lock=True)

                # skinning:
                cmds.skinCluster(self.centerJoint,
                                 self.geoHolder,
                                 toSelectedBones=True,
                                 dropoffRate=4.0,
                                 maximumInfluences=3,
                                 skinMethod=0,
                                 normalizeWeights=1,
                                 removeUnusedInfluence=False,
                                 name=side + self.userGuideName + "_" +
                                 self.langDic[self.langName]['c046_holder'] +
                                 "_SC")
                if self.loadedGeo:
                    if cmds.objExists(self.loadedGeo):
                        baseName = utils.extractSuffix(self.loadedGeo)
                        skinClusterName = baseName + "_SC"
                        if "|" in skinClusterName:
                            skinClusterName = skinClusterName[skinClusterName.
                                                              rfind("|") + 1:]
                        try:
                            cmds.skinCluster(self.centerJoint,
                                             self.loadedGeo,
                                             toSelectedBones=True,
                                             dropoffRate=4.0,
                                             maximumInfluences=3,
                                             skinMethod=0,
                                             normalizeWeights=1,
                                             removeUnusedInfluence=False,
                                             name=skinClusterName)
                        except:
                            childList = cmds.listRelatives(self.loadedGeo,
                                                           children=True,
                                                           allDescendents=True)
                            if childList:
                                for item in childList:
                                    itemType = cmds.objectType(item)
                                    if itemType == "mesh" or itemType == "nurbsSurface":
                                        try:
                                            skinClusterName = utils.extractSuffix(
                                                item) + "_SC"
                                            cmds.skinCluster(
                                                self.centerJoint,
                                                item,
                                                toSelectedBones=True,
                                                dropoffRate=4.0,
                                                maximumInfluences=3,
                                                skinMethod=0,
                                                normalizeWeights=1,
                                                removeUnusedInfluence=False,
                                                name=skinClusterName)
                                        except:
                                            pass

                # lattice:
                latticeList = cmds.lattice(self.geoHolder,
                                           divisions=(6, 6, 6),
                                           outsideLattice=2,
                                           outsideFalloffDistance=1,
                                           position=(0, 0, 0),
                                           scale=(self.ctrlRadius * 2,
                                                  self.ctrlRadius * 2,
                                                  self.ctrlRadius * 2),
                                           name=side + self.userGuideName +
                                           "_FFD")  #[deformer, lattice, base]
                cmds.scale(self.ctrlRadius * 2, self.ctrlRadius * 2,
                           self.ctrlRadius * 2, latticeList[2])
                # clusters:
                upperClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][4:5][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c044_upper'] +
                    "_Cls")  #[deform, handle]
                middleClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][2:3][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m033_middle'] +
                    "_Cls")  #[deform, handle]
                lowerClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][0:1][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c045_lower'] +
                    "_Cls")  #[deform, handle]
                clusterGrpList = utils.zeroOut([
                    upperClusterList[1], middleClusterList[1],
                    lowerClusterList[1]
                ])
                clustersGrp = cmds.group(clusterGrpList,
                                         name=side + self.userGuideName +
                                         "_Clusters_Grp")

                # deform controls:
                upperDefCtrl = self.ctrls.cvControl(
                    "id_063_WheelDeform",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c044_upper'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree)
                middleDefCtrl = self.ctrls.cvControl(
                    "id_064_WheelMiddle",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m033_middle'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree)
                lowerDefCtrl = self.ctrls.cvControl(
                    "id_063_WheelDeform",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c045_lower'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree,
                    rot=(0, 0, 180))
                defCtrlGrpList = utils.zeroOut(
                    [upperDefCtrl, middleDefCtrl, lowerDefCtrl])
                defCtrlGrp = cmds.group(defCtrlGrpList,
                                        name=side + self.userGuideName +
                                        "_Ctrl_Grp")

                # positions:
                cmds.delete(
                    cmds.parentConstraint(upperClusterList[1],
                                          defCtrlGrpList[0],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(middleClusterList[1],
                                          defCtrlGrpList[1],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(lowerClusterList[1],
                                          defCtrlGrpList[2],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          latticeList[1],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          latticeList[2],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          clustersGrp,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          defCtrlGrp,
                                          maintainOffset=False))
                outsideDist = cmds.getAttr(self.cvOutsideLoc + ".tz")
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        outsideDist = -outsideDist
                cmds.move(outsideDist,
                          defCtrlGrp,
                          moveZ=True,
                          relative=True,
                          objectSpace=True,
                          worldSpaceDistance=True)
                self.ctrls.directConnect(upperDefCtrl, upperClusterList[1])
                self.ctrls.directConnect(middleDefCtrl, middleClusterList[1])
                self.ctrls.directConnect(lowerDefCtrl, lowerClusterList[1])
                # grouping deformers:
                if self.loadedGeo:
                    if cmds.objExists(self.loadedGeo):
                        cmds.lattice(latticeList[0],
                                     edit=True,
                                     geometry=self.loadedGeo)
                defGrp = cmds.group(latticeList[1],
                                    latticeList[2],
                                    clustersGrp,
                                    name=side + self.userGuideName +
                                    "_Deform_Grp")
                cmds.parentConstraint(self.mainCtrl,
                                      defGrp,
                                      maintainOffset=True,
                                      name=defGrp + "_ParentConstraint")
                cmds.scaleConstraint(self.mainCtrl,
                                     defGrp,
                                     maintainOffset=True,
                                     name=defGrp + "_ScaleConstraint")
                cmds.parent(defCtrlGrp, self.mainCtrl)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c021_showControls'],
                    defCtrlGrp + ".visibility",
                    force=True)

                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp = cmds.group(
                    zeroGrpList[2],
                    name=side + self.userGuideName + "_Control_Grp")
                self.toScalableHookGrp = cmds.group(
                    self.centerJoint,
                    defGrp,
                    name=side + self.userGuideName + "_Joint_Grp")
                self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp,
                                                  self.toScalableHookGrp,
                                                  self.oldLoc,
                                                  self.wheelAutoGrpLoc,
                                                  self.geoHolder,
                                                  name=side +
                                                  self.userGuideName + "_Grp")
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp,
                              hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp,
                              hookType='staticHook')
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_name",
                             dataType="string")
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_type",
                             dataType="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_name",
                             self.userGuideName,
                             type="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_type",
                             CLASS_NAME,
                             type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp,
                             longName='dpAR_count',
                             attributeType='long',
                             keyable=False)
                cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
                self.ctrlHookGrpList.append(self.toCtrlHookGrp)
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
                # delete duplicated group for side (mirror):
                cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
예제 #40
0
import maya.cmds as cmds

sel = cmds.ls(sl=True)
src = sel[0]
tgts = sel[1:]
shps = cmds.listRelatives(src, s=True)
shp = shps[0]
for shpe in shps:
    if "Deformed" in shpe:
        shp = shpe
hist = cmds.listHistory(shp)
print shp

defs = []
for h in hist:
    types = cmds.nodeType(h, i=True)
    if "geometryFilter" in types and "tweak" not in h:
        defs.append(h)

# here I have to parse the type of deformer and add that
for d in defs:
    typ = cmds.nodeType(d)
    for t in tgts:
        if typ == "cluster":
            # this is weird and hard to do (get cmpts?)
            cmds.cluster(d, e=True, g=t)
        if typ == "nonLinear":
            cmds.nonLinear(d, e=True, g=t)
        if typ == "ffd":
            cmds.lattice(d, e=True, g=t)
예제 #41
0
    def dpHeadDeformer(self, *args):
        """ Create the arrow curve and deformers (squash and bends).
        """
        # defining variables
        headDeformerName = self.langDic[self.langName][
            "c024_head"] + self.langDic[self.langName]["c097_deformer"]
        centerSymmetryName = self.langDic[self.langName][
            "c098_center"] + self.langDic[self.langName]["c101_symmetry"]
        topSymmetryName = self.langDic[self.langName][
            "c099_top"] + self.langDic[self.langName]["c101_symmetry"]
        intensityName = self.langDic[self.langName]["c049_intensity"]
        expandName = self.langDic[self.langName]["c104_expand"]
        axisList = ["X", "Y", "Z"]

        # validating namming in order to be possible create more than one setup
        validName = utils.validateName(headDeformerName + "_FFDSet", "FFDSet")
        numbering = validName.replace(headDeformerName, "")[:-7]
        if numbering:
            headDeformerName = headDeformerName + numbering
            centerSymmetryName = centerSymmetryName + numbering
            topSymmetryName = topSymmetryName + numbering

        # get a list of selected items
        selList = cmds.ls(selection=True)
        if selList:
            # lattice deformer
            latticeDefList = cmds.lattice(
                name=headDeformerName + "_FFD",
                divisions=(6, 6, 6),
                ldivisions=(6, 6, 6),
                outsideLattice=1,
                objectCentered=True)  #[Set, Lattice, Base]
            latticePointsList = latticeDefList[1] + ".pt[0:5][2:5][0:5]"

            # store initial scaleY in order to avoid lattice rotation bug on non frozen transformations
            bBoxMaxY = cmds.getAttr(
                latticeDefList[2] +
                ".boundingBox.boundingBoxMax.boundingBoxMaxY")
            bBoxMinY = cmds.getAttr(
                latticeDefList[2] +
                ".boundingBox.boundingBoxMin.boundingBoxMinY")
            initialSizeY = bBoxMaxY - bBoxMinY

            # force rotate zero to lattice in order to avoid selected non froozen transformations
            for axis in axisList:
                cmds.setAttr(latticeDefList[1] + ".rotate" + axis, 0)
                cmds.setAttr(latticeDefList[2] + ".rotate" + axis, 0)
            cmds.setAttr(latticeDefList[1] + ".scaleY", initialSizeY)
            cmds.setAttr(latticeDefList[2] + ".scaleY", initialSizeY)

            # getting size and distances from Lattice Bounding Box
            bBoxMaxY = cmds.getAttr(
                latticeDefList[2] +
                ".boundingBox.boundingBoxMax.boundingBoxMaxY")
            bBoxMinY = cmds.getAttr(
                latticeDefList[2] +
                ".boundingBox.boundingBoxMin.boundingBoxMinY")
            bBoxSize = bBoxMaxY - bBoxMinY
            bBoxMidY = bBoxMinY + (bBoxSize * 0.5)

            # twist deformer
            twistDefList = cmds.nonLinear(latticePointsList,
                                          name=headDeformerName + "_Twist",
                                          type="twist")  #[Deformer, Handle]
            cmds.setAttr(twistDefList[0] + ".lowBound", 0)
            cmds.setAttr(twistDefList[0] + ".highBound", bBoxSize)
            cmds.setAttr(twistDefList[1] + ".ty", bBoxMinY)

            # squash deformer
            squashDefList = cmds.nonLinear(latticePointsList,
                                           name=headDeformerName + "_Squash",
                                           type="squash")  #[Deformer, Handle]
            cmds.setAttr(squashDefList[0] + ".highBound", 0.5 * bBoxSize)
            cmds.setAttr(squashDefList[0] + ".startSmoothness", 1)
            cmds.setAttr(squashDefList[1] + ".ty", bBoxMidY)

            # side bend deformer
            sideBendDefList = cmds.nonLinear(latticePointsList,
                                             name=headDeformerName +
                                             "_Side_Bend",
                                             type="bend")  #[Deformer, Handle]
            cmds.setAttr(sideBendDefList[0] + ".lowBound", 0)
            cmds.setAttr(sideBendDefList[0] + ".highBound", bBoxSize)
            cmds.setAttr(sideBendDefList[1] + ".ty", bBoxMinY)

            # front bend deformer
            frontBendDefList = cmds.nonLinear(latticePointsList,
                                              name=headDeformerName +
                                              "_Front_Bend",
                                              type="bend")  #[Deformer, Handle]
            cmds.setAttr(frontBendDefList[0] + ".lowBound", 0)
            cmds.setAttr(frontBendDefList[0] + ".highBound", bBoxSize)
            cmds.setAttr(frontBendDefList[1] + ".ry", -90)
            cmds.setAttr(frontBendDefList[1] + ".ty", bBoxMinY)

            # fix deform transforms scale to 1
            defHandleList = [
                twistDefList[1], squashDefList[1], sideBendDefList[1],
                frontBendDefList[1]
            ]
            for defHandle in defHandleList:
                for axis in axisList:
                    cmds.setAttr(defHandle + ".scale" + axis, 1)

            # force correct rename for Maya versions before 2020:
            if (int(cmds.about(version=True)[:4]) < 2020):
                if cmds.objExists(twistDefList[0] + "Set"):
                    cmds.rename(twistDefList[0] + "Set",
                                headDeformerName + "_TwistSet")
                    twistDefList[0] = cmds.rename(twistDefList[0],
                                                  headDeformerName + "_Twist")
                    twistDefList[1] = cmds.rename(
                        twistDefList[1], headDeformerName + "_TwistHandle")
                if cmds.objExists(squashDefList[0] + "Set"):
                    cmds.rename(squashDefList[0] + "Set",
                                headDeformerName + "_SquashSet")
                    squashDefList[0] = cmds.rename(
                        squashDefList[0], headDeformerName + "_Squash")
                    squashDefList[1] = cmds.rename(
                        squashDefList[1], headDeformerName + "_SquashHandle")
                if cmds.objExists(sideBendDefList[0] + "Set"):
                    cmds.rename(sideBendDefList[0] + "Set",
                                headDeformerName + "_Side_BendSet")
                    sideBendDefList[0] = cmds.rename(
                        sideBendDefList[0], headDeformerName + "_Side_Bend")
                    sideBendDefList[1] = cmds.rename(
                        sideBendDefList[1],
                        headDeformerName + "_Side_BendHandle")
                if cmds.objExists(frontBendDefList[0] + "Set"):
                    cmds.rename(frontBendDefList[0] + "Set",
                                headDeformerName + "_Front_BendSet")
                    frontBendDefList[0] = cmds.rename(
                        frontBendDefList[0], headDeformerName + "_Front_Bend")
                    frontBendDefList[1] = cmds.rename(
                        frontBendDefList[1],
                        headDeformerName + "_Front_BendHandle")

            # arrow control curve
            arrowCtrl = self.ctrls.cvControl("id_053_HeadDeformer",
                                             headDeformerName + "_Ctrl",
                                             0.25 * bBoxSize,
                                             d=0)

            # add control intensite and calibrate attributes
            for axis in axisList:
                cmds.addAttr(arrowCtrl,
                             longName=intensityName + axis,
                             attributeType='float',
                             defaultValue=1)
                cmds.setAttr(arrowCtrl + "." + intensityName + axis,
                             edit=True,
                             keyable=False,
                             channelBox=True)
            cmds.addAttr(arrowCtrl,
                         longName=expandName,
                         attributeType='float',
                         min=0,
                         defaultValue=1,
                         max=10,
                         keyable=True)
            cmds.addAttr(arrowCtrl,
                         longName="calibrateX",
                         attributeType='float',
                         defaultValue=100 / (3 * bBoxSize),
                         keyable=False)
            cmds.addAttr(arrowCtrl,
                         longName="calibrateY",
                         attributeType='float',
                         defaultValue=300 / bBoxSize,
                         keyable=False)
            cmds.addAttr(arrowCtrl,
                         longName="calibrateZ",
                         attributeType='float',
                         defaultValue=100 / (3 * bBoxSize),
                         keyable=False)
            cmds.addAttr(arrowCtrl,
                         longName="calibrateReduce",
                         attributeType='float',
                         defaultValue=100,
                         keyable=False)

            # multiply divide in order to intensify influences
            calibrateMD = cmds.createNode("multiplyDivide",
                                          name=headDeformerName +
                                          "_Calibrate_MD")
            calibrateReduceMD = cmds.createNode("multiplyDivide",
                                                name=headDeformerName +
                                                "_CalibrateReduce_MD")
            intensityMD = cmds.createNode("multiplyDivide",
                                          name=headDeformerName + "_" +
                                          intensityName.capitalize() + "_MD")
            twistMD = cmds.createNode("multiplyDivide",
                                      name=headDeformerName + "_Twist_MD")
            cmds.setAttr(twistMD + ".input2Y", -1)
            cmds.setAttr(calibrateReduceMD + ".operation", 2)

            # connections
            for axis in axisList:
                cmds.connectAttr(arrowCtrl + "." + intensityName + axis,
                                 calibrateMD + ".input1" + axis,
                                 force=True)
                cmds.connectAttr(arrowCtrl + ".calibrate" + axis,
                                 calibrateReduceMD + ".input1" + axis,
                                 force=True)
                cmds.connectAttr(arrowCtrl + ".calibrateReduce",
                                 calibrateReduceMD + ".input2" + axis,
                                 force=True)
                cmds.connectAttr(calibrateReduceMD + ".output" + axis,
                                 calibrateMD + ".input2" + axis,
                                 force=True)
                cmds.connectAttr(arrowCtrl + ".translate" + axis,
                                 intensityMD + ".input1" + axis,
                                 force=True)
                cmds.connectAttr(calibrateMD + ".output" + axis,
                                 intensityMD + ".input2" + axis,
                                 force=True)
            cmds.connectAttr(intensityMD + ".outputX",
                             sideBendDefList[0] + ".curvature",
                             force=True)
            cmds.connectAttr(intensityMD + ".outputY",
                             squashDefList[0] + ".factor",
                             force=True)
            cmds.connectAttr(intensityMD + ".outputZ",
                             frontBendDefList[0] + ".curvature",
                             force=True)
            cmds.connectAttr(arrowCtrl + ".ry",
                             twistMD + ".input1Y",
                             force=True)
            cmds.connectAttr(twistMD + ".outputY",
                             twistDefList[0] + ".endAngle",
                             force=True)
            # change squash to be more cartoon
            cmds.setDrivenKeyframe(squashDefList[0] + ".lowBound",
                                   currentDriver=intensityMD + ".outputY",
                                   driverValue=-0.25 * bBoxSize,
                                   value=-bBoxSize,
                                   inTangentType="auto",
                                   outTangentType="auto")
            cmds.setDrivenKeyframe(squashDefList[0] + ".lowBound",
                                   currentDriver=intensityMD + ".outputY",
                                   driverValue=0,
                                   value=-0.5 * bBoxSize,
                                   inTangentType="auto",
                                   outTangentType="auto")
            cmds.setDrivenKeyframe(squashDefList[0] + ".lowBound",
                                   currentDriver=intensityMD + ".outputY",
                                   driverValue=0.5 * bBoxSize,
                                   value=-0.25 * bBoxSize,
                                   inTangentType="auto",
                                   outTangentType="flat")
            cmds.connectAttr(arrowCtrl + "." + expandName,
                             squashDefList[0] + ".expand",
                             force=True)
            # fix side values
            for axis in axisList:
                unitConvNode = cmds.listConnections(intensityMD + ".output" +
                                                    axis,
                                                    destination=True)[0]
                if unitConvNode:
                    if cmds.objectType(unitConvNode) == "unitConversion":
                        cmds.setAttr(unitConvNode + ".conversionFactor", 1)

            self.ctrls.setLockHide([arrowCtrl],
                                   ['rx', 'rz', 'sx', 'sy', 'sz', 'v'])

            # create symetry setup
            centerClusterList = cmds.cluster(
                latticeDefList[1] + ".pt[0:5][2:3][0:5]",
                relative=True,
                name=centerSymmetryName + "_Cls")  #[Cluster, Handle]
            topClusterList = cmds.cluster(latticeDefList[1] +
                                          ".pt[0:5][2:5][0:5]",
                                          relative=True,
                                          name=topSymmetryName + "_Cls")
            clustersZeroList = utils.zeroOut(
                [centerClusterList[1], topClusterList[1]])
            cmds.delete(
                cmds.parentConstraint(centerClusterList[1],
                                      clustersZeroList[1]))
            clusterGrp = cmds.group(
                clustersZeroList,
                name=headDeformerName + "_" +
                self.langDic[self.langName]["c101_symmetry"] + "_Grp")
            # symmetry controls
            centerSymmetryCtrl = self.ctrls.cvControl("id_068_Symmetry",
                                                      centerSymmetryName +
                                                      "_Ctrl",
                                                      bBoxSize,
                                                      d=0,
                                                      rot=(-90, 0, 90))
            topSymmetryCtrl = self.ctrls.cvControl("id_068_Symmetry",
                                                   topSymmetryName + "_Ctrl",
                                                   bBoxSize,
                                                   d=0,
                                                   rot=(0, 90, 0))
            symmetryCtrlZeroList = utils.zeroOut(
                [centerSymmetryCtrl, topSymmetryCtrl])
            for axis in axisList:
                cmds.connectAttr(centerSymmetryCtrl + ".translate" + axis,
                                 centerClusterList[1] + ".translate" + axis,
                                 force=True)
                cmds.connectAttr(centerSymmetryCtrl + ".rotate" + axis,
                                 centerClusterList[1] + ".rotate" + axis,
                                 force=True)
                cmds.connectAttr(centerSymmetryCtrl + ".scale" + axis,
                                 centerClusterList[1] + ".scale" + axis,
                                 force=True)
                cmds.connectAttr(topSymmetryCtrl + ".translate" + axis,
                                 topClusterList[1] + ".translate" + axis,
                                 force=True)
                cmds.connectAttr(topSymmetryCtrl + ".rotate" + axis,
                                 topClusterList[1] + ".rotate" + axis,
                                 force=True)
                cmds.connectAttr(topSymmetryCtrl + ".scale" + axis,
                                 topClusterList[1] + ".scale" + axis,
                                 force=True)

            # create groups
            arrowCtrlGrp = cmds.group(arrowCtrl, name=arrowCtrl + "_Grp")
            utils.zeroOut([arrowCtrl])
            offsetGrp = cmds.group(name=headDeformerName + "_Offset_Grp",
                                   empty=True)
            dataGrp = cmds.group(name=headDeformerName + "_Data_Grp",
                                 empty=True)
            cmds.delete(
                cmds.parentConstraint(latticeDefList[2],
                                      arrowCtrlGrp,
                                      maintainOffset=False))
            arrowCtrlHeigh = bBoxMaxY + (bBoxSize * 0.5)
            cmds.setAttr(arrowCtrlGrp + ".ty", arrowCtrlHeigh)
            cmds.delete(
                cmds.parentConstraint(latticeDefList[2],
                                      offsetGrp,
                                      maintainOffset=False))
            cmds.delete(
                cmds.parentConstraint(latticeDefList[2],
                                      symmetryCtrlZeroList[0],
                                      maintainOffset=False))
            cmds.delete(
                cmds.parentConstraint(latticeDefList[2],
                                      symmetryCtrlZeroList[1],
                                      maintainOffset=False))
            cmds.parent(symmetryCtrlZeroList, arrowCtrlGrp)
            latticeGrp = cmds.group(name=latticeDefList[1] + "_Grp",
                                    empty=True)
            cmds.parent(latticeDefList[1], latticeDefList[2], latticeGrp)

            # try to integrate to Head_Head_Ctrl
            allTransformList = cmds.ls(selection=False, type="transform")
            headCtrlList = self.ctrls.getControlNodeById("id_023_HeadHead")
            if headCtrlList:
                if len(headCtrlList) > 1:
                    mel.eval("warning" + "\"" +
                             self.langDic[self.langName]["i075_moreOne"] +
                             " Head control.\"" + ";")
                else:
                    self.headCtrl = headCtrlList[0]
            if self.headCtrl:
                # setup hierarchy
                headCtrlPosList = cmds.xform(self.headCtrl,
                                             query=True,
                                             rotatePivot=True,
                                             worldSpace=True)
                cmds.xform(dataGrp,
                           translation=(headCtrlPosList[0], headCtrlPosList[1],
                                        headCtrlPosList[2]),
                           worldSpace=True)
                cmds.parentConstraint(self.headCtrl,
                                      dataGrp,
                                      maintainOffset=True,
                                      name=dataGrp + "_ParentConstraint")
                cmds.scaleConstraint(self.headCtrl,
                                     dataGrp,
                                     maintainOffset=True,
                                     name=dataGrp + "_ScaleConstraint")
                # influence controls
                toHeadDefCtrlList = []
                for item in allTransformList:
                    if cmds.objExists(item + ".controlID"):
                        if cmds.getAttr(item +
                                        ".controlID") == "id_024_HeadJaw":
                            toHeadDefCtrlList.append(item)
                        elif cmds.getAttr(
                                item + ".controlID") == "id_027_HeadLipCorner":
                            toHeadDefCtrlList.append(item)
                headChildrenList = cmds.listRelatives(self.headCtrl,
                                                      children=True,
                                                      allDescendents=True,
                                                      type="transform")
                if headChildrenList:
                    for item in headChildrenList:
                        if cmds.objExists(item + ".controlID"):
                            if not cmds.getAttr(item + ".controlID"
                                                ) == "id_052_FacialFace":
                                if not cmds.getAttr(
                                        item + ".controlID"
                                ) == "id_029_SingleIndSkin":
                                    if not cmds.getAttr(
                                            item + ".controlID"
                                    ) == "id_054_SingleMain":
                                        toHeadDefCtrlList.append(item)
                                    else:
                                        singleMainShapeList = cmds.listRelatives(
                                            item, children=True, shapes=True)
                                        if singleMainShapeList:
                                            for mainShape in singleMainShapeList:
                                                toHeadDefCtrlList.append(
                                                    mainShape)
                if toHeadDefCtrlList:
                    for item in toHeadDefCtrlList:
                        cmds.sets(item, include=headDeformerName + "_FFDSet")
                cmds.parent(arrowCtrlGrp, self.headCtrl)

            cmds.parent(squashDefList[1], sideBendDefList[1],
                        frontBendDefList[1], twistDefList[1], offsetGrp)
            cmds.parent(offsetGrp, clusterGrp, latticeGrp, dataGrp)

            # try to integrate to Scalable_Grp
            for item in allTransformList:
                if cmds.objExists(item + ".masterGrp") and cmds.getAttr(
                        item + ".masterGrp") == 1:
                    scalableGrp = cmds.listConnections(item +
                                                       ".scalableGrp")[0]
                    cmds.parent(dataGrp, scalableGrp)
                    break

            # try to change deformers to get better result
            cmds.scale(1.25, 1.25, 1.25, offsetGrp)

            # colorize
            self.ctrls.colorShape(
                [arrowCtrl, centerSymmetryCtrl, topSymmetryCtrl], "cyan")

            # finish selection the arrow control
            cmds.select(arrowCtrl)
            print self.langDic[self.langName]["i179_addedHeadDef"],

        else:
            mel.eval("warning" + "\"" +
                     self.langDic[self.langName]["i034_notSelHeadDef"] + "\"" +
                     ";")
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File    : lattice_to_skin
# @Author  : cgpengda
# @Email   : [email protected]

import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
import maya.cmds as cmds

cmds.select('ffd1Lattice', r=1)
selectList = cmds.ls(sl=True)
latticeShape = cmds.listRelatives(selectList[0], type='lattice')[0]
ffd = cmds.listConnections(latticeShape, type='ffd')[0]
skincluster = cmds.listConnections(latticeShape, type='skinCluster')[0]
geometry = cmds.lattice(latticeShape, q=1, g=1)[0]
jointList = cmds.skinCluster(skincluster, q=1, inf=1)

# Geometry to Dag Path
meshMSelection = om.MSelectionList()
meshMSelection.add(geometry)
meshDagPath = meshMSelection.getDagPath(0)

# Get the mesh orgin position
mFnMesh = om.MFnMesh(meshDagPath)
geoPosition = mFnMesh.getPoints(om.MSpace.kObject)

# Get the weight from each joint
weightList = []
for index in range(len(jointList)):
예제 #43
0

def add_stetch_squash(sel):
    """
    @ add stretch squash controller. on selected poly objects.
    add lattice non linear etc etc.
    @ param sel(list): poly mesh objects list
    """
    if not sel:
        raise RuntimeError('Error:- no object to add stretch squash')


sel = cmds.ls(sl=True)
for each in sel:
    cmds.makeIdentity(each, apply=True, t=1, r=1, s=1, n=0)
    myLattice = cmds.lattice(each, dv=(6, 6, 6), oc=True)
    myGroup = cmds.createNode('transform', n=each + '_RG')
    cmds.parent(myLattice[1], myLattice[2], myGroup)
    cmds.hide(myGroup)
    myStretchSquash = cmds.nonLinear(each,
                                     typ='squash',
                                     lowBound=-1,
                                     highBound=1)
    squash = cmds.rename(myStretchSquash[0], 'squash_' + each)
    squashHandle = cmds.rename(myStretchSquash[1],
                               'squash_' + each + '_handle')
    myGroup = cmds.createNode('transform', n='_RG')
    cmds.parent(squashHandle, myGroup)
    cmds.hide(myGroup)
    myCluster = cmds.cluster(each)
    ctrlGrp = cmds.createNode('transform', n=each + '_grp')
예제 #44
0
def latt(*args):
	cmds.lattice(divisions=[2,2,2], objectCentered=True, ldv=[2,2,2])