def ik_stretch(ikhnd):
    '''

    '''
    jts = cmds.ikHandle(ikhnd, q=True, jl=True)
    cu_s = cmds.ikHandle(ikhnd, q=True, c=True)
    cu = cmds.listRelatives(cu_s, p=1)[0]
    cmds.addAttr(ikhnd, longName='ik_stretch', k=1, defaultValue=1.0, minValue=0.0, maxValue=1.)

    dcu = cmds.duplicate(cu, n=cu + '_base_scale')[0]
    dcu_s = cmds.listRelatives(dcu, c=1)[0]

    cf = cmds.createNode('curveInfo')
    dcf = cmds.createNode('curveInfo')
    bl = cmds.createNode('blendTwoAttr')
    md = cmds.createNode('multiplyDivide')

    cmds.connectAttr(cu_s + '.worldSpace', cf + '.inputCurve')
    cmds.connectAttr(dcu_s + '.worldSpace', dcf + '.inputCurve')
    cmds.connectAttr(dcf + '.arcLength', bl + '.input[0]')
    cmds.connectAttr(cf + '.arcLength', bl + '.input[1]')
    cmds.connectAttr(ikhnd + '.ik_stretch', bl + '.attributesBlender')
    cmds.connectAttr(bl + '.output', md + '.input1X')

    cmds.setAttr(md + '.input2X', cmds.getAttr(cf + '.arcLength'), l=1)
    cmds.setAttr(md + '.operation', 2)
    cmds.setAttr(dcu + '.v', 0)

    for j in jts:
        cmds.connectAttr(md + '.outputX', j + '.sx')

    return dcu
Beispiel #2
0
def addDefaultAttrState(objList):
	'''
	Add a default attribute state multi attribute that will be used to store specified attribute values which can be restored on command.
	@param objList: List of objects to add the default attribute state multi attribute to.
	@type objList: list
	'''
	# Check objList
	if not objList: return
	
	# Define defaultAttrState attribute name
	defAttr = 'defaultAttrState'
	
	# For each object in list
	attrList = []
	for obj in objList:
		
		# Check Object
		if not mc.objExists(obj):
			raise Exception('Object "'+obj+'" does not exist!')
		
		# Check Attr
		if not mc.attributeQuery(defAttr,n=obj,ex=True):
		
			# Add attribute
			mc.addAttr(obj,ln=defAttr,dv=-1,m=True)
			attrList.append(obj+'.'+defAttr)
			
		else:
			
			print ('Object "'+obj+'" already has a "'+defAttr+'" attribute! Skipping...')
	
	# Return Result
	return attrList
Beispiel #3
0
 def __init__(self, targets, base ):
     
     targets.append( base )
     
     self._mainBlendShape = cmds.blendShape( *targets, n= base+'_mainBlendShape' )[0]
     
     cmds.addAttr( self._mainBlendShape, ln='isMainBlendShape', at='bool' )
Beispiel #4
0
    def _create_functionality(self):
        ctl = self.get_control(0)
        attrs = ['heel', 'ball', 'tip', 'bankIn', 'bankOut']
        for attr in attrs:
            cmds.addAttr(ctl.ctl, ln=attr, at="double", min=-10, max=10)
            cmds.setAttr("%s.%s" % (ctl.ctl, attr), cb=True)
            cmds.setAttr("%s.%s" % (ctl.ctl, attr), k=True)

        # Standard connections
        self.range_detail = {}
        for attr in attrs:
            sr = cmds.createNode("setRange", name=name.create_name(self.position, self.description, 0, "%sRange" % attr))
            self.range_detail[attr] = sr

            # Create settings node connections
            for settings_attr in ['minX', 'maxX', 'oldMinX', 'oldMaxX']:
                titled_attr = re.sub('([a-zA-Z])', lambda k: k.groups()[0].upper(), settings_attr, 1)
                settings_full_attr = "%s.%s%s" % (self.setup_node, attr, titled_attr)
                cmds.addAttr(self.setup_node, ln="%s%s" % (attr, titled_attr), at="double")
                cmds.setAttr(settings_full_attr, cb=True)
                cmds.setAttr(settings_full_attr, k=True)

                cmds.connectAttr(settings_full_attr, "%s.%s" % (sr, settings_attr))

        # Load settings for part
        if self.settings_file:
            log.debug("Settings file found! Loading...")
            key = os.path.splitext(os.path.basename(self.part_file))[0]
            data = SettingsFileHandler(key).read()
            for full_attr, value in data.items():
                if cmds.objExists(full_attr):
                    cmds.setAttr(full_attr, value)
        else:
            log.warning("No settnings file found, please create before continuing.")
Beispiel #5
0
def switch(node,attr,value=0,inputNames=list(),inputValues=list()):
    '''
    :param node:
    :param attr:
    :param value:
    :param inputName:
    :param inputValues:
    :return:
    '''

    attrName = "{0}.{1}".format(node,attr)
    choiceName = "{0}_{1}_switch".format(node,attr)
    cmds.createNode("choice",name=choiceName)
    cmds.addAttr(node,ln=attr,at="enum",en=":".join(inputNames),dv=value,keyable=True)

    for i in range(len(inputValues)):
        choiceAttr = "output{0}".format(i)
        cmds.addAttr(choiceName,ln=choiceAttr,at="double3")
        cmds.addAttr(choiceName,ln="{0}x".format(choiceAttr),at="double",p=choiceAttr,dv=inputValues[i][0])
        cmds.addAttr(choiceName,ln="{0}y".format(choiceAttr),at="double",p=choiceAttr,dv=inputValues[i][1])
        cmds.addAttr(choiceName,ln="{0}z".format(choiceAttr),at="double",p=choiceAttr,dv=inputValues[i][2])

        cmds.connectAttr("{0}.{1}".format(choiceName,choiceAttr),"{0}.input[{1}]".format(choiceName,i))

    cmds.connectAttr(attrName,"{0}.selector".format(choiceName),f=True)

    return "{0}.output".format(choiceName)
def addScalePP(particle):
    """
    Add a per particle vector(Array) attribute named "scalePP", to the specified particle object.
    An initial state attribute "scalePP0" will also be created.
    @param particle: The particle or nParticle object to add the attribute to
    @type particle: str
    """
    # Check Particle
    if not cmds.objExists(particle):
        raise Exception('Particle "' + particle + '" does not exist!')
    if cmds.objectType(particle) == 'transform':
        particleShape = cmds.listRelatives(particle, s=True)
        if not particleShape:
            raise Exception('Unable to determine particle shape from transform "' + particle + '"!')
        else:
            particle = particleShape[0]
    if (cmds.objectType(particle) != 'particle') and (cmds.objectType(particle) != 'nParticle'):
        raise Exception('Object "' + particle + '" is not a valid particle or nParticle object!')

    # Add rotatePP attribute
    if not cmds.objExists(particle + '.scalePP0'):
        cmds.addAttr(particle, ln='scalePP0', dt='vectorArray')
    if not cmds.objExists(particle + '.scalePP'):
        cmds.addAttr(particle, ln='scalePP', dt='vectorArray')

    # Return Result
    return particle + '.scalePP'
Beispiel #7
0
 def stampCompiled(self, audioNodes):
     '''
     Used by the compiler - stamp the audioNodes from which this audio
     track was compiled from
     '''
     cmds.addAttr(self.audioNode, longName='compiledAudio', dt='string')
     cmds.setAttr('%s.compiledAudio' % self.audioNode, ','.join(audioNodes), type="string")
Beispiel #8
0
 def addAttr( target, **options ):
 
     items = options.items()
     
     attrName = ''
     channelBox = False
     keyable = False
     for key, value in items:
         if key in ['ln', 'longName']:
             attrName = value
         elif key in ['cb', 'channelBox']:
             channelBox = True
             options.pop( key )
         elif key in ['k', 'keyable']:
             keyable = True 
             options.pop( key )
     
     if cmds.attributeQuery( attrName, node=target, ex=1 ): return None
     
     cmds.addAttr( target, **options )
     
     if channelBox:
         cmds.setAttr( target+'.'+attrName, e=1, cb=1 )
     elif keyable:
         cmds.setAttr( target+'.'+attrName, e=1, k=1 )
Beispiel #9
0
def copy_user_attr(selparentshapes, seltargetshapes, copyUV=True):
    listattrvalue = {}
    listdatatype = {}
    userattr = cmds.listAttr(selparentshapes, ud=True)
    if copyUV and cmds.nodeType(seltargetshapes) == 'mesh' and cmds.nodeType(selparentshapes) == 'mesh':
            cmds.transferAttributes(selparentshapes, seltargetshapes, transferUVs=1, transferColors=2, searchMethod=3, sampleSpace=5, flipUVs=False)
    if userattr:
        for attr in userattr:
            nodetype = cmds.nodeType(selparentshapes)
            checkrendershape = cmds.getAttr(selparentshapes + '.intermediateObject')
            if checkrendershape != 1 or nodetype != 'mesh':
                key = attr
                value = cmds.getAttr("%s.%s" % (selparentshapes, key))
                data = cmds.getAttr("%s.%s" % (selparentshapes, key), typ=True)
                listattrvalue[key] = value
                listdatatype[key] = data
    checkrendershape = cmds.getAttr(seltargetshapes + '.intermediateObject')
    if checkrendershape != 1:
        for key in listattrvalue:
            if not cmds.attributeQuery(key, node=seltargetshapes, ex=True):
                if listdatatype[key] == 'string':
                    cmds.addAttr(seltargetshapes, longName=key, dataType=listdatatype[key])
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                else:
                    cmds.addAttr(seltargetshapes, longName=key)
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
            else:
                cmds.warning('Attribute ' + key + ' already on ' + seltargetshapes)
                if cmds.getAttr("%s.%s" % (seltargetshapes, key), se=True):
                    if listdatatype[key] == 'string':
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                    else:
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
Beispiel #10
0
def create_base_rig(cog, rig_region_name):
    # create curve and scale it to the correct size
    base_curve, base_curve_group = jt_ctl_curve.create(None, 'star_30')
    cmds.select(base_curve)
    cmds.setAttr(base_curve + '.scale', 5,5,5)
    cmds.makeIdentity(apply=True, t=0, r=1, s=1, n=0)

    # unparent the curve from the default group it is given so its a child of the world
    base_curve = cmds.rename('base')
    cmds.parent(w=True)
    cmds.select(base_curve_group, r=True)
    cmds.delete()

    # add a string attribute to keep track of all the nodes that are used for easy de-rigging
    # NOTE: text is stored in the attr as a string formatted like a python dict with the key being
    # the name of the body region and the value being a list of the nodes involved this makes 
    # de-rigging nice and easy as you just need to find the entry in the dict and delete all the nodes

    cmds.select(base_curve)
    cmds.addAttr(ln='rig_nodes', dt='string')
    cmds.setAttr(base_curve + '.rig_nodes', '{}', type='string')

    # add base_curve to base curve attr list
    add_node_to_rig_nodes(base_curve, 'base', base_curve)

    # update ui base_curve_field
    cmds.textField('jt_autorig_base_name_select_text', e=True, tx=base_curve)
Beispiel #11
0
def addRmanPrimVar(mesh,attrName,attrType='float',paintable=False):
	'''
	'''
	# Prefix attr
	attr = 'rmanF'+attrName
	
	# Data type
	if attrType == 'float': dataType = 'doubleArray'
	if attrType == 'vector': dataType = 'vectorArray'
	if attrType == 'string': dataType = 'stringArray'
	
	# Check mesh
	if not glTools.utils.mesh.isMesh(mesh):
		raise Exception('Mesh "'+mesh+'" does not exist!!')
	
	# Check attr
	if mc.objExists(mesh+'.'+attr):
		raise Exception('Attribute "'+mesh+'.'+attr+'" already exists!!')
	
	# Get shape
	meshShape = mc.listRelatives(mesh,s=True,ni=True,pa=True)
	if not meshShape:
		raise Exception('Unable to determine shape for mesh "'+mesh+'"!!')
	
	# Add attribute
	mc.addAttr(meshShape[0],ln=attr,dt=dataType)
	
	# Make paintable
	if paintable: mc.makePaintable('mesh',attr,attrType=dataType)
def save_scene(search_key, context, description, all_process):

    # add info about particular scene
    skey_link = 'skey://{0}&context={1}'.format(search_key, context)
    if not cmds.attributeQuery('tacticHandler_skey', node='defaultObjectSet', exists=True):
        cmds.addAttr('defaultObjectSet', longName='tacticHandler_skey', dataType='string')
    cmds.setAttr('defaultObjectSet.tacticHandler_skey', skey_link, type='string')

    # get template names for scene and playblast image
    temp_dir = env.Env().get_temp_dir()
    random_uuid = uuid.uuid4()

    types = {
        'mayaBinary': 'mb',
        'mayaAscii': 'ma',
    }
    temp_file = '{0}/{1}.ma'.format(temp_dir, random_uuid)
    temp_playblast = '{0}/{1}.jpg'.format(temp_dir, random_uuid)

    # rename file, save scene, playblast, get saving format
    cmds.file(rename=temp_file)
    cmds.file(save=True, type='mayaAscii')
    current_frame = cmds.currentTime(query=True)
    cmds.playblast(
        forceOverwrite=True,
        format='image',
        completeFilename=temp_playblast,
        showOrnaments=False,
        widthHeight=[960, 540],
        sequenceTime=False,
        frame=[current_frame],
        compression='jpg',
        offScreen=True,
        viewer=False,
        percent=100
    )

    # check in snapshot
    snapshot = tc.checkin_snapshot(search_key, context, temp_file, file_type='maya', is_current=True,
                                   description=description)

    # from pprint import pprint
    # pprint(snapshot)
    # retrieve checked in snapshot file info
    asset_dir = env.Env().get_asset_dir()
    file_sobject = snapshot['__file_sobjects__'][0]
    relative_dir = file_sobject['relative_dir']
    file_name = file_sobject['file_name']

    # make proper file path, and dir path to set workspace
    new_file = '{0}/{1}/{2}'.format(asset_dir, relative_dir, file_name)
    split_path = relative_dir.split('/')
    dir_path = '{0}/{1}'.format(asset_dir, '{0}/{1}/{2}'.format(*split_path))
    set_workspace(dir_path, all_process)

    # check in playblast
    tc.checkin_playblast(snapshot['code'], temp_playblast)

    # set proper scene name
    cmds.file(rename=new_file)
def add_wf_mat_name_attr(*args):
	r'''addes a material name attribute of WFMaterialName based on diffuse file connection
	'''
	mat_pairs=[]
	mats = cmds.ls(mat=True)
	for mat in mats:
		_file = cmds.listConnections('%s.color' % mat)
		if _file :
				tex_path =  cmds.getAttr(_file[0] + '.fileTextureName')
				idx = tex_path.lower().find('assets') 
				if idx != -1:
					new_name = '/' + tex_path[idx+7:-6]
					attr_list = cmds.listAttr(mat)
					if not ('WFMaterialName' in attr_list):
						print 'Attribute not in list, making attribute' 
						cmds.addAttr(mat, dt="string", ln="WFMaterialName")
						
					cmds.setAttr(mat + '.WFMaterialName', new_name, type="string" )
					# print ([mat, new_name])
					mat_pairs.append([mat, new_name])
		

				else:
					print 'Material: \n  %s' % mat
					print 'String \"assets\" does not exist in the path\n  %s' % tex_path
	return mat_pairs
Beispiel #14
0
    def cleanup(self, version = 2.0):
        #hide groups and lock attributes
        cmds.setAttr(self.negativeBshpesGrp + ".v", 0)
        cmds.setAttr(self.resultBshpesGrp + ".v", 0)

        for i in cmds.ls(self.eTools, self.engineersToolsGrp, self.doNotTouchGrp, self.shotFinalGrp, self.mainBshpesGrp, self.negativeBshpesGrp, self.sculptBshpesGrp, self.resultBshpesGrp, "*Negative*", "*Sculpt*", "*Result*"):
            try:
                for axis in "xyz":
                    cmds.setAttr(i + ".t" + axis, lock = 1, keyable = 0)
                    cmds.setAttr(i + ".r" + axis, lock = 1, keyable = 0)
                    cmds.setAttr(i + ".s" + axis, lock = 1, keyable = 0)
                cmds.setAttr(i + ".v", keyable = 0)
                cmds.setAttr(i + ".ihi", 0)
            except:
                pass

        #hide isHistoricallyInteresting
        for i in cmds.ls("blendShape*", "tweak*"):
            cmds.setAttr(i + ".ihi", 0)


        #add versionNumber of the SHOTFINAL script
        if not cmds.objExists(self.engineersToolsGrp + ".version"):
            cmds.addAttr(self.engineersToolsGrp, longName = "version", shortName = "version", attributeType = "float", keyable = 1)
            cmds.setAttr(self.engineersToolsGrp + ".version", version, edit  = 1, channelBox = 1, lock = 1)


        #select the engineersTools group
        cmds.select(self.sculptTools)
Beispiel #15
0
	def connect( self, obj, slot=None ):
		'''
		performs the actual connection of an object to a connect slot
		'''
		if not cmd.objExists(obj):
			return -1

		#if the user is trying to connect the trigger to itself, return zero which is the reserved slot for the trigger
		if apiExtensions.cmpNodes( self.obj, obj ):
			return 0

		if slot is None:
			slot = self.nextSlot()

		if slot <= 0:
			return 0

		#make sure the connect isn't already connected - if it is, return the slot number
		existingSlots = self.isConnected(obj)
		if existingSlots:
			return self.getConnectSlots(obj)[0]

		conPrefix = 'zooTrig'
		prefixSize = len(conPrefix)

		slotPath = "%s.%s%d" % (self.obj, conPrefix, slot)
		if not objExists( slotPath ):
			cmd.addAttr(self.obj,ln= "%s%d" % (conPrefix, slot), at='message')

		cmd.connectAttr( "%s.msg" % obj, slotPath, f=True )
		self.cacheConnect( slot )

		return slot
Beispiel #16
0
    def add_target(self, name):
        cmds.select(self.main_jnt)
        jnt = cmds.joint(name=self.name + "_" + name + "_target_jnt")
        cmds.setAttr(jnt + ".t" + self.axis, 1.0)
        cmds.addAttr(jnt, ln="cone_angle", at="double", keyable=1, maxValue=360, minValue=0)
        cmds.addAttr(jnt, ln="pose_weight", at="double")

        norm_vp = cmds.createNode("vectorProduct", name=self.name + "_" + name + "normalize_vp")
        cmds.connectAttr(jnt + ".t", norm_vp + ".input1")
        cmds.setAttr(norm_vp + ".normalizeOutput", 1)
        cmds.setAttr(norm_vp + ".operation", 0)

        dot_vp = cmds.createNode("vectorProduct", name=self.name + "_" + name + "dot_vp")
        cmds.connectAttr(norm_vp + ".output", dot_vp + ".input1")
        cmds.connectAttr(self.reader_jnt + ".t", dot_vp + ".input2")
        cmds.setAttr(dot_vp + ".normalizeOutput", 1)

        angle_rv = cmds.createNode("remapValue", name=self.name + "_" + name + "_angle_rv")
        cmds.connectAttr(jnt + ".cone_angle", angle_rv + ".inputValue")
        cmds.setAttr(angle_rv + ".value[0].value_FloatValue", 1)
        cmds.setAttr(angle_rv + ".value[1].value_FloatValue", -1)
        cmds.setAttr(angle_rv + ".inputMax", 360.0)

        rv = cmds.createNode("remapValue", name=self.name + "_" + name + "_rv")
        # cmds.connectAttr(jnt + '.cone_angle', rv + '.value[0].value_Position')
        cmds.connectAttr(angle_rv + ".outValue", rv + ".value[0].value_Position")
        cmds.connectAttr(dot_vp + ".outputX", rv + ".inputValue")
        cmds.connectAttr(rv + ".outValue", jnt + ".pose_weight")
Beispiel #17
0
	def add(self,objectList):
		'''
		Adds the channel state attr to all specified objects
		@param objectList: List of objects to add flags to
		@type objectList: list
		'''
		# Add Channel State Attrs
		for obj in objectList:
			
			# Check obj
			if not mc.objExists(obj):
				raise Exception('Object "'+obj+'" does not exist!')
			if not glTools.utils.transform.isTransform(obj):
				raise Exception('Object "'+obj+'" is not a valid transform!')
			if mc.objExists(obj+'.channelState'):
				print ('Object "'+obj+'" already has a "channelState" attribute! Skipping...')
			
			# Add channelState attr
			#mc.addAttr(obj,ln='channelState',at='enum',en=':Keyable:NonKeyable:Locked:',m=1,dv=-1)
			mc.addAttr(obj,ln='channelState',at='enum',en=':Keyable:NonKeyable:Locked:',m=1)
			
			# Set channelState flag values
			for i in range(len(self.channel)):
				if mc.getAttr(obj+'.'+self.channel[i],l=1):
					# Set Locked State
					mc.setAttr(obj+'.channelState['+str(i)+']',2)
				elif not mc.getAttr(obj+'.'+self.channel[i],k=1):
					# Set NonKeyable State
					mc.setAttr(obj+'.channelState['+str(i)+']',1)
				else:
					# Set Keyable State
					mc.setAttr(obj+'.channelState['+str(i)+']',0)
				# Alias Attribute
				mc.aliasAttr(self.channel[i]+'_state',obj+'.channelState['+str(i)+']')
Beispiel #18
0
 def __add_root_attributes(self):
     #--- globalScale
     if not cmds.objExists(self.root + ".globalScale"):
         cmds.addAttr(self.root, longName="globalScale",
                      min=0, defaultValue=1, attributeType='float')
         cmds.setAttr(self.root + '.globalScale',
                      edit=True, keyable=False, channelBox=True)
     #--- project
     if not cmds.objExists(self.root + ".project"):
         cmds.addAttr(self.root, longName="project", dataType='string')
         cmds.setAttr(self.root + '.project', self.assetInfo[0],
                      type='string', lock=True)
     #--- assetType
     if not cmds.objExists(self.root + ".assetType"):
         cmds.addAttr(self.root, longName="assetType", dataType='string')
         cmds.setAttr(self.root + '.assetType', self.assetInfo[1],
                      type='string', lock=True)
     #--- assetResolution
     if not cmds.objExists(self.root + ".assetResolution"):
         cmds.addAttr(self.root, longName="assetResolution", dataType='string')
         cmds.setAttr(self.root + '.assetResolution', self.assetInfo[2],
                      type='string', lock=True)
     #--- assetName
     if not cmds.objExists(self.root + ".assetName"):
         cmds.addAttr(self.root, longName="assetName", dataType='string')
         cmds.setAttr(self.root + '.assetName', self.assetInfo[3],
                      type='string', lock=True)
Beispiel #19
0
 def __cleanup(self, version = 2.0):
     #--- hide groups and lock attributes
     cmds.setAttr(self.negative_grp + '.v', 0)
     cmds.setAttr(self.result_grp + '.v', 0)
     sf_objs = cmds.ls(self.sf_tool, self.blendshapes, self.shotfinaling,
                      self.mesh_bsp_grp, self.mesh_shotfinal_grp,
                      self.negative_grp, self.sculpt_grp, self.result_grp,
                      '*Negative*', '*Sculpt*', '*Result*', type = 'transform')
     for i in sf_objs:
         for axis in 'xyz':
             cmds.setAttr(i + '.t' + axis, lock = 1, keyable = 0)
             cmds.setAttr(i + '.r' + axis, lock = 1, keyable = 0)
             cmds.setAttr(i + '.s' + axis, lock = 1, keyable = 0)
         cmds.setAttr(i + '.v', keyable = 0)
         cmds.setAttr(i + '.ihi', 0)
     #--- hide isHistoricallyInteresting
     to_ihi = cmds.ls('*BSP*', '*Bshpe*', '*tweak*', '*Shape*')
     for i in sf_objs:
         to_ihi.append(i)
     for i in to_ihi:
         cmds.setAttr(i + '.ihi', 0)
     #--- add versionNumber of the SHOTFINAL script
     if not cmds.objExists(self.shotfinaling + '.version'):
         cmds.addAttr(self.shotfinaling,
                      longName = 'version',
                      shortName = 'version',
                      attributeType = 'float',
                      keyable = True)
         cmds.setAttr(self.shotfinaling + '.version',
                      version,
                      edit  = True,
                      channelBox = True,
                      lock = True)
     #--- select the sculpt tool
     cmds.select(self.sculpt_tool)
Beispiel #20
0
	def combine(self, objs=[], new_name="", keepHistory=0):
		'''
		Combines the geometry and stores the names.
		This is useful for speeding up the rigs and seperating in a predictible way.
		@param objs: Mesh objects to combine
		@type objs: list
		@param new_name: New name for the combined mesh
		@type new_name: str
		@param keepHistory: Maintain history after function has completed
		@type keepHistory: bool
		'''
		# Check input arguments
		if not objs:
			raise Exception('Input list "objs" is not a valid list!')
		for obj in objs:
			if not mc.objExists(obj):
				raise Exception('Object '+obj+' does not exist!')
		if mc.objExists(new_name):
			raise Exception('An object of name '+new_name+' already exists! Please choose another name!')
		
		# Combine multiple mesh objects to a single mesh
		new_obj = mc.polyUnite(objs, n=new_name)
		mc.addAttr( new_obj[0], ln='origNames', dt='string', multi=True)
		# Recond original names list on new mesh transform
		for i in range(len(objs)):
			mc.setAttr( new_obj[0]+'.origNames['+str(i)+']', objs[i], type='string')
		# Delete history
		if not keepHistory : mc.delete(new_obj[1])
		mc.delete(objs)
		
		return new_obj[0]
Beispiel #21
0
def add_long(node, kwargs):
    """Long attribute"""
    attr = kwargs["ln"]
    if _safe_attr(node, attr):
        full = "%s.%s" % (node, attr)
        cmds.addAttr(node, **kwargs)
    return full
Beispiel #22
0
def pyToAttr(objAttr, data):
	"""
	Write (pickle) Python data to the given Maya obj.attr.  This data can
	later be read back (unpickled) via attrToPy().

	Arguments:
	objAttr : string : a valid object.attribute name in the scene.  If the
		object exists, but the attribute doesn't, the attribute will be added.
		The if the attribute already exists, it must be of type 'string', so
		the Python data can be written to it.
	data : some Python data :  Data that will be pickled to the attribute
		in question.
	"""
	obj, attr = objAttr.split('.')
	# Add the attr if it doesn't exist:
	if not cmds.objExists(objAttr):
		cmds.addAttr(obj, longName=attr, dataType='string')
	# Make sure it is the correct type before modifing:
	if cmds.getAttr(objAttr, type=True) != 'string':
		raise Exception("Object '%s' already has an attribute called '%s', but it isn't type 'string'"%(obj,attr))

	# Pickle the data and return the coresponding string value:
	stringData = cPickle.dumps(data)
	# Make sure attr is unlocked before edit:
	cmds.setAttr(objAttr, edit=True, lock=False)
	# Set attr to string value:
	cmds.setAttr(objAttr, stringData, type='string')
	# And lock it for safety:
	cmds.setAttr(objAttr, edit=True, lock=True)
Beispiel #23
0
 def _create_meta_data(self):
     """
     Creates a network node to hold the meta data for the rig.
     """
     network_node = cmds.createNode("network")
     meta_node_name = self._get_unique_name("metaNode", "DyMETA")
     meta_node = cmds.rename(network_node, meta_node_name)
     data = {
             "rootGroup" : self.root_group,
             "rigName" : self.rig_name,
             "parentControl" : self.parent_control,
             "controls" : self.controls,
             "pointLock" : self.point_lock,
             "startFrame" : self.start_frame,
             "endFrame" : self.end_frame,
             "dynamicControl" : self.dynamic_control,
             "metaNode" : meta_node,
             "hairSystem" : self.hair_system}
     # build data
     for meta, data in data.iteritems():
         if meta == "controls":
             cmds.addAttr(meta_node, dt="stringArray", ln=meta)
             cmds.setAttr("{0}.{1}".format(meta_node, meta),
                          *([len(data)]+data), type="stringArray")
             continue
         cmds.addAttr(meta_node, dt="string", ln=meta)
         cmds.setAttr("{0}.{1}".format(meta_node, meta),
                      data, type="string")
Beispiel #24
0
def createAssetSetFromSelect(name = 'asset1', type = ''):
    asset = mc.sets(name = "%s" % name)
    mc.addAttr(asset, longName = 'asset', niceName = "Asset", dataType = 'string')
    mc.addAttr(asset, longName = 'type', niceName = "Type", dataType = 'string')
    mc.setAttr("%s.asset" % asset, name, type = "string")
    mc.setAttr("%s.type" % asset, type, type = "string")
    return asset
Beispiel #25
0
def addSymEdgeAttr(edge):
	'''
	Add mesh symmetry edge attribute based on specified mesh edge.
	@param edge: Mesh edge that defined the center edge row of a symmetrical mesh
	@type edge: str
	'''
	# Check Edge
	edge = mc.filterExpand(edge,ex=True,sm=32) or []
	if not edge:
		raise Exception('No valid mesh edge selected!')
	if len(edge) > 1:
		print('Multiple mesh edges found! Using first edge only ("'+edge[0]+'").')
	edge = edge[0]
	
	# Get Edge Mesh
	mesh = mc.ls(edge,o=True) or []
	if not mesh:
		raise Exception('Unable to determine mesh from edge!')
	if len(mesh) > 1:
		print('Multiple mesh objects found from edge!')
	mesh = mesh[0]
	
	# Get Edge ID
	edgeID = glTools.utils.component.index(edge)
	
	# Add Attribute
	symAttr = 'symmetryEdgeId'
	if not mc.objExists(mesh+'.'+symAttr):
		mc.addAttr(mesh,ln=symAttr,at='long',min=0,dv=edgeID)
	mc.setAttr(mesh+'.'+symAttr,edgeID)
	
	# Return Result
	return mesh+'.'+symAttr
def rsChangeCheck(i_b_state, i_s_floatField):
    if i_s_floatField == "rsMinField":
        i_b_state = cmds.checkBox("rsMinBox", query=True, value=True)
    else:
        i_b_state = cmds.checkBox("rsMaxBox", query=True, value=True)
    l_oSels = rsObjList()
    if i_b_state == True:
        if i_s_floatField == "rsMinField":
            b_minimum = cmds.attributeQuery(l_oSels[1], node=l_oSels[0], minExists=True)
            f_atValue = 0.0
            if b_minimum == 1:
                f_atValue = (cmds.attributeQuery(l_oSels[1], node=l_oSels[0], minimum=True))[0]
            else:
                cmds.addAttr(l_oSels[2], edit=True, hasMinValue=True)
        if i_s_floatField == "rsMaxField":
            b_maximum = cmds.attributeQuery(l_oSels[1], node=l_oSels[0], maxExists=True)
            f_atValue = 1.0
            if b_maximum == 1:
                f_atValue = (cmds.attributeQuery(l_oSels[1], node=l_oSels[0], maximum=True))[0]
            else:
                cmds.addAttr(l_oSels[2], edit=True, hasMaxValue=True)
                cmds.addAttr(l_oSels[2], edit=True, maxValue=f_atValue)
        cmds.floatField(i_s_floatField, edit=True, value=f_atValue, enable=True)
    else:
        cmds.floatField(i_s_floatField, edit=True, value=0, enable=False)
        if i_s_floatField == "rsMinField":
            cmds.addAttr(l_oSels[2], edit=True, hasMinValue=False)
        else:
            cmds.addAttr(l_oSels[2], edit=True, hasMaxValue=False)
    return True
def rsChName(i_s_textField, s_name):
    l_oSels = rsObjList()
    i_LockState = cmds.getAttr(l_oSels[2], lock=True)
    if i_LockState:
        cmds.setAttr(l_oSels[2], lock=False)
    if s_name == "NewName":
        s_NewName = l_oSels[0] + "." + i_s_textField
        cmds.renameAttr(l_oSels[2], i_s_textField)
        if i_LockState:
            cmds.setAttr(s_NewName, lock=True)
        s_search = i_s_textField
    else:
        cmds.addAttr(l_oSels[2], edit=True, niceName=i_s_textField)
        if i_LockState:
            cmds.setAttr(l_oSels[2], lock=True)
        s_search = l_oSels[1]
    l_ChannelAtList = rsChannelAtList()
    l_AttrKey = l_ChannelAtList[0]
    l_AttrKeyHidden = l_ChannelAtList[1]
    if l_AttrKey or l_AttrKeyHidden:
        cmds.textScrollList("rsAttributeScroll", edit=True, removeAll=True, append=l_AttrKey)
        cmds.textScrollList("rsAttributeScrollHidden", edit=True, removeAll=True, append=l_AttrKeyHidden)
    cmds.select(cl=True)
    cmds.select(l_oSels[0], r=True)
    rsSearchInScroll(s_search)
    return True
 def addIdAttr(self,*args):
     selList = self.listSelected()
     meshList = self.getMeshList(selList)
     # add attribute to selected meshes
     for mesh in meshList:
         if not mc.objExists(mesh+'.'+self.idGroupAttr):
             mc.addAttr(mesh,ln = self.idGroupAttr,sn = self.idGroupAttr,at = "long",dv = -1)
Beispiel #29
0
 def createGuide(self, *args):
     Base.StartClass.createGuide(self)
     # Custom GUIDE:
     cmds.addAttr(self.moduleGrp, longName="flip", attributeType='bool')
     cmds.setAttr(self.moduleGrp+".flip", 0)
     
     cmds.addAttr(self.moduleGrp, longName="indirectSkin", attributeType='bool')
     cmds.setAttr(self.moduleGrp+".indirectSkin", 0)
     
     cmds.setAttr(self.moduleGrp+".moduleNamespace", self.moduleGrp[:self.moduleGrp.rfind(":")], type='string')
     
     self.cvJointLoc, shapeSizeCH = ctrls.cvJointLoc(ctrlName=self.guideName+"_JointLoc1", r=0.3)
     self.connectShapeSize(shapeSizeCH)
     self.jGuide1 = cmds.joint(name=self.guideName+"_JGuide1", radius=0.001)
     cmds.setAttr(self.jGuide1+".template", 1)
     cmds.parent(self.jGuide1, self.moduleGrp, relative=True)
     
     self.cvEndJoint, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.1)
     self.connectShapeSize(shapeSizeCH)
     cmds.parent(self.cvEndJoint, self.cvJointLoc)
     cmds.setAttr(self.cvEndJoint+".tz", 1.3)
     self.jGuideEnd = cmds.joint(name=self.guideName+"_JGuideEnd", radius=0.001)
     cmds.setAttr(self.jGuideEnd+".template", 1)
     cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
     ctrls.setLockHide([self.cvEndJoint], ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
     
     cmds.parent(self.cvJointLoc, self.moduleGrp)
     cmds.parent(self.jGuideEnd, self.jGuide1)
     cmds.parentConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_ParentConstraint")
     cmds.parentConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_ParentConstraint")
     cmds.scaleConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_ScaleConstraint")
     cmds.scaleConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_ScaleConstraint")
Beispiel #30
0
	def updateOrigNamesFormat(self,objectList=[]):
		'''
		Update a combined meshes origNames attribute to the newest format.
		@param objectList: list of mesh objects to update origNames attribute on.
		@type objectList: list
		'''
		# Confirm list
		if type(objectList) == str:
			objectList = [objectList]
		
		# Iterate through object list
		for obj in objectList:
			
			# Check origNames attribute
			if not mc.objExists(obj+'.origNames'):
				raise Exception('Object '+obj+' does not have a "origNames" attribute!')
			if mc.addAttr(obj+'.origNames',q=True,multi=True):
				print(obj+'.origNames is already in the correct format.')
				continue
			
			# Extract original names list from old format
			origNamesList = []
			index = 0
			while True:
				if mc.objExists(obj+'.origNames.origNames_'+str(index)):
					origNamesList.append(mc.getAttr(obj+'.origNames.origNames_'+str(index)))
					index+=1
				else: break
			
			# Re-create the origNames attribute in the new format
			mc.deleteAttr(obj+'.origNames')
			mc.addAttr(obj,ln='origNames',dt='string',multi=True)
			for i in range(len(origNamesList)):
				mc.setAttr( obj+'.origNames['+str(i)+']', origNamesList[i], type='string')
Beispiel #31
0
    def setupBlueprintWeightBasedBlending(self):
        settingsLocator = self.blueprintNamespace + ":SETTINGS"

        attributes = cmds.listAttr(settingsLocator, keyable=False)
        weightAttributes = []
        for attr in attributes:
            if attr.find("_weight") != -1:
                weightAttributes.append(attr)

        value = 0
        if len(weightAttributes) == 0:
            value = 1
            cmds.setAttr(settingsLocator + ".creationPoseWeight", 0)

        cmds.select(settingsLocator)
        weightAttributeName = self.moduleNamespace + "_weight"
        cmds.addAttr(ln=weightAttributeName,
                     at="double",
                     min=0,
                     max=1,
                     defaultValue=value,
                     keyable=False)

        cmds.container(self.blueprintNamespace + ":module_container",
                       edit=True,
                       publishAndBind=[
                           settingsLocator + "." + weightAttributeName,
                           weightAttributeName
                       ])

        currentEntries = cmds.attributeQuery("activeModule",
                                             n=settingsLocator,
                                             listEnum=True)

        newEntry = self.moduleNamespace

        if currentEntries[0] == "None":
            cmds.addAttr(settingsLocator + ".activeModule",
                         edit=True,
                         enumName=newEntry)
            cmds.setAttr(settingsLocator + ".activeModule", 0)
        else:
            cmds.addAttr(settingsLocator + ".activeModule",
                         edit=True,
                         enumName=currentEntries[0] + ":" + newEntry)

        utilityNodes = []
        for i in range(1, len(self.joints)):
            joint = self.joints[i]

            nameSuffix = utils.stripAllNamespaces(joint)[1]
            blueprintJoint = self.blueprintNamespace + ":blueprint_" + nameSuffix
            weightNodeAttr = settingsLocator + "." + weightAttributeName

            if i < len(self.joints) - 1 or len(self.joints) == 2:
                multiplyRotations = cmds.shadingNode(
                    "multiplyDivide",
                    n=joint + "_multiplyRotationsWeight",
                    asUtility=True)
                utilityNodes.append(multiplyRotations)
                cmds.connectAttr(joint + ".rotate",
                                 multiplyRotations + ".input1",
                                 force=True)

                for attr in ["input2X", "input2Y", "input2Z"]:
                    cmds.connectAttr(weightNodeAttr,
                                     multiplyRotations + "." + attr,
                                     force=True)

                index = utils.findFirstFreeConnection(blueprintJoint +
                                                      "_addRotations.input3D")
                cmds.connectAttr(
                    multiplyRotations + ".output", blueprintJoint +
                    "_addRotations.input3D[" + str(index) + "]")

            if i == 1:
                addNode = blueprintJoint + "_addTranslate"
                if cmds.objExists(addNode):
                    multiplyTranslation = cmds.shadingNode(
                        "multiplyDivide",
                        n=joint + "_multiplyTranslationWeight",
                        asUtility=True)
                    utilityNodes.append(multiplyTranslation)

                    cmds.connectAttr(joint + ".translate",
                                     multiplyTranslation + ".input1",
                                     force=True)
                    for attr in ["input2X", "input2Y", "input2Z"]:
                        cmds.connectAttr(weightNodeAttr,
                                         multiplyTranslation + "." + attr,
                                         force=True)

                    index = utils.findFirstFreeConnection(addNode + ".input3D")
                    cmds.connectAttr(multiplyTranslation + ".output",
                                     addNode + ".input3D[" + str(index) + "]",
                                     force=True)

                addNode = blueprintJoint + "_addScale"
                #I am removing the following lines to eliminate scale for now.
                if cmds.objExists(addNode):
                    multiplyScale = cmds.shadingNode("multiplyDivide",
                                                     n=joint +
                                                     "_multiplyScaleWeight",
                                                     asUtility=True)
                    utilityNodes.append(multiplyScale)

                    cmds.connectAttr(joint + ".scale",
                                     multiplyScale + ".input1",
                                     force=True)
                    for attr in ["input2X", "input2Y", "input2Z"]:
                        cmds.connectAttr(weightNodeAttr,
                                         multiplyScale + "." + attr,
                                         force=True)

                    index = utils.findFirstFreeConnection(addNode + ".input3D")
                    cmds.connectAttr(multiplyScale + ".output",
                                     addNode + ".input3D[" + str(index) + "]",
                                     force=True)

            else:
                multiplyTranslation = cmds.shadingNode(
                    "multiplyDivide",
                    n=joint + "_multiplyTranslationWeight",
                    asUtility=True)
                utilityNodes.append(multiplyTranslation)

                cmds.connectAttr(joint + ".translateX",
                                 multiplyTranslation + ".input1X",
                                 force=True)
                cmds.connectAttr(weightNodeAttr,
                                 multiplyTranslation + ".input2X",
                                 force=True)

                addNode = blueprintJoint + "_addTx"
                index = utils.findFirstFreeConnection(addNode + ".input1D")
                cmds.connectAttr(multiplyTranslation + ".outputX",
                                 addNode + ".input1D[" + str(index) + "]",
                                 force=True)

        return utilityNodes
Beispiel #32
0
    def create(self, renderMeshes=None, rootJoint=None, strName='uExport'):

        uExport = None

        if cmds.objExists(strName):

            #later re-hook up

            #set uExport

            pass

        else:

            uExport = cmds.group(em=1, name=strName)

            cmds.addAttr(uExport, ln='rendermesh', at='message')

            cmds.addAttr(uExport, ln='export_root', at='message')

            cmds.addAttr(uExport, ln='materials', at='message')

            cmds.addAttr(uExport, ln='uexport_ver', dt='string')

            cmds.setAttr(uExport + '.uexport_ver', '1.0', type='string')

            cmds.addAttr(uExport, ln='folder_path', dt='string')

            cmds.addAttr(uExport, ln='asset_name', dt='string')

            cmds.addAttr(uExport, ln='fbx_name', dt='string')

        if uExport:

            try:

                if renderMeshes:

                    self.connectRenderMeshes(uExport, renderMeshes, rewire=0)

                #rootJoint

                if rootJoint:

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

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

                    cmds.connectAttr(rootJoint + '.export',
                                     uExport + '.export_root')

                else:

                    cmds.warning('No root joint or could not find root: ' +
                                 str(rootJoint))

            except Exception as e:

                print cmds.warning(e)
Beispiel #33
0
def braidGen():
    allSel = cmds.ls(sl=1)
    for eachCurve in allSel:
        cmds.select(eachCurve)
        mel.eval('makeCurvesDynamic 2 { "1", "1", "1", "1", "0"}')
        #First Step nHair - Make Curves Dynamic
        follicle = cmds.listConnections(eachCurve)
        follicleShape = cmds.listRelatives(follicle[0], shapes=1)
        follicleBraid = follicleShape[0] + ".braid"
        follicleSampleDensity = follicleShape[0] + ".sampleDensity"
        cmds.setAttr(follicleBraid, 1)
        # Set Braid to be TRUE
        cmds.setAttr(follicleSampleDensity, 100)
        # Set SampleDensity to be smoother
        cmds.select(eachCurve)
        #print $follicleShape;
        hairSystem = cmds.listConnections(follicleShape[0], type='hairSystem')
        hairSystemShape = cmds.listRelatives(hairSystem[0], type='hairSystem')
        #string $hairSystemShape[] = `ls -type hairSystem`;
        for i in range(0, len(hairSystemShape)):
            if i != 0:
                hairSystemShape.pop(i)
        mainGroup = eachCurve + "_HairSystemGrp"
        #print $hairSystemShape;
        cmds.group(hairSystemShape[0], n=mainGroup)
        NucleusList = cmds.listConnections(hairSystemShape[0], type='nucleus')
        thisNucleus = NucleusList[0]
        cmds.parent(thisNucleus, mainGroup)
        cmds.select(eachCurve)
        hairSystemShapeLastNum = len(hairSystemShape)
        hairSystemShapeClumpCount = hairSystemShape[hairSystemShapeLastNum -
                                                    1] + ".hairsPerClump"
        hairSystemShapeClumpWidth = hairSystemShape[hairSystemShapeLastNum -
                                                    1] + ".clumpWidth"
        hairSystemShapeClumpTaper = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[1].clumpWidthScale_FloatValue"
        hairSystemShapeClumpFlatness = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpFlatness[0].clumpFlatness_FloatValue"
        hairSystemShapeClumpCount = hairSystemShape[hairSystemShapeLastNum -
                                                    1] + ".hairsPerClump"
        ClumpWidthScale_pos1 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[0].clumpWidthScale_Position"
        ClumpWidthScale_val1 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[0].clumpWidthScale_FloatValue"
        ClumpWidthScale_pos2 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[1].clumpWidthScale_Position"
        ClumpWidthScale_val2 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[1].clumpWidthScale_FloatValue"
        ClumpWidthScale_pos3 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[2].clumpWidthScale_Position"
        ClumpWidthScale_val3 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[2].clumpWidthScale_FloatValue"
        ClumpWidthScale_pos4 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[3].clumpWidthScale_Position"
        ClumpWidthScale_val4 = hairSystemShape[
            hairSystemShapeLastNum -
            1] + ".clumpWidthScale[3].clumpWidthScale_FloatValue"
        cmds.setAttr(ClumpWidthScale_pos1, 0)
        cmds.setAttr(ClumpWidthScale_val1, 0)
        cmds.setAttr(ClumpWidthScale_pos2, 0.001)
        cmds.setAttr(ClumpWidthScale_val2, 1)
        cmds.setAttr(ClumpWidthScale_pos3, 0.999)
        cmds.setAttr(ClumpWidthScale_val3, 1)
        cmds.setAttr(ClumpWidthScale_pos4, 0.999)
        cmds.setAttr(ClumpWidthScale_val4, 0)
        cmds.setAttr(hairSystemShapeClumpCount, 3)
        cmds.setAttr(hairSystemShapeClumpWidth, 3)
        mel.eval("AssignBrushToHairSystem;")
        pfxHair = cmds.listConnections(hairSystemShape[hairSystemShapeLastNum -
                                                       1])
        pfxHair_Size = len(pfxHair)
        pfxHairLast = pfxHair[pfxHair_Size - 1]
        cmds.parent(pfxHairLast, mainGroup)
        cmds.select(pfxHairLast)
        # select last one
        mel.eval("doPaintEffectsToCurve(1);")
        pfxHairStringCount = len(pfxHairLast)
        pfxHairLastNum = pfxHairLast[7:pfxHairStringCount]
        pfxHairShapeCurves = "pfxHairShape" + pfxHairLastNum + "Curves"
        cmds.parent(pfxHairShapeCurves, mainGroup)
        follicleConnectedCurve = cmds.listConnections(follicleShape[0],
                                                      type='nurbsCurve')
        for originCurve in follicleConnectedCurve:
            objects = cmds.ls(originCurve, l=1)
            parentList = []
            parentList = objects[0].split("|")
            cmds.parent(parentList[1], mainGroup)

        cmds.select(pfxHairShapeCurves)
        getList = ldmt_tubeGen.tubeGen(eachCurve)
        Tubes = cmds.ls(sl=1)
        cmds.select(eachCurve)
        Tube0_LengthDiv = Tubes[0] + ".lengthDivisions"
        Tube1_LengthDiv = Tubes[1] + ".lengthDivisions"
        Tube2_LengthDiv = Tubes[2] + ".lengthDivisions"
        Tube0_WidthDiv = Tubes[0] + ".widthDivisions"
        Tube1_WidthDiv = Tubes[1] + ".widthDivisions"
        Tube2_WidthDiv = Tubes[2] + ".widthDivisions"
        Tube0_Width = Tubes[0] + ".width"
        Tube1_Width = Tubes[1] + ".width"
        Tube2_Width = Tubes[2] + ".width"
        Tube0_Taper = Tubes[0] + ".taper"
        Tube1_Taper = Tubes[1] + ".taper"
        Tube2_Taper = Tubes[2] + ".taper"
        lengthDivisionsControl = eachCurve + ".lengthDivisions"
        widthDivisionsControl = eachCurve + ".widthDivisions"
        braidWidthControl = eachCurve + ".braidWidth"
        braidTaperControl = eachCurve + ".braidTaper"
        flatnessControl = eachCurve + ".flatness"
        perbraidWidthControl = eachCurve + ".perbraidWidth"
        perBraidTaperControl = eachCurve + ".perbraidtaper"
        if cmds.attributeQuery("braidWidth", node=eachCurve, ex=1):
            cmds.deleteAttr(lengthDivisionsControl)
            cmds.deleteAttr(widthDivisionsControl)
            cmds.deleteAttr(braidWidthControl)
            cmds.deleteAttr(braidTaperControl)
            cmds.deleteAttr(flatnessControl)
            cmds.deleteAttr(perbraidWidthControl)
            cmds.deleteAttr(perBraidTaperControl)
        cmds.addAttr(eachCurve,
                     min=0,
                     ln="braidWidth",
                     h=0,
                     k=1,
                     at='double',
                     dv=1)
        cmds.addAttr(eachCurve,
                     min=0,
                     ln="braidTaper",
                     h=0,
                     k=1,
                     at='double',
                     dv=1)
        cmds.addAttr(eachCurve,
                     ln="flatness",
                     h=0,
                     k=1,
                     at='double',
                     max=1,
                     dv=0)
        cmds.addAttr(eachCurve,
                     min=0,
                     ln="lengthDivisions",
                     h=0,
                     k=1,
                     at='long',
                     dv=100)
        cmds.addAttr(eachCurve,
                     min=0,
                     ln="widthDivisions",
                     h=0,
                     k=1,
                     at='long',
                     dv=7)
        cmds.addAttr(eachCurve,
                     min=0,
                     ln="perbraidWidth",
                     h=0,
                     k=1,
                     at='double',
                     dv=0.5)
        cmds.addAttr(eachCurve,
                     min=0,
                     ln="perbraidtaper",
                     h=0,
                     k=1,
                     at='double',
                     dv=1)
        cmds.expression(s=(hairSystemShapeClumpWidth + "=" +
                           braidWidthControl))
        cmds.expression(s=(hairSystemShapeClumpTaper + "=" +
                           braidTaperControl))
        cmds.expression(s=(hairSystemShapeClumpFlatness + "=" +
                           flatnessControl))
        cmds.expression(s=(Tube0_LengthDiv + "=" + lengthDivisionsControl))
        cmds.expression(s=(Tube1_LengthDiv + "=" + lengthDivisionsControl))
        cmds.expression(s=(Tube2_LengthDiv + "=" + lengthDivisionsControl))
        cmds.expression(s=(Tube0_WidthDiv + "=" + widthDivisionsControl))
        cmds.expression(s=(Tube1_WidthDiv + "=" + widthDivisionsControl))
        cmds.expression(s=(Tube2_WidthDiv + "=" + widthDivisionsControl))
        cmds.expression(s=(Tube0_Width + "=" + perbraidWidthControl))
        cmds.expression(s=(Tube1_Width + "=" + perbraidWidthControl))
        cmds.expression(s=(Tube2_Width + "=" + perbraidWidthControl))
        cmds.expression(s=(Tube0_Taper + "=" + perBraidTaperControl))
        cmds.expression(s=(Tube1_Taper + "=" + perBraidTaperControl))
        cmds.expression(s=(Tube2_Taper + "=" + perBraidTaperControl))
        cmds.hide(mainGroup)
        cmds.parent(eachCurve, w=1, r=1)
        cmds.parent(mainGroup, eachCurve)
        cmds.parent(getList[0], eachCurve)
        cmds.parent(getList[1], eachCurve)
        cmds.select(Tubes)
        ldmt_fixReverse.fixReverse()
    cmds.select(allSel)
    for i in allSel:
        cmds.rename(i, 'Braid_#')
Beispiel #34
0
    def etc_set(self):

        ### attribute

        # sup con vis

        for x in range(8):
            cmds.addAttr(TP.AA['PL'][x],
                         ln='sub_con_vis',
                         at='enum',
                         en='off:on:')
            cmds.setAttr(TP.AA['PL'][x] + '.sub_con_vis', e=1, keyable=1)
            cmds.connectAttr(TP.AA['PL'][x] + '.sub_con_vis',
                             TP.AA['CL'][x] + '.visibility')

        # FK / IK switch
        for x in range(2):
            switchCon = controllerShape(TP.conVis['key'][x][0] + '_CON',
                                        'cross', 'yellow')
            switchNul = cmds.group(switchCon,
                                   n=TP.conVis['key'][x][0] + '_NUL')

            cmds.delete(cmds.pointConstraint(TP.conVis['key'][x][1],
                                             switchNul))
            cmds.parent(switchNul, TP.conVis['key'][x][1])
            cmds.move(5, 0, 0, ws=1, r=1)

            cmds.addAttr(switchCon,
                         ln=TP.conVis['attr'][0],
                         at='enum',
                         en='off:on:')
            cmds.setAttr(switchCon + '.' + TP.conVis['attr'][0],
                         e=1,
                         keyable=1)

            cmds.addAttr(switchCon,
                         ln=TP.conVis['attr'][1],
                         at='enum',
                         en='off:on:')
            cmds.setAttr(switchCon + '.' + TP.conVis['attr'][1],
                         e=1,
                         keyable=1)

        for x in range(2):
            top_list = TP.conVis['vis'][x]
            for y in top_list:
                for z in y:
                    if len(y) == 1:
                        cmds.connectAttr(
                            TP.conVis['key'][x][0] + '_CON.' +
                            TP.conVis['attr'][0], z + '.visibility')
                    else:
                        cmds.connectAttr(
                            TP.conVis['key'][x][0] + '_CON.' +
                            TP.conVis['attr'][1], z + '.visibility')

                    cmds.setAttr(TP.conVis['key'][x][0] + '_CON.IK_con_vis', 1)

        ### Parent node

        cmds.parent(TP.attach_list, 'attach_GRP')
        cmds.parent(TP.noneTrans_list, 'noneTransform_GRP')
        cmds.parent(TP.auxillary_list, 'auxillary_GRP')
        cmds.parent(TP.neck_list, 'C_neck_GRP')
        cmds.parent(TP.spine_list, 'C_spine_GRP')
        cmds.parent(TP.L_foreLeg_list, 'L_foreLeg_GRP')
        cmds.parent(TP.R_foreLeg_list, 'R_foreLeg_GRP')
        cmds.parent(TP.L_hindLeg_list, 'L_hindLeg_GRP')
        cmds.parent(TP.R_hindLeg_list, 'R_hindLeg_GRP')

        cmds.delete(TP.delete_list)

        #cmds.select ( TP.noneTrans_list, 'templateJoint_GRP', TP.hide_list )
        #cmds.HideSelectedObjects ()

        ### Rotate controler

        self.controlerRotate(TP.rotate_con_list_A, 0, 0, -90)
        self.controlerRotate(TP.rotate_con_list_B, -90, 0, 0)
Beispiel #35
0
def CreateFeet():
    l_arrow = base.curve(p = [(1,0,0),(1,0,2), (2,0,2),(0,0,6), (-2,0,2), (-1,0,2), (-1,0,0), (1,0,0)], degree = 1, name = "CTRL_L_Foot")
    base.addAttr(shortName = "KF", longName = "Knee_Twist", attributeType = 'double', defaultValue = 0, minValue = -100, maxValue = 100, keyable = True)            
    base.addAttr(shortName = "KR", longName = "Knee_Fix", attributeType = 'double', defaultValue = 0, minValue = 0, maxValue = 100, keyable = True)            
    base.addAttr(shortName = "FR", longName = "Foot_Roll", attributeType = 'double', defaultValue = 0, minValue = 0, maxValue = 100, keyable = True)            
    base.addAttr(shortName = "BR", longName = "Ball_Roll", attributeType = 'double', defaultValue = 0, minValue = 0, maxValue = 100, keyable = True)            


    r_arrow = base.curve(p = [(1,0,0),(1,0,2), (2,0,2),(0,0,6), (-2,0,2), (-1,0,2), (-1,0,0), (1,0,0)], degree = 1, name = "CTRL_R_Foot")
    base.addAttr(shortName = "KF", longName = "Knee_Twist", attributeType = 'double', defaultValue = 0, minValue = -100, maxValue = 100, keyable = True)            
    base.addAttr(shortName = "KR", longName = "Knee_Fix", attributeType = 'double', defaultValue = 0, minValue = 0, maxValue = 100, keyable = True)            
    base.addAttr(shortName = "FR", longName = "Foot_Roll", attributeType = 'double', defaultValue = 0, minValue = 0, maxValue = 100, keyable = True) 
    base.addAttr(shortName = "BR", longName = "Ball_Roll", attributeType = 'double', defaultValue = 0, minValue = 0, maxValue = 100, keyable = True)                           
  
    
    base.scale(0.08, 0.08, 0.08, l_arrow)
    base.scale(0.08, 0.08, 0.08, r_arrow)
        
    l_footPos = base.xform(base.ls("RIG_L_Foot"), q = True, t = True, ws = True)
    r_footPos = base.xform(base.ls("RIG_R_Foot"), q = True, t = True, ws = True)  
        
    base.move(l_footPos[0], 0, l_footPos[2], l_arrow)
    base.move(r_footPos[0], 0, r_footPos[2], r_arrow)    
    
    base.makeIdentity(l_arrow, apply = True, t = 1, r = 1, s = 1)        
    base.makeIdentity(r_arrow, apply = True, t = 1, r = 1, s = 1) 
        
    base.parent(l_arrow, "MASTER_CONTROLLER")
    base.parent(r_arrow, "MASTER_CONTROLLER")    
Beispiel #36
0
    def install_init(self):
        cmds.namespace(setNamespace=self.blueprintNamespace)
        cmds.namespace(add=self.moduleNamespace)
        cmds.namespace(setNamespace=":")

        characterContainer = self.characterNamespaceOnly + ":character_container"
        blueprintContainer = self.blueprintNamespace + ":module_container"
        containers = [characterContainer, blueprintContainer]
        for c in containers:
            cmds.lockNode(c, lock=False, lockUnpublished=False)

        # Duplicate creation pose joints to create new instance. Stored in external method.
        self.joints = self.duplicateAndRenameCreationPose()
        moduleJointsGrp = self.joints[0]

        # Group everything for animation module and parent to "Hook_IN_Grp"
        moduleGrp = cmds.group(empty=True,
                               name=self.blueprintNamespace + ":" +
                               self.moduleNamespace + ":module_grp")
        hookIn = self.blueprintNamespace + ":HOOK_IN"
        cmds.parent(moduleGrp, hookIn, relative=True)
        cmds.parent(moduleJointsGrp, moduleGrp, absolute=True)

        # Attr to define icon size.
        cmds.select(moduleGrp)
        cmds.addAttr(at="float",
                     ln="iconScale",
                     min=0.001,
                     softMaxValue=10.0,
                     defaultValue=1,
                     k=True)
        cmds.setAttr(moduleGrp + ".overrideEnabled", 1)
        cmds.setAttr(moduleGrp + ".overrideColor", 6)

        utilityNodes = self.setupBlueprintWeightBasedBlending()

        self.setupModuleVisibility(moduleGrp)

        containedNodes = list(self.joints)
        containedNodes.append(moduleGrp)
        containedNodes.extend(utilityNodes)

        self.moduleContainer = cmds.container(n=self.moduleContainer)
        utils.addNodeToContainer(self.moduleContainer,
                                 containedNodes,
                                 ihb=True)
        utils.addNodeToContainer(blueprintContainer, self.moduleContainer)
        #151
        index = 0
        publishToOuterContainers = False
        for joint in self.joints:
            if index > 0:
                niceJointName = utils.stripAllNamespaces(joint)[1]
                self.publishNameToModuleContainer(
                    joint + ".rotate",
                    niceJointName + "_R",
                    publishToOuterContainers=False)
                publishToOuterContainers = False

            index += 1

        self.publishNameToModuleContainer(moduleGrp + ".lod", "Control_LOD")
        self.publishNameToModuleContainer(moduleGrp + ".iconScale",
                                          "Icon_Scale")
        self.publishNameToModuleContainer(moduleGrp + ".overrideColor",
                                          "Icon_Color")
        self.publishNameToModuleContainer(moduleGrp + ".visibility", "Vis")
        self.publishNameToModuleContainer(moduleGrp + ".visibility",
                                          "Vis",
                                          publishToOuterContainers=False)

        return (self.joints, moduleGrp, self.moduleContainer)
Beispiel #37
0
    def uninstall(self):
        characterContainer = self.characterNamespaceOnly + ":character_container"
        blueprintContainer = self.blueprintNamespace + ":module_container"
        moduleContainer = self.moduleContainer

        # Unlock containers
        containers = [characterContainer, blueprintContainer, moduleContainer]
        for c in containers:
            cmds.lockNode(c, lock=False, lockUnpublished=False)

        containers.pop()

        blueprintJointsGrp = self.blueprintNamespace + ":blueprint_joints_grp"
        blueprintJoints = utils.findJointChain(blueprintJointsGrp)
        blueprintJoints.pop(0)

        settingsLocator = self.blueprintNamespace + ":SETTINGS"

        connections = cmds.listConnections(blueprintJoints[0] +
                                           "_addRotations",
                                           source=True,
                                           destination=False)
        if len(connections) == 2:
            cmds.setAttr(blueprintJointsGrp + ".controlModulesInstalled",
                         False)

        publishedNames = cmds.container(moduleContainer,
                                        q=True,
                                        publishName=True)
        publishedNames.sort()

        for name in publishedNames:
            outerPublishedNames = cmds.container(characterContainer,
                                                 q=True,
                                                 publishName=True)
            if name in outerPublishedNames:
                cmds.container(characterContainer,
                               edit=True,
                               unbindAndUnpublish=blueprintContainer + "." +
                               name)
                cmds.container(blueprintContainer,
                               edit=True,
                               unbindAndUnpublish=moduleContainer + "." + name)

        cmds.delete(moduleContainer)

        weightAttributeName = self.moduleNamespace + "_weight"
        cmds.deleteAttr(settingsLocator + "." + weightAttributeName)

        attributes = cmds.listAttr(settingsLocator, keyable=False)
        weightAttributes = []
        for attr in attributes:
            if attr.find("_weight") != -1:
                weightAttributes.append(attr)

        totalWeight = 0
        for attr in weightAttributes:
            totalWeight += cmds.getAttr(settingsLocator + "." + attr)

        cmds.setAttr(settingsLocator + ".creationPoseWeight", 1 - totalWeight)

        currentEntries = cmds.attributeQuery("activeModule",
                                             n=settingsLocator,
                                             listEnum=True)
        currentEntriesList = currentEntries[0].split(":")

        ourEntry = self.moduleNamespace

        currentEntriesString = ""
        for entry in currentEntriesList:
            if entry != ourEntry:
                currentEntriesString += entry + ":"

        if currentEntriesString == "":
            currentEntriesString = "None"

        cmds.addAttr(settingsLocator + ".activeModule",
                     edit=True,
                     enumName=currentEntriesString)

        cmds.setAttr(settingsLocator + ".activeModule", 0)

        cmds.namespace(setNamespace=self.blueprintNamespace)
        cmds.namespace(removeNamespace=self.moduleNamespace)
        cmds.namespace(setNamespace=":")

        for c in containers:
            cmds.lockNode(c, lock=True, lockUnpublished=True)
    def importPointCloudX(self, filePath):
        """ Read data from file - old method.
			Kept here for completeness.
		"""
        if os.path.isfile(filePath):  # Check file exists

            # Read data into numpy array
            data = np.genfromtxt(filePath)
            count = data.shape[0]

            # Initialise progress bar and start timer
            mc.progressBar(self.gMainProgressBar,
                           edit=True,
                           beginProgress=True,
                           isInterruptable=True,
                           maxValue=count)  # Initialise progress bar
            startTime = time.time()

            # Create group and particles etc.
            fileName = os.path.splitext(os.path.basename(filePath))[0]
            pCloudGroup = mc.group(name="%s_pointCloud_GRP" % fileName,
                                   empty=True)
            pCloudParticle = mc.particle(name="pCloud_%s" % fileName)

            #mel.eval('addAttr -ln "rgbPP" -dt vectorArray %s' %pCloudParticle[1])
            #mel.eval('addAttr -ln "rgbPP0" -dt vectorArray %s' %pCloudParticle[1])
            mc.addAttr(pCloudParticle[1],
                       longName="rgbPP",
                       dataType="vectorArray")
            mc.addAttr(pCloudParticle[1],
                       longName="rgbPP0",
                       dataType="vectorArray")

            for i in range(count):

                #				# Progress bar
                #				if mc.progressBar(self.gMainProgressBar, query=True, isCancelled=True): # Cancel operation if esc key pressed
                #					mc.progressBar(self.gMainProgressBar, edit=True, endProgress=True) # Complete progress bar
                #					mc.warning("Operation interrupted. You may wish to undo.")
                #					return False
                #				else:
                #					mc.progressBar(self.gMainProgressBar, edit=True, step=1, status="Generating point cloud...") # Increment progress bar

                pX = data[i, 0]
                pY = data[i, 1]
                pZ = data[i, 2]
                pR = data[i, 3] / 255.0
                pG = data[i, 4] / 255.0
                pB = data[i, 5] / 255.0
                #				xyz = data[i,0:3]
                #				rgb = data[i,3:6]/255

                mel.eval('emit -o %s -at "rgbPP" -pos %s %s %s -vv %s %s %s' %
                         (pCloudParticle[0], pX, pY, pZ, pR, pG, pB))
                #mc.emit(object=pCloudParticle[0], position=xyz, attribute="rgbPP", vectorValue=rgb)

            mc.saveInitialState(pCloudParticle[0])
            mc.setAttr("%s.isDynamic" % pCloudParticle[1], 0)
            mc.parent(pCloudParticle[0], pCloudGroup)

            # Complete progress bar and end clock
            mc.progressBar(self.gMainProgressBar, edit=True,
                           endProgress=True)  # Complete progress bar
            totalTime = time.time() - startTime
            print "Read %d points in %f seconds.\n" % (count, totalTime)

            return pCloudGroup
        else:
            mc.error("File doesn't exist: %s" % filePath)
            return False
    def publish(self, settings, item):
        """
        Executes the publish logic for the given item and settings.

        :param settings: Dictionary of Settings. The keys are strings, matching
            the keys returned in the settings property. The values are `Setting`
            instances.
        :param item: Item to process
        """

        publisher = self.parent

        # get the path to create and publish
        publish_path = item.properties["path"]

        # ensure the publish folder exists:
        publish_folder = os.path.dirname(publish_path)
        self.parent.ensure_folder_exists(publish_folder)

        # set the alembic args that make the most sense when working with Mari.
        # These flags will ensure the export of an USD file that contains
        # all visible geometry from the current scene together with UV's and
        # face sets for use in Mari.

        usd_args = [
            '-shd "none"',
            '-dms "none"',
            '-uvs 1',
            '-cls 0',
            '-vis 1',
            '-mt 0',
            '-sl',
            #'-fs %f'%item.properties['sub_frame'],
            '-ft %f' % item.properties['sub_frame']
        ]

        # find the animated frame range to use:
        start_frame, end_frame = _find_scene_animation_range()
        if start_frame and end_frame:
            usd_args.append("-fr %d %d" % (start_frame, end_frame))

        # Set the output path:
        # Note: The AbcExport command expects forward slashes!

        usd_args.append('-f "%s"' % publish_path.replace("\\", "/"))

        # build the export command.  Note, use AbcExport -help in Maya for
        # more detailed USD export help
        usd_export_cmd = ("usdExport %s" % " ".join(usd_args))

        # ...and execute it:
        try:
            self.parent.log_debug("Executing command: %s" % usd_export_cmd)

            select_list = [
                x for x in cmds.listRelatives(
                    item.properties['name'], c=1, f=1, ad=1)
                if not x.find("cache_grp") == -1 and x.find("cache_grp|") == -1
            ]
            for obj in select_list:
                if not cmds.attributeQuery("USD_kind", node=obj, exists=True):
                    cmds.addAttr(obj, longName="USD_kind", dataType="string")
                cmds.setAttr(obj + ".USD_kind", "component", type="string")

            cmds.select(select_list)
            _to_tractor(self, item, usd_export_cmd)
            #mel.eval(usd_export_cmd)
        except Exception, e:
            import traceback

            print usd_export_cmd
            self.parent.log_debug("Executing command: %s" % usd_export_cmd)
            self.logger.error("Failed to export USD: %s" % e,
                              extra={
                                  "action_show_more_info": {
                                      "label":
                                      "Error Details",
                                      "tooltip":
                                      "Show the full error stack trace",
                                      "text":
                                      "<pre>%s</pre>" %
                                      (traceback.format_exc(), )
                                  }
                              })
            return
Beispiel #40
0
	def create(self):
		self._lBpCtrlsSpine = self._lBpCtrls
		self._lBpCtrls = [self._lBpCtrlsPelvis[1]] + self._lBpCtrls

		sGrp = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sRig' %(self._sPart, self._sNameRig), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = self._sConnectInJnt)
		sGrpCtrl = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sCtrl' %(self._sPart, self._sNameRig), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = self._sConnectInCtrl)
		sGrpNode = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sNode' %(self._sPart, self._sNameRig), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = self._sGrpNode)

		self._sConnectInJnt = sGrp
		self._sConnectInCtrl = sGrpCtrl
		self._sGrpNode = sGrpNode

		super(spineRig, self).create()


		## fk rig

		oSpineFk = fkJointChainRig.fkJointChainRig(
													sName = 'Fk',
													sSide = self._sSide,
													sPart = self._sPart,
													iIndex = self._iIndex,
													lBpJnts = self._lBpCtrlsSpine,
													sConnectInCtrl = self._sConnectInCtrl,
													sConnectInJnt = self._sConnectInJnt,
													bSub = self._bSub,
													iStacks = self._iStacks,
													lLockHideAttrs = self._lLockHideAttrs)

		oSpineFk.create()

		## pelvis rig
		oPelvisFk = fkJointChainRig.fkJointChainRig(
													sName = 'Fk',
													sSide = self._sSide,
													sPart = self._sPartPelvis,
													iIndex = self._iIndex,
													lBpJnts = self._lBpCtrlsPelvis,
													sConnectInCtrl = self._sConnectInCtrl,
													sConnectInJnt = self._sConnectInJnt,
													bSub = self._bSub,
													iStacks = self._iStacks,
													lLockHideAttrs = self._lLockHideAttrs
														)
		oPelvisFk.create()

		## ik spline
		oSpineIk = ikSplineRig.ikSplineRig(
											sName = 'ikSpline',
											sSide = self._sSide,
											sPart = self._sPart,
											iIndex = self._iIndex,
											lBpJnts = self._lBpCtrls,
											sConnectInCtrl = self._sConnectInCtrl,
											sConnectInJnt = self._sConnectInJnt,
											sGrpNode = self._sGrpNode,
											bSub = self._bSub,
											iStacks = self._iStacks,
											lLockHideAttrs = self._lLockHideAttrs,
											lBpCtrls = self._lBpCtrlsSpine[:-1],
											bOrientTop = True,
											bOrientBot = True,
											lCtrlOrient = self._lCtrlOrient,
											)
		oSpineIk.create()

		## constraint and hidde ribbon controls
		for i, sCtrl in enumerate(self._lCtrls):
			oCtrl = controls.oControl(sCtrl)
			cmds.parentConstraint(oSpineIk.lJnts[i], oCtrl.sPasser, mo = False)
			cmds.setAttr('%s.v' %oCtrl.sPasser, 0)

		## constraint ik controls
		## pelvis
		oCtrl = controls.oControl(oSpineIk.lCtrls[0])
		constraints.constraint([oPelvisFk.lJnts[0], oCtrl.sPasser], sType = 'parent', bMaintainOffset = True)

		## spine
		for i, sCtrl in enumerate(oSpineIk.lCtrls[1:]):
			oCtrl = controls.oControl(sCtrl)
			if i == 0:
				constraints.constraint([oSpineFk.lJnts[i], oCtrl.sPasser], sType = 'parent', bMaintainOffset = True)
			else:
				constraints.constraint([oSpineFk.lJnts[i + 1], oCtrl.sPasser], sType = 'parent', bMaintainOffset = True)
		## add ctrl shape
		sCtrlShape = naming.oName(sType = 'ctrl', sSide = self._sSide, sPart = self._sPart, iIndex = self._iIndex).sName
		controls.addCtrlShape(oSpineIk.lCtrls + oSpineFk.lCtrls + oPelvisFk.lCtrls, sCtrlShape, bVis = False)

		cmds.addAttr(sCtrlShape, ln = 'ikCtrlVis', at = 'long', min = 0, max = 1)
		cmds.setAttr('%s.ikCtrlVis' %sCtrlShape, channelBox = True)
		attributes.connectAttrs(['%s.ikCtrlVis' %sCtrlShape], ['%s.v' %oSpineIk.sGrpCtrl], bForce = True)

		## write rig info
		sModuleNodes = '%s,%s,%s' %(oSpineFk.sModuleNode, oPelvisFk.sModuleNode, oSpineIk.sModuleNode)

		sString_lJnts = self._convertListToString(self._lJnts)
		sString_lCtrls = self._convertListToString(oSpineFk.lCtrls + oPelvisFk.lCtrls + oSpineIk.lCtrls)
		lRigInfo = ['spineRig', self._sConnectInJnt, self._sConnectInCtrl, self._sConnectOutJnt, self._sConnectOutCtrl, self._sConnectOutRootCtrl,sString_lJnts, sString_lCtrls, sGrpCtrl, sModuleNodes, sGrp]
		lAttrs = ['sModuleType', 'sConnectInJnt', 'sConnectInCtrl', 'sConnectOutJnt', 'sConnectOutCtrl', 'sConnectOutRootCtrl', 'lJnts', 'lCtrls', 'sGrpCtrl', 'lModuleNodes', 'sModuleNode']
		self._writeRigInfo(sGrp, lRigInfo, lAttrs)

		self._getRigInfo(sGrp)
def buildDeck(num=54, stack=0.015, holdValue=1.5):

    # identify if the hold value needs to decrease
    if (holdValue * num > 100):
        print('the hold value needs to decrease')
    intv = stack / num  # interval between each cards

    # build card and attach to motion path
    for i in range(0, num):
        offsetGroup = cmds.group(em=True, name='car_offsetGrp_' + str(i))
        if not advance:
            card = cmds.polyPlane(height=3.5,
                                  width=2.5,
                                  sw=1,
                                  sh=1,
                                  name='card_' + str(i))
        elif advance:
            card = cmds.polyPlane(height=3.5,
                                  width=2.5,
                                  sw=1,
                                  sh=10,
                                  name='card_' + str(i))
        cmds.parent(card[0], offsetGroup)
        cmds.pathAnimation(offsetGroup,
                           curve='pokerPath',
                           f=True,
                           fm=True,
                           name='mopathtest' + str(i))
        cardPos = i * intv
        cmds.setAttr('mopathtest%s.uValue' % str(i), cardPos)
        cmds.addAttr(at='float', k=True, h=False, ln='pathValue')
        cmds.parent(offsetGroup, 'Deck')

    cards = cmds.ls('card*', transforms=True)

    for i, card in enumerate(cards):
        startPos = i * intv
        endPos = 1 - (stack - startPos)
        cmds.setDrivenKeyframe(card + '.pathValue',
                               currentDriver='pokerPath.completion',
                               dv=0,
                               v=startPos)
        cmds.setDrivenKeyframe(card + '.pathValue',
                               currentDriver='pokerPath.completion',
                               dv=100,
                               v=endPos)
        cmds.setDrivenKeyframe(card + '.pathValue',
                               currentDriver='pokerPath.completion',
                               dv=0 + (num - i) * holdValue,
                               v=startPos)
        cmds.setDrivenKeyframe(card + '.pathValue',
                               currentDriver='pokerPath.completion',
                               dv=100 - i * holdValue,
                               v=endPos)

        cmds.connectAttr(card + '.pathValue',
                         'mopathtest%s.uValue' % str(i),
                         force=True)
        cmds.keyTangent(card,
                        lock=False,
                        itt='auto',
                        ott='auto',
                        index=[(1, 1), (2, 2)])

    connectNode(cards)
    assignTexture(cards)
    if advance:
        addBlend()
    randomOffest(cards)
if len(selectList) >= 2:
    targetName = selectList[0]
    selectList.remove(targetName)

    locatorGroupName = cmds.group(empty=True, name='expantion_locator_grp#')

    maxExpantion = 100

    newAttrName = 'expantion'

    if not cmds.objExists('%s.%s' % (targetName, newAttrName)):
        cmds.select(targetName)
        cmds.addAttr(longName=newAttrName,
                     shortName='expa',
                     attributeType='double',
                     min=0,
                     max=maxExpantion,
                     defaultValue=maxExpantion,
                     keyable=True)

    for objName in selectList:
        coords = cmds.getAttr('%s.translate' % (objName))[0]

        locatorName = cmds.spaceLocator(position=coords,
                                        name='%s_loc#' % (objName))[0]
        cmds.xform(locatorName, centerPivots=True)
        cmds.parent(locatorName, locatorGroupName)

        pointConstraintName = cmds.pointConstraint([targetName, locatorName],
                                                   objName,
                                                   name='%s_pointConstraint#' %
Beispiel #43
0
def traceArc(space='camera'):
    '''
    The main function for creating the arc.
    '''

    if space not in ('world','camera'):
        OpenMaya.MGlobal.displayWarning('Improper space argument.')
        return

    global ML_TRACE_ARC_PREVIOUS_SELECTION
    global ML_TRACE_ARC_PREVIOUS_SPACE

    globalScale = 1
    if mc.optionVar(exists='ml_arcTracer_brushGlobalScale'):
        globalScale = mc.optionVar(query='ml_arcTracer_brushGlobalScale')

    #save for reset:
    origTime = mc.currentTime(query=True)

    #frame range
    frameRange = utl.frameRange()
    start = frameRange[0]
    end = frameRange[1]

    #get neccesary nodes
    objs = mc.ls(sl=True, type='transform')
    if not objs:
        OpenMaya.MGlobal.displayWarning('Select objects to trace')
        return

    ML_TRACE_ARC_PREVIOUS_SELECTION = objs
    ML_TRACE_ARC_PREVIOUS_SPACE = space

    cam = None
    nearClipPlane = None
    shortCam = ''
    if space=='camera':
        cam = utl.getCurrentCamera()

        #the arc will be placed just past the clip plane distance, but no closer than 1 unit.
        nearClipPlane = max(mc.getAttr(cam+'.nearClipPlane'),1)

        shortCam = mc.ls(cam, shortNames=True)[0]

    topGroup = 'ml_arcGroup'
    worldGrp = 'ml_arcWorldGrp'
    localGrp = 'ml_localGrp_'+shortCam

    #create nodes
    if not mc.objExists(topGroup):
        topGroup = mc.group(empty=True, name=topGroup)

    parentGrp = topGroup
    if space=='world' and not mc.objExists(worldGrp):
        worldGrp = mc.group(empty=True, name=worldGrp)
        mc.setAttr(worldGrp+'.overrideEnabled',1)
        mc.setAttr(worldGrp+'.overrideDisplayType',2)
        mc.parent(worldGrp, topGroup)
        parentGrp = mc.ls(worldGrp)[0]

    if space == 'camera':
        camConnections = mc.listConnections(cam+'.message', plugs=True, source=False, destination=True)
        if camConnections:
            for cc in camConnections:
                if '.ml_parentCam' in cc:
                    localGrp = mc.ls(cc, o=True)[0]

        if not mc.objExists(localGrp):
            localGrp = mc.group(empty=True, name=localGrp)
            mc.parentConstraint(cam, localGrp)
            mc.setAttr(localGrp+'.overrideEnabled',1)
            mc.setAttr(localGrp+'.overrideDisplayType',2)
            mc.parent(localGrp, topGroup)

            mc.addAttr(localGrp, at='message', longName='ml_parentCam')
            mc.connectAttr(cam+'.message', localGrp+'.ml_parentCam')

        parentGrp = mc.ls(localGrp)[0]

    #group per object:
    group = []

    for i,obj in enumerate(objs):
        sn = mc.ls(obj,shortNames=True)[0]
        name = sn.replace(':','_')

        groupName = 'ml_{}_arcGrp'.format(name)
        if mc.objExists(groupName):
            mc.delete(groupName)

        group.append(mc.group(empty=True, name=groupName))

        group[i] = mc.parent(group[i],parentGrp)[0]
        mc.setAttr(group[i]+'.translate', 0,0,0)
        mc.setAttr(group[i]+'.rotate', 0,0,0)

    with utl.UndoChunk():

        #determine the method to run. Test fast against accurate.
        #If fast is the same, continue with fast method.
        #Otherwise revert to accurate method.

        mc.currentTime(start)
        fastPoints = arcDataFast([objs[0]], parentGrp, start+1, start+1, space, nearClipPlane, cam)
        accuratePoints = arcDataAccurate([objs[0]], parentGrp, start+1, start+1, space, nearClipPlane, cam)

        points = None
        #if they're equivalent, continue with fast:
        if [int(x*1000000) for x in fastPoints[0][0]] == [int(x*1000000) for x in accuratePoints[0][0]]:
            points = arcDataFast([objs[0]], parentGrp, start, end, space, nearClipPlane, cam)
        else:
            points = arcDataAccurate([objs[0]], parentGrp, start, end, space, nearClipPlane, cam)

        #create the curves and do paint effects
        mc.ResetTemplateBrush()
        brush = mc.getDefaultBrush()
        mc.setAttr(brush+'.screenspaceWidth',1)
        mc.setAttr(brush+'.distanceScaling',0)
        mc.setAttr(brush+'.brushWidth',0.005)

        for i,obj in enumerate(objs):

            #setup brush for path
            globalScale
            mc.setAttr(brush+'.globalScale', globalScale)
            mc.setAttr(brush+'.screenspaceWidth',1)
            mc.setAttr(brush+'.distanceScaling',0)
            mc.setAttr(brush+'.brushWidth',0.003)

            #color
            for c in ('R','G','B'):
                color = random.uniform(0.3,0.7)
                mc.setAttr(brush+'.color1'+c,color)

            baseCurve = mc.curve(d=3,p=points[i])
            #fitBspline makes a curve that goes THROUGH the points, a more accurate path
            curve = mc.fitBspline(baseCurve, constructionHistory=False, tolerance=0.001, name='ml_arcTracer_curve_#')
            mc.delete(baseCurve)

            #paint fx
            mc.AttachBrushToCurves(curve)
            stroke = mc.ls(sl=True)[0]
            mc.rename(mc.listConnections(stroke+'.brush', destination=False)[0], 'ml_arcTracer_brush_#')

            stroke = mc.parent(stroke,group[i])[0]

            mc.setAttr(stroke+'.overrideEnabled',1)
            mc.setAttr(stroke+'.overrideDisplayType',2)

            mc.setAttr(stroke+'.displayPercent',92)
            mc.setAttr(stroke+'.sampleDensity',0.5)
            mc.setAttr(stroke+'.inheritsTransform',0)
            mc.setAttr(stroke+'.translate',0,0,0)
            mc.setAttr(stroke+'.rotate',0,0,0)

            curve = mc.parent(curve,group[i])[0]
            mc.setAttr(curve+'.translate',0,0,0)
            mc.setAttr(curve+'.rotate',0,0,0)

            mc.hide(curve)

            #setup brush for tics
            if space=='camera':
                mc.setAttr(brush+'.brushWidth',0.008)
            if space=='world':
                mc.setAttr(brush+'.brushWidth',0.005)
            mc.setAttr(brush+'.color1G',0)
            mc.setAttr(brush+'.color1B',0)

            for t in range(len(points[i])):
                frameCurve = None
                if space=='camera':
                    vec = utl.Vector(points[i][t][0],points[i][t][1],points[i][t][2])
                    vec*=0.98
                    frameCurve = mc.curve(d=1,p=[points[i][t],vec[:]])

                elif space=='world':
                    frameCurve = mc.circle(constructionHistory=False, radius=0.0001, sections=4)[0]
                    mc.setAttr(frameCurve+'.translate', points[i][t][0], points[i][t][1], points[i][t][2])
                    constraint = mc.tangentConstraint(curve, frameCurve, aimVector=(0,0,1), worldUpType='scene')
                    #mc.delete(constraint)

                #check for keyframe
                colorAttribute='color1G'
                if mc.keyframe(obj, time=((t+start-0.5),(t+start+0.5)), query=True):
                    mc.setAttr(brush+'.color1R',1)
                else:
                    mc.setAttr(brush+'.color1R',0)

                mc.AttachBrushToCurves(curve)

                stroke = mc.ls(sl=True)[0]
                thisBrush = mc.listConnections(stroke+'.brush', destination=False)[0]
                thisBrush = mc.rename(thisBrush, 'ml_arcTracer_brush_#')

                #setup keyframes for frame highlighting
                mc.setKeyframe(thisBrush, attribute='color1G', value=0, time=(start+t-1, start+t+1))
                mc.setKeyframe(thisBrush, attribute='color1G', value=1, time=(start+t,))

                stroke = mc.parent(stroke,group[i])[0]

                mc.hide(frameCurve)

                mc.setAttr(stroke+'.displayPercent',92)
                mc.setAttr(stroke+'.sampleDensity',0.5)

                frameCurve = mc.parent(frameCurve,group[i])[0]

                if space=='camera':
                    mc.setAttr(stroke+'.inheritsTransform',0)
                    mc.setAttr(stroke+'.pressureScale[1].pressureScale_Position', 1)
                    mc.setAttr(stroke+'.pressureScale[1].pressureScale_FloatValue', 0)
                    mc.setAttr(stroke+'.translate',0,0,0)
                    mc.setAttr(stroke+'.rotate',0,0,0)
                    mc.setAttr(frameCurve+'.translate',0,0,0)
                    mc.setAttr(frameCurve+'.rotate',0,0,0)

        mc.currentTime(origTime, edit=True)
        panel = mc.getPanel(withFocus=True)
        try:
            mc.modelEditor(panel, edit=True, strokes=True)
        except:
            pass

    mc.select(objs,replace=True)
    mc.refresh()
Beispiel #44
0
	def globalGammaCtrl(self,gammaVaule):
		gg = cmds.createNode('transform',n='globalGammaCtrl' )
		cmds.addAttr(gg,ln='gamma',at='double',dv=gammaVaule)
		cmds.setAttr(gg+'.gamma',e=1,keyable=1)
Beispiel #45
0
def main(templateFile=None, controlShapes=None, fbx=False, scale=1, radius=1):

    template(filepath=templateFile, scale=scale)

    root.main(name="assembly",
              fbx=fbx,
              radius=radius,
              body=False,
              pelvis=False)
    mc.addAttr("assembly", ln="placers", at="bool", k=True)
    mc.addAttr("assembly", ln="wheels", at="bool", dv=True, k=True)
    mc.addAttr("assembly", ln="terrain", at="bool", dv=True, k=True)
    mc.addAttr("assembly", ln="editTerrain", at="bool", k=True)
    mc.addAttr("assembly", ln="terrainDetection", at="bool", dv=True, k=True)

    t = terrain.main(parent="world_ctrl", scale=scale * 10)

    wheels = []
    jnts = mc.ls(typ="joint") or []
    for jnt in jnts:
        if jnt.startswith("wheel"):
            grp, ctrl, ctrl2, _wheel = wheel.main(name=jnt.replace("_tmp", ""),
                                                  terrain=t,
                                                  radius=radius)
            mc.delete(mc.parentConstraint(jnt, grp, st="y"))
            ty = mc.xform(jnt, q=True, ws=True, rp=True)[1]
            mc.setAttr(ctrl2 + ".size", ty)
            wheels.append(grp)

    grp, ctrl = chassis.main(wheels=wheels, parent="world_ctrl", radius=radius)
    mc.parent(wheels, grp)
    mc.parent(grp, "cog_ctrl")

    mc.connectAttr("assembly.joints", ctrl + ".joints")
    mc.setAttr(ctrl + ".joints", k=False)
    mc.connectAttr("assembly.editJoints", ctrl + ".editJoints")
    mc.setAttr(ctrl + ".editJoints", k=False)
    mc.connectAttr("assembly.controls", ctrl + ".controls")
    mc.connectAttr("assembly.controls", "chassis_ctrlShape.v")
    mc.setAttr(ctrl + ".controls", k=False)
    mc.connectAttr("assembly.placers", ctrl + ".placers")
    mc.setAttr(ctrl + ".placers", k=False)
    mc.connectAttr("assembly.wheels", ctrl + ".wheels")
    mc.setAttr(ctrl + ".wheels", k=False)
    mc.connectAttr("assembly.terrain", t + ".v")
    mc.setAttr(ctrl + ".terrain", k=False)
    r = mc.createNode("reverse", ss=True)
    mc.connectAttr("assembly.editTerrain", r + ".inputX")
    mc.connectAttr(r + ".outputX", t + ".template")
    mc.setAttr(ctrl + ".editTerrain", k=False)
    mc.connectAttr("assembly.terrainDetection", ctrl + ".terrainDetection")
    mc.setAttr(ctrl + ".terrainDetection", k=False)

    if fbx:
        mc.createNode("joint", n="root_fbx", p="skeleton_fbx")
        mc.setAttr("root_fbx.radius", radius * 0.25)
        c = mc.pointConstraint("cog_ctrl", "root_fbx", sk=["y"])[0]
        mc.parent(c, "constraints_fbx")
        c = mc.orientConstraint("cog_ctrl", "root_fbx", sk=["x", "z"])[0]
        mc.parent(c, "constraints_fbx")
        c = mc.scaleConstraint("cog_ctrl", "root_fbx")[0]
        mc.parent(c, "constraints_fbx")
        mc.createNode("joint", n="chassis_fbx", p="root_fbx")
        mc.setAttr("chassis_fbx.radius", radius * 0.25)
        c = mc.parentConstraint("chassis_jnt", "chassis_fbx")[0]
        mc.parent(c, "constraints_fbx")
        c = mc.scaleConstraint("chassis_jnt", "chassis_fbx")[0]
        mc.parent(c, "constraints_fbx")
        for n in wheels:
            n = n.replace("_grp", "")
            mc.createNode("joint", n=n + "_fbx", p="chassis_fbx")
            mc.setAttr(n + "_fbx.radius", radius * 0.25)
            c = mc.parentConstraint(n + "_jnt", n + "_fbx")[0]
            mc.parent(c, "constraints_fbx")
            c = mc.scaleConstraint(n + "_jnt", n + "_fbx")[0]
            mc.parent(c, "constraints_fbx")

    if controlShapes:
        if os.path.isfile(THIS_DIR + "/" + controlShapes):
            common.loadControlShapes(THIS_DIR + "/" + controlShapes)
        elif os.path.isfile(controlShapes):
            common.loadControlShapes(controlShapes)

    mc.delete("template")
    mc.select(cl=True)
    mc.dgdirty(a=True)
Beispiel #46
0
def BT_AddPose(set=None, poseName='', index=None):

    prefixedPoseName = 'BT_' + poseName

    if not set:
        return False

    if not cmds.attributeQuery('Blend_Node', ex=True, n=set):
        return False

    if BT_IsSetupConnected(set=set):
        cmds.warning('Disconnect setup first!')
        return False

    blendNode = cmds.getAttr(set + '.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    if cmds.attributeQuery(prefixedPoseName, ex=True, n=set):
        return False

    transforms = cmds.listConnections(set + '.dagSetMembers')

    numTransforms = len(transforms)
    poseIndex = cmds.getAttr(blendNode + '.transforms[0].poses', size=True)

    if index is not None:
        poseIndex = index

    if index is None:
        cmds.addAttr(set,
                     ln=prefixedPoseName,
                     nn=poseName,
                     k=True,
                     min=0,
                     max=1.0,
                     at='double')

    # print ('Num poses = ' +str(numPoses))
    for i in range(0, numTransforms):
        #get the base matrix
        baseScale = cmds.getAttr(blendNode + '.transforms[' + str(i) +
                                 '].baseScale')[0]
        baseMatrix = cmds.getAttr(blendNode + '.transforms[' + str(i) +
                                  '].baseMatrix')

        #store the scale and set it
        transformScale = cmds.getAttr(transforms[i] + '.scale')[0]

        #set the scale back to 1.0
        cmds.setAttr(transforms[i] + '.scale', 1.0, 1.0, 1.0, type='double3')
        transformMatrix = cmds.xform(transforms[i], q=True, m=True)

        poseMatrix = [x - y for x, y in zip(transformMatrix, baseMatrix)]
        poseScale = [x - y for x, y in zip(transformScale, baseScale)]

        #set the scale back to what the user had it at
        cmds.setAttr(transforms[i] + '.scale',
                     transformScale[0],
                     transformScale[1],
                     transformScale[2],
                     type='double3')
        cmds.setAttr(blendNode + '.transforms[' + str(i) + '].poses[' +
                     str(poseIndex) + '].matrix',
                     poseMatrix,
                     type='matrix')
        BT_Double3ValuesToNode(values=poseScale,
                               node=blendNode,
                               attr='transforms[' + str(i) + '].poses[' +
                               str(poseIndex) + '].scale')

        if index is None:
            cmds.connectAttr(
                set + '.' + prefixedPoseName, blendNode + '.transforms[' +
                str(i) + '].poses[' + str(poseIndex) + '].weight')

    return True
Beispiel #47
0
def combineSingleAttrConnections(targetAttr,
                                 inputAttr1='',
                                 inputAttr2='',
                                 inputAttr1Value=None,
                                 inputAttr2Value=None,
                                 combineMode='add',
                                 enableAttributeOverride=False,
                                 blendAttr=''):
    """
    Connect the combined result of 2 input attributes/values to a target attribute.

    @param targetAttr: Target attribute to receive the combined values result
    @type targetAttr: str
    @param inputAttr1: First attribute to be used to obtain the combined result
    @type inputAttr1: str
    @param inputAttr2: Second attribute to be used to obtain the combined result. If left as default (''), the existing input connection to targetAttr will be used.
    @type inputAttr2: str
    @param inputAttr1Value: Set the value of the first input
    @type inputAttr1Value: float
    @param inputAttr2Value: Set the value of the second input
    @type inputAttr2Value: float
    @param combineMode: How to combine the 2 input attribute values. Accepted inputs are "add", "mult" and "blend".
    @type combineMode: str
    @param enableAttributeOverride: If you specify both a source attribute and value for an input, this will attempt to set the source attribute to the input value.
    @type enableAttributeOverride: str
    @param blendAttr: Source attribute that will drive the attribute blend amount. If left as default (''), no connection will be made to the "blendNode.attributeBlender" attribute.
    @type blendAttr: str
    """
    # Check existing connections
    existingConn = cmds.listConnections(targetAttr, s=True, d=False, p=True)

    # Check target attributes
    if not cmds.objExists(targetAttr):
        raise Exception('Target attribute ' + targetAttr + ' does not exist!')
    # Check inputs
    if (not inputAttr1) and (inputAttr1Value == None):
        raise Exception('No input attribute or value specified for input1!')
    if (not inputAttr2) and (inputAttr2Value == None):
        raise Exception('No input attribute or value specified for input2!')
    # Check input attributes
    if inputAttr1 and not cmds.objExists(inputAttr1):
        raise Exception('Input attribute 1 ' + inputAttr1 + ' does not exist!')
    if inputAttr2 and not cmds.objExists(inputAttr2):
        raise Exception('Input attribute 2 ' + inputAttr2 + ' does not exist!')

    # Get target node name
    if not targetAttr.count('.'):
        raise Exception(targetAttr + ' is not a valid attribute!')
    targetNode = targetAttr.split('.')[0]

    # Combine inputs
    combineNode = ''
    combineAttr1 = 'input1'
    combineAttr2 = 'input2'
    if combineMode == 'add':
        combineNode = self.nameUtil.appendName(
            targetNode,
            self.nameUtil.node['addDoubleLinear'],
            stripNameSuffix=True)
        combineNode = cmds.createNode('addDoubleLinear', n=combineNode)
    if combineMode == 'mult':
        combineNode = self.nameUtil.appendName(
            targetNode,
            self.nameUtil.node['multDoubleLinear'],
            stripNameSuffix=True)
        combineNode = cmds.createNode('multDoubleLinear', n=combineNode)
    if combineMode == 'blend':
        combineNode = self.nameUtil.appendName(
            targetNode,
            self.nameUtil.node['blendTwoAttr'],
            stripNameSuffix=True)
        combineNode = cmds.createNode('blendTwoAttr', n=combineNode)
        combineAttr1 = 'input[0]'
        combineAttr2 = 'input[1]'

    # Set Input 1
    if inputAttr1:
        cmds.connectAttr(inputAttr1, combineNode + '.' + combineAttr1, f=True)
        if enableAttributeOverride and cmds.getAttr(inputAttr1, se=True):
            cmds.setAttr(inputAttr1, inputAttr1Value)
    else:
        cmds.setAttr(combineNode + '.' + combineAttr1, inputAttr1Value)
    # Set Input 2
    if inputAttr2:
        cmds.connectAttr(inputAttr2, combineNode + '.' + combineAttr2, f=True)
        if enableAttributeOverride and cmds.getAttr(inputAttr2, se=True):
            cmds.setAttr(inputAttr2, inputAttr2Value)
    else:
        cmds.setAttr(combineNode + '.' + combineAttr2, inputAttr2Value)

    # Connect to target attribute
    cmds.connectAttr(combineNode + '.output', targetAttr, f=True)

    # Connect blend attribute
    if combineMode == 'blend' and blendAttr:
        # Check blend attribute
        if not cmds.objExists(blendAttr):
            if not blendAttr.count('.'):
                raise Exception(targetAttr +
                                ' is not a valid object.attribute name!')
            blendAttrName = blendAttr.split('.')
            if len(blendAttrName) != 2:
                raise Exception(targetAttr +
                                ' is not a valid object.attribute name!')
            if not cmds.objExists(blendAttrName[0]):
                raise Exception('Object ' + blendAttrName[0] +
                                ' does not exist!')
            cmds.addAttr(blendAttrName[0],
                         ln=blendAttrName[1],
                         at='float',
                         min=0,
                         max=1,
                         dv=0)
            cmds.setAttr(blendAttr, k=True)
        cmds.connectAttr(blendAttr, blendNode + '.attributesBlender', f=True)

    # Return result
    return combineNode
Beispiel #48
0
    def createCtrl(cls, crv, jntLs):
        fkOpt = cmds.checkBoxGrp(cls.uiWdgDic['optChkBoxGrp'], q=True, v1=True)

        ctrlLs = []

        # Create all control
        allCtrl = cmds.curve(n=crv + '_all_ctrl',
                             d=3,
                             p=[[0, 0, -2.995565], [0.789683, 0, -2.990087],
                                [2.37399, 0, -2.329641],
                                [3.317845, 0, 0.0217106],
                                [2.335431, 0, 2.360484],
                                [-0.0144869, 0, 3.320129],
                                [-2.355941, 0, 2.340014],
                                [-3.317908, 0, -0.00724357],
                                [-2.353569, 0, -2.350269],
                                [-0.76356, 0, -2.996864], [0, 0, -2.995565]],
                             k=(0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0,
                                7.0, 8.0, 8.0, 8.0))
        ctrlLs.append(allCtrl)
        ctrlGrpLs = cls.ctrlGrp(allCtrl)
        cmds.delete(cmds.parentConstraint(jntLs[0], ctrlGrpLs[0], mo=False))
        cmds.addAttr(allCtrl,
                     ln='bindJointsVis',
                     nn='Bind Joints Vis',
                     keyable=True,
                     at='bool')
        cmds.setAttr('%s.visibility' % allCtrl,
                     lock=True,
                     keyable=False,
                     channelBox=False)

        # Create each joint control
        for jnt in jntLs:
            # Create cube shape control
            ctrl = cmds.curve(
                n=jnt.rsplit('_rbBnd_jnt')[0] + '_ctrl',
                d=1,
                p=[(-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1), (-1, 1, 1),
                   (-1, -1, 1), (-1, -1, -1),
                   (1, -1, -1), (1, -1, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1),
                   (1, 1, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1)],
                k=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
            ctrlLs.append(ctrl)

            # Lock and hide unused attributes of control.
            unUsedAttr = ['scaleX', 'scaleY', 'scaleZ', 'visibility']
            for attr in unUsedAttr:
                cmds.setAttr("%s.%s" % (ctrl, attr),
                             lock=True,
                             keyable=False,
                             channelBox=False)

            # Control group hierarchy
            ctrlGrpLs = cls.ctrlGrp(ctrl)
            cmds.parent(ctrl, ctrlGrpLs[2])

            # Match control to the joint
            cmds.delete(cmds.parentConstraint(jnt, ctrlGrpLs[0], mo=False))

            # Constraint part
            cmds.parentConstraint(ctrl, jnt, mo=False)
            cmds.scaleConstraint(ctrl, jnt, mo=False)
            if fkOpt:
                cmds.orientConstraint(ctrl, ctrlGrpLs[3], mo=False)

            # Parent to the parent child rotation pivot group
            matchObj = re.match(r'(.+)_(\d+)_.+', jnt)
            crvName = matchObj.group(1)
            jntNum = int(matchObj.group(2))

            if jntNum == 0:
                cmds.parent(ctrlGrpLs[3], '%s_all_ctrl' % crvName)
            else:
                parentJntNum = jntNum - 1
                cmds.parent(ctrlGrpLs[0], ctrlGrpLs[3],
                            '%s_%d_ctrl_chldRoPivot' % (crvName, parentJntNum))

        cmds.parent(ctrlLs[1] + '_zero', allCtrl)

        return ctrlLs
Beispiel #49
0
def create(spaceNode,
           spaceSwitch=None,
           parent=None,
           mode='parent',
           master_node='Main',
           verbose=False):
    '''
    other modes: 'orient', 'point'
    nodes in the network:
    spaceGrp:        node to group the space targets (usually parented to the noXform_grp) 'Lf_arm_ikh_zeroSpaces'
    spaceSwitch:     node used to mamage switch (usually a control) 'Lf_arm_ikh_ctrl'
    spaceNode:       node that gets constrained to the various space targets (usually a parent of the control node) 'Lf_arm_ikh_zero'
    spaceConstraint: constraint node used to switch spaces 'Lf_arm_ikh_zero_parentConstraint1'
    '''

    if verbose == True:
        print('creating space node for %s' % spaceNode)

    if not spaceSwitch:
        spaceSwitch = spaceNode

    if not cmds.objExists(spaceNode + '.spaceGrp'):

        # Space Group
        grp = cmds.createNode('transform',
                              n=spaceNode + 'Spaces',
                              parent=parent)
        cmds.setAttr(grp + '.inheritsTransform', False)
        decomposeMatrix = cmds.createNode('decomposeMatrix')
        cmds.connectAttr(spaceNode + '.parentMatrix',
                         decomposeMatrix + '.inputMatrix')
        cmds.connectAttr(decomposeMatrix + '.outputTranslate',
                         grp + '.translate')
        cmds.connectAttr(decomposeMatrix + '.outputRotate', grp + '.rotate')
        cmds.connectAttr(decomposeMatrix + '.outputScale', grp + '.scale')

        # Initial Space = MasterOffset
        cmds.addAttr(spaceSwitch,
                     ln=SPACEATTR,
                     attributeType='enum',
                     enumName='master',
                     keyable=True)
        masterSpace = cmds.createNode('transform',
                                      name=grp + '_master',
                                      parent=grp)
        matchPose(spaceNode, masterSpace)

        if not cmds.objExists(master_node):
            cmds.createNode("transform", name=master_node)
        cmds.parentConstraint(master_node, masterSpace, mo=True)
        #cmds.parentConstraint("Main", masterSpace, mo=True)
        lockAndHide(['t', 'r', 's', 'v'], masterSpace)

        # Space Constraint
        if mode == 'point':
            constraint = cmds.pointConstraint(masterSpace, spaceNode,
                                              mo=True)[0]
        if mode == 'orient':
            constraint = cmds.orientConstraint(masterSpace, spaceNode,
                                               mo=True)[0]
        else:
            constraint = cmds.parentConstraint(masterSpace, spaceNode,
                                               mo=True)[0]

        # Message Attrs (for tracing network)
        cmds.addAttr(spaceNode, ln='spaceGrp', at='message', keyable=True)
        cmds.connectAttr(grp + '.message', spaceNode + '.spaceGrp')

        cmds.addAttr(spaceSwitch, ln='spaceNode', at='message', keyable=True)
        cmds.connectAttr(spaceNode + '.message', spaceSwitch + '.spaceNode')

        cmds.addAttr(spaceNode,
                     ln='spaceConstraint',
                     at='message',
                     keyable=True)
        cmds.connectAttr(constraint + '.message',
                         spaceNode + '.spaceConstraint')

        cmds.addAttr(spaceNode, ln='spaceSwitch', at='message', keyable=True)
        cmds.connectAttr(spaceSwitch + '.' + SPACEATTR,
                         spaceNode + '.spaceSwitch')

        return (spaceNode)

    else:

        print 'spaces.create: ' + spaceNode + 'already exists. Use spaces.add'
        return None
Beispiel #50
0
def _create_twist_decomposition_network(driver, twist_axis):
    """Create the twist decomposition network for driver.

    :param driver: Driver transform
    :param twist_axis: Local twist axis on driver
    """
    # Connect message attributes to the decomposed twist nodes so we can reuse them
    # if the network is driving multiple nodes
    if not cmds.objExists("{}.{}".format(driver, TWIST_OUTPUT)):
        cmds.addAttr(driver, ln=TWIST_OUTPUT, at="message")
    if not cmds.objExists("{}.{}".format(driver, INVERTED_TWIST_OUTPUT)):
        cmds.addAttr(driver, ln=INVERTED_TWIST_OUTPUT, at="message")

    # Store the current local matrix of driver to be used as a frame of reference
    if not cmds.objExists("{}.{}".format(driver, REST_MATRIX)):
        cmds.addAttr(driver, ln=REST_MATRIX, at="matrix")
    rest_matrix = cmds.getAttr("{}.m".format(driver))
    cmds.setAttr("{}.restMatrix".format(driver), rest_matrix, type="matrix")
    # Get the local offset matrix which is the matrix from the world rest xform to
    # the current world xform
    world_rest_matrix = cmds.createNode(
        "multMatrix", name="{}_world_rest_matrix".format(driver))
    for i, attr in enumerate(["parentMatrix[0]", REST_MATRIX]):
        cmds.connectAttr("{}.{}".format(driver, attr),
                         "{}.matrixIn[{}]".format(world_rest_matrix, i))
    world_rest_inverse = cmds.createNode(
        "inverseMatrix", name="{}_world_rest_inverse".format(driver))
    cmds.connectAttr(
        "{}.matrixSum".format(world_rest_matrix),
        "{}.inputMatrix".format(world_rest_inverse),
    )
    local_offset_matrix = cmds.createNode(
        "multMatrix", name="{}_local_offset_matrix".format(driver))
    cmds.connectAttr("{}.worldMatrix[0]".format(driver),
                     "{}.matrixIn[0]".format(local_offset_matrix))
    cmds.connectAttr(
        "{}.outputMatrix".format(world_rest_inverse),
        "{}.matrixIn[1]".format(local_offset_matrix),
    )
    # Transform the twist axis by the local offset matrix
    if twist_axis is None:
        twist_axis = _get_local_twist_axis(driver)
    local_twist_axis = cmds.createNode("vectorProduct",
                                       name="{}_twist_axis".format(driver))
    cmds.setAttr("{}.operation".format(local_twist_axis),
                 3)  # Vector Matrix Product
    cmds.setAttr("{}.input1".format(local_twist_axis), *twist_axis)
    cmds.connectAttr("{}.matrixSum".format(local_offset_matrix),
                     "{}.matrix".format(local_twist_axis))
    cmds.setAttr("{}.normalizeOutput".format(local_twist_axis), True)
    # Get the angle between the rest and transformed twist axis to get the swing
    # rotation
    swing_euler = cmds.createNode("angleBetween",
                                  name="{}_swing_euler".format(driver))
    cmds.connectAttr("{}.input1".format(local_twist_axis),
                     "{}.vector1".format(swing_euler))
    cmds.connectAttr("{}.output".format(local_twist_axis),
                     "{}.vector2".format(swing_euler))
    # Convert the swing euler rotation to quaternion
    swing = cmds.createNode("eulerToQuat", name="{}_swing".format(driver))
    cmds.connectAttr("{}.euler".format(swing_euler),
                     "{}.inputRotate".format(swing))
    # Remove the inverse swing from the local offset to be left with the twist
    swing_inverse = cmds.createNode("quatInvert",
                                    name="{}_swing_inverse".format(driver))
    cmds.connectAttr("{}.outputQuat".format(swing),
                     "{}.inputQuat".format(swing_inverse))
    local_rotation = cmds.createNode("decomposeMatrix",
                                     name="{}_local_rotation".format(driver))
    cmds.connectAttr(
        "{}.matrixSum".format(local_offset_matrix),
        "{}.inputMatrix".format(local_rotation),
    )
    twist = cmds.createNode("quatProd", name="{}_twist".format(driver))
    cmds.connectAttr("{}.outputQuat".format(local_rotation),
                     "{}.input1Quat".format(twist))
    cmds.connectAttr("{}.outputQuat".format(swing_inverse),
                     "{}.input2Quat".format(twist))
    cmds.connectAttr("{}.message".format(twist),
                     "{}.{}".format(driver, TWIST_OUTPUT))

    twist_inverse = cmds.createNode("quatInvert",
                                    name="{}_twist_inverse".format(driver))
    cmds.connectAttr("{}.outputQuat".format(twist),
                     "{}.inputQuat".format(twist_inverse))
    cmds.connectAttr(
        "{}.message".format(twist_inverse),
        "{}.{}".format(driver, INVERTED_TWIST_OUTPUT),
    )
Beispiel #51
0
 def dpCreateRivet(self, geoToAttach, uvSetName, itemList, attachTranslate, attachRotate, addFatherGrp, addInvert, invT, invR, rivetGrpName='Rivet_Grp', askComponent=False, *args):
     """ Create the Rivet setup.
     """
     # declaring variables
     self.shapeToAttachList = None
     self.shapeToAttach = None
     self.cpNode = None
     self.tempNoce = None
     attrList = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
     self.rivetList, togetherList = [], []
     isComponent = None
     
     # integrate to dpAutoRigSystem:
     self.masterGrp = None
     self.masterCtrl = None
     self.scalableGrp = None
     allList = cmds.ls(selection=False, type="transform")
     if allList:
         for node in allList:
             if cmds.objExists(node+"."+MASTER_GRP) and cmds.getAttr(node+"."+MASTER_GRP) == 1:
                 self.masterGrp = node
     if self.masterGrp:
         masterCtrlList = cmds.listConnections(self.masterGrp+".masterCtrl")
         scalableGrpList = cmds.listConnections(self.masterGrp+".scalableGrp")
         if masterCtrlList:
             self.masterCtrl = masterCtrlList[0]
         if scalableGrpList:
             self.scalableGrp = scalableGrpList[0]
     
     # create Rivet_Grp in order to organize hierarchy:
     createdRivetGrp = False
     self.rivetGrp = rivetGrpName
     if not cmds.objExists(rivetGrpName):
         createdRivetGrp = True
         self.rivetGrp = cmds.group(name=rivetGrpName, empty=True)
         for attr in attrList:
             cmds.setAttr(self.rivetGrp+"."+attr, lock=True, keyable=False, channelBox=False)
         cmds.addAttr(self.rivetGrp, longName="dpRivetGrp", attributeType='bool')
         cmds.setAttr(self.rivetGrp+".dpRivetGrp", 1)
         if self.scalableGrp:
             cmds.parent(self.rivetGrp, self.scalableGrp)
         
     # get shape to attach:
     if cmds.objExists(geoToAttach):
         self.shapeToAttachList = cmds.ls(geoToAttach, dag=True, shapes=True)
     if self.shapeToAttachList:
         self.shapeToAttach = self.shapeToAttachList[0]
         # get shape type:
         self.shapeType = cmds.objectType(self.shapeToAttach)
         # verify if there are vertices, cv's or lattice points in our itemList:
         if itemList:
             asked = False
             for i, item in enumerate(itemList):
                 if ".vtx" in item or ".cv" in item or ".pt" in item:
                     if askComponent:
                         if not asked:
                             isComponent = cmds.confirmDialog(title="dpRivet on Components", message="How do you want attach vertices, cv's or lattice points?", button=("Individually", "Together", "Ignore"), defaultButton="Individually", dismissString="Ignore", cancelButton="Ignore")
                             asked = True
                             if isComponent == "Individually":
                                 cls = cmds.cluster(item, name=item[:item.rfind(".")]+"_"+str(i)+"_Cls")[0]+"Handle"
                                 clsToRivet = cmds.parent(cls, self.rivetGrp)[0]
                                 self.rivetList.append(clsToRivet)
                             elif isComponent == "Together":
                                 togetherList.append(item)
                             elif isComponent == "Ignore":
                                 itemList.remove(item)
                         elif isComponent == "Ignore":
                             itemList.remove(item)
                         elif isComponent == "Together":
                             togetherList.append(item)
                         else: #Individually
                             cls = cmds.cluster(item, name=item[:item.rfind(".")]+"_"+str(i)+"_Cls")[0]+"Handle"
                             clsToRivet = cmds.parent(cls, self.rivetGrp)[0]
                             self.rivetList.append(clsToRivet)
                     else: #Individually
                         cls = cmds.cluster(item, name=item[:item.rfind(".")]+"_"+str(i)+"_Cls")[0]+"Handle"
                         clsToRivet = cmds.parent(cls, self.rivetGrp)[0]
                         self.rivetList.append(clsToRivet)
                 elif cmds.objExists(item):
                     self.rivetList.append(item)
         else:
             mel.eval("error \"Select and add at least one item to be attached as a Rivet, please.\";")
         if isComponent == "Together":
             cls = cmds.cluster(togetherList, name="dpRivet_Cls")[0]+"Handle"
             clsToRivet = cmds.parent(cls, self.rivetGrp)[0]
             self.rivetList.append(clsToRivet)
         
         # check about locked or animated attributes on items:
         if not addFatherGrp:
             cancelProcess = False
             for rivet in self.rivetList:
                 # locked:
                 if cmds.listAttr(rivet, locked=True):
                     cancelProcess = True
                     break
                 # animated:
                 for attr in attrList:
                     if cmds.listConnections(rivet+"."+attr, source=True, destination=False):
                         cancelProcess = True
                         break
             if cancelProcess:
                 if createdRivetGrp:
                     cmds.delete(self.rivetGrp)
                 else:
                     for rivet in self.rivetList:
                         if not rivet in itemList:
                             # clear created clusters:
                             cmds.delete(rivet)
                 mel.eval("error \"Canceled process: items to be Rivet can't be animated or have locked attributes, sorry.\";")
                 return
         
         # workarount to avoid closestPoint node ignores transformations.
         # then we need to duplicate, unlock attributes and freezeTransformation:
         dupGeo = cmds.duplicate(geoToAttach, name=geoToAttach+"_dpRivet_TEMP_Geo")[0]
         # unlock attr:
         for attr in attrList:
             cmds.setAttr(dupGeo+"."+attr, lock=False)
         # parent to world:
         if cmds.listRelatives(dupGeo, allParents=True):
             cmds.parent(dupGeo, world=True)
         # freezeTransformation:
         cmds.makeIdentity(dupGeo, apply=True)
         dupShape = cmds.ls(dupGeo, dag=True, shapes=True)[0]
         
         # temporary transform node to store object's location:
         self.tempNode = cmds.createNode("transform", name=geoToAttach+"_dpRivet_TEMP_Transf", skipSelect=True)
             
         # working with mesh:
         if self.shapeType == "mesh":
             # working with uvSet:
             uvSetList = cmds.polyUVSet(dupShape, query=True, allUVSets=True)
             if len(uvSetList) > 1:
                 if not uvSetList[0] == uvSetName:
                     # change uvSet order because closestPointOnMesh uses the default uv set
                     cmds.polyUVSet(dupShape, copy=True, uvSet=uvSetName, newUVSet=uvSetList[0])
                     
             # closest point on mesh node:
             self.cpNode = cmds.createNode("closestPointOnMesh", name=geoToAttach+"_dpRivet_TEMP_CP", skipSelect=True)
             cmds.connectAttr(dupShape+".outMesh", self.cpNode+".inMesh", force=True)
             
             # move tempNode to cpNode position:
             cmds.connectAttr(self.tempNode+".translate", self.cpNode+".inPosition", force=True)
         
         else: #nurbsSurface
             uRange = cmds.getAttr(dupShape+".minMaxRangeU")[0]
             vRange = cmds.getAttr(dupShape+".minMaxRangeV")[0]
             
             # closest point on mesh node:
             self.cpNode = cmds.createNode("closestPointOnSurface", name=geoToAttach+"_dpRivet_TEMP_CP", skipSelect=True)
             cmds.connectAttr(dupShape+".local", self.cpNode+".inputSurface", force=True)
             
         # working with follicles and attaches
         for rivet in self.rivetList:
             rivetPos = cmds.xform(rivet, query=True, worldSpace=True, rotatePivot=True)
             if addFatherGrp:
                 rivet = cmds.group(rivet, name=rivet+"_Rivet_Grp")
                 cmds.xform(rivet, worldSpace=True, rotatePivot=(rivetPos[0], rivetPos[1], rivetPos[2]))
             
             # move temp tranform to rivet location:
             cmds.xform(self.tempNode, worldSpace=True, translation=(rivetPos[0], rivetPos[1], rivetPos[2]))
             
             # get uv coords from closestPoint node
             fu = cmds.getAttr(self.cpNode+".u")
             fv = cmds.getAttr(self.cpNode+".v")
             
             if self.shapeType == "nurbsSurface":
                 # normalize UVs:
                 fu = abs((fu - uRange[0])/(uRange[1] - uRange[0]))
                 fv = abs((fv - vRange[0])/(vRange[1] - vRange[0]))
                 
             # create follicle:
             folTransf = cmds.createNode("transform", name=rivet+"_Fol", parent=self.rivetGrp, skipSelect=True)
             folShape = cmds.createNode("follicle", name=rivet+"_FolShape", parent=folTransf, skipSelect=True)
             
             # connect geometry shape and follicle:
             if self.shapeType == "mesh":
                 cmds.connectAttr(self.shapeToAttach+".worldMesh[0]", folShape+".inputMesh", force=True)
                 cmds.setAttr(folShape+".mapSetName", uvSetName, type="string")
             else: #nurbsSurface:
                 cmds.connectAttr(self.shapeToAttach+".local", folShape+".inputSurface", force=True)
             cmds.connectAttr(self.shapeToAttach+".worldMatrix[0]", folShape+".inputWorldMatrix", force=True)
             cmds.connectAttr(folShape+".outRotate", folTransf+".rotate", force=True)
             cmds.connectAttr(folShape+".outTranslate", folTransf+".translate", force=True)
             # put follicle in the correct place:
             cmds.setAttr(folShape+".parameterU", fu)
             cmds.setAttr(folShape+".parameterV", fv)
             
             # attach follicle and rivet using constraint:
             if attachTranslate and attachRotate:
                 cmds.parentConstraint(folTransf, rivet, maintainOffset=True, name=rivet+"_ParentConstraint")
             elif attachTranslate:
                 cmds.parentConstraint(folTransf, rivet, maintainOffset=True, name=rivet+"_ParentConstraint" , skipRotate=("x", "y", "z"))
             elif attachRotate:
                 cmds.parentConstraint(folTransf, rivet, maintainOffset=True, name=rivet+"_ParentConstraint" , skipTranslate=("x", "y", "z"))
             
             # try to integrate to dpAutoRigSystem in order to keep the Rig as scalable:
             if self.masterCtrl:
                 cmds.scaleConstraint(self.masterCtrl, folTransf, maintainOffset=True, name=folTransf+"_ScaleConstraint")
         
         # check invert group (back) in order to avoide double transformations:
         if addInvert:
             for rivet in self.rivetList:
                 self.dpInvertAttrTranformation(rivet, invT, invR)
                 
         # clean-up temporary nodes:
         cmds.delete(dupGeo, self.cpNode, self.tempNode)
         
     else:
         mel.eval("error \"Load one geometry to attach Rivets on it, please.\";")
     
     cmds.select(clear=True)
Beispiel #52
0
def addCustomUDIMMeshAttributes(mesh_name):
    #Adding custom UDIM attribute to meshes in a group
    if not cmds.objExists('%s.udim' % mesh_name):
        cmds.addAttr(mesh_name, shortName='udim', longName='udim', at='short', defaultValue= 1002, keyable=True)
Beispiel #53
0
def createRbnCtrl(posGrpList=[],
                  radius=1,
                  side='',
                  firstJnt='',
                  secondJnt='',
                  nurbsName=''):
    skinJntNameList = []
    dtlCtrlNameList = []
    dtlCtrlZgrpNameList = []
    mainJntNameList = []
    mainCtrlNameList = []
    mainCtrlZgrpNameList = []
    posMainJntList = [firstJnt, secondJnt]
    mainJntPosList = []
    posMainJntDesList = ['_rbnStart', '_rbnMid', '_rbnEnd']
    firstJntName = firstJnt.split('_')[0]
    skinGrpName = firstJntName + '_rbnSkin' + side + '_grp'
    # * create skinJnt dltCtrl
    for i in range(0, len(posGrpList)):
        # nameing
        ctrlName = posGrpList[i].split('_')[0] + '_rbnDtl' + side + '_ctrl'
        jntName = posGrpList[i].split('_')[0] + '_rbnDtl' + side + '_jnt'
        # add jnt to List
        skinJntNameList.append(jntName)
        # create ctrl
        mc.circle(nr=(0, 1, 0), c=(0, 0, 0), n=ctrlName)
        mc.setAttr(ctrlName + '.sx', radius)
        mc.setAttr(ctrlName + '.sz', radius)
        mc.delete(ctrlName, ch=True)
        # create jnt
        mc.select(cl=True)
        mc.joint(n=jntName, p=[0, 0, 0])
        mc.select(cl=True)
        # make ctrl and jnt have the same pviot
        gn.parentConOffMainTain(jntName, posGrpList[i])
        gn.parentConOffMainTain(ctrlName, posGrpList[i])
        mc.makeIdentity(jntName, apply=True, t=1, r=1, s=1, n=2)
        # add dtlCtrl to list
        dtlCtrlNameList.append(ctrlName)
        # make zGrp
        dtlCtrlZgrpNameList.append(gn.zeroGroup(ctrlName, posGrpList[i]))
        # parentConstrain
        mc.parentConstraint(posGrpList[i], dtlCtrlZgrpNameList[i])
        # parent jnt to ctrl
        mc.parentConstraint(ctrlName, jntName, mo=False)
    # create skinGrp
    mc.group(em=True, n=skinGrpName)
    # parent skinJnt into skinGrp
    mc.parent(skinJntNameList, skinGrpName)
    # * create mainCtrl
    # get ThridJnt world Position
    mc.select(cl=True)
    thirdJnt = mc.joint(n='thirdJnt', p=[0, 0, 0])
    ampCon = mc.parentConstraint([firstJnt, secondJnt], thirdJnt)
    mc.delete(ampCon)
    # app posJnt to List at index 1
    posMainJntList.insert(1, thirdJnt)
    # get jnt position from posJnt
    mainJntPosList = list(map(gn.getWorldPosition, posMainJntList))
    # delete thirdJnr
    mc.delete(thirdJnt)
    for i in range(0, 3):
        mc.select(cl=True)
        jnt = mc.joint(n=firstJntName + posMainJntDesList[i] + side + '_jnt',
                       p=[0, 0, 0])
        ampCon = mc.parentConstraint(posGrpList[1], jnt, mo=False)
        mc.delete(ampCon)
        mc.setAttr(jnt + '.t', mainJntPosList[i][0], mainJntPosList[i][1],
                   mainJntPosList[i][2])
        # add each jnt to the List
        mainJntNameList.append(jnt)
        # nameing mainCtrl
        mainCtrlName = mainJntNameList[i].split(
            '_')[0] + posMainJntDesList[i] + side + '_ctrl'
        # create mainCtrl
        mainCtrlAmp = mc.curve(p=[(-1, 0, -1), (-1, 0, 1), (1, 0, 1),
                                  (1, 0, -1), (-1, 0, -1)],
                               k=[0, 1, 2, 3, 4],
                               d=1)
        mc.rename(mainCtrlAmp, mainCtrlName)
        mc.setAttr(mainCtrlName + '.sx', radius)
        mc.setAttr(mainCtrlName + '.sz', radius)
        # mark ctrl has same direction to jnt
        gn.parentConOffMainTain(mainCtrlName, jnt)
        # create zGrp and put into list
        mainCtrlZgrpNameList.append(gn.zeroGroup(mainCtrlName, mainCtrlName))
        mainCtrlNameList.append(mainCtrlName)
        mc.parent(jnt, mainCtrlName)

    # create ctrlGrp
    ctrlGrpName = mc.group(em=True,
                           n=firstJntName + '_rbnCtrl' + side + '_grp')
    # parentConstraint ctrlGrpName -> firstJnt
    mc.parentConstraint(firstJnt, ctrlGrpName)
    # pontConstraint endCtrl -> secondJnt
    mc.pointConstraint(secondJnt, mainCtrlZgrpNameList[-1], mo=True)
    # put all mainCtrl in to ctrlGrpName
    mc.parent(mainCtrlZgrpNameList, ctrlGrpName)

    dtlCtrlGrpName = mc.group(em=True,
                              n=firstJntName + '_rbnDtlCtrl' + side + '_grp')
    # parentConstraint ctrlGrpName -> dtlCtrlGrpName and then delete parent
    mc.delete(mc.parentConstraint(ctrlGrpName, dtlCtrlGrpName))
    # parent dtlCtrlGrpName -> ctrlGrpName
    mc.parent(dtlCtrlGrpName, ctrlGrpName)
    # parent dtlCtrlZgrpNameList -> dtlCtrlGrpName
    mc.parent(dtlCtrlZgrpNameList, dtlCtrlGrpName)
    # parentConstraint ctrlGrpName -> skinGrpName
    mc.parentConstraint(ctrlGrpName, skinGrpName, mo=True)
    mc.pointConstraint(mainJntNameList[0], mainJntNameList[-1],
                       mainCtrlZgrpNameList[1])

    # aim startJnt and ndJnt to midJnt
    if side == 'LFT':
        mc.aimConstraint(mainJntNameList[1],
                         mainJntNameList[0],
                         weight=1,
                         aimVector=(0, 1, 0),
                         upVector=(0, 0, 1),
                         worldUpType='objectrotation',
                         worldUpVector=(0, 0, 1),
                         worldUpObject=mainJntNameList[1])
        mc.aimConstraint(mainJntNameList[1],
                         mainJntNameList[2],
                         weight=1,
                         aimVector=(0, 1, 0),
                         upVector=(0, 0, 1),
                         worldUpType='objectrotation',
                         worldUpVector=(0, 0, 1),
                         worldUpObject=mainJntNameList[1])
        mc.aimConstraint(mainJntNameList[2],
                         mainCtrlZgrpNameList[1],
                         weight=1,
                         aimVector=(0, 1, 0),
                         upVector=(0, 0, 1),
                         worldUpType='objectrotation',
                         worldUpVector=(0, 0, 1),
                         worldUpObject=firstJnt)
    elif side == 'RGT':
        mc.aimConstraint(mainJntNameList[1],
                         mainJntNameList[0],
                         weight=1,
                         aimVector=(0, 1, 0),
                         upVector=(0, 0, 1),
                         worldUpType='objectrotation',
                         worldUpVector=(0, 0, 1),
                         worldUpObject=mainJntNameList[1])
        mc.aimConstraint(mainJntNameList[1],
                         mainJntNameList[2],
                         weight=1,
                         aimVector=(0, 1, 0),
                         upVector=(0, 0, 1),
                         worldUpType='objectrotation',
                         worldUpVector=(0, 0, 1),
                         worldUpObject=mainJntNameList[1])
        mc.aimConstraint(mainJntNameList[2],
                         mainCtrlZgrpNameList[1],
                         weight=1,
                         aimVector=(0, 1, 0),
                         upVector=(0, 0, 1),
                         worldUpType='objectrotation',
                         worldUpVector=(0, 0, 1),
                         worldUpObject=secondJnt)

    # bindSkin
    mc.skinCluster(mainJntNameList[0], mainJntNameList[1], mainJntNameList[2],
                   nurbsName)
    # setAttr skinGrp, startCtrl and endCtrl to be unseen
    mc.setAttr(skinGrpName + '.v', False)
    mc.setAttr(mainCtrlNameList[0] + '.v', False)
    mc.setAttr(mainCtrlNameList[2] + '.v', False)
    mc.setAttr(mainJntNameList[1] + '.v', False)
    # add attr dtlCtrl to mid ctrl
    mc.addAttr(mainCtrlNameList[1] + 'Shape',
               ln='detailCtrl',
               at='double',
               min=0,
               max=1,
               dv=0,
               k=True)
    # connecting Attr
    mc.connectAttr(mainCtrlNameList[1] + 'Shape.detailCtrl',
                   dtlCtrlGrpName + '.v')
    # return dtlCtrlZgrpNameList ,mainCtrlZgrpNameList, skinJntNameList
    return {
        'dtlCtrlNameList': dtlCtrlNameList,
        'mainCtrlNameList': mainCtrlNameList,
        'skinJntNameList': skinJntNameList
    }
Beispiel #54
0
    def createPalmCtrls(self, jntPalmBase, leftRight, colourTU, jntPalm,
                        isLeft, *args):

        # create the CTRL, then move it
        handOffsetCtrl = CRU.createCTRLs(jntPalmBase,
                                         5,
                                         ornt=True,
                                         pnt=True,
                                         colour=colourTU,
                                         orientVal=(1, 0, 0))
        handLength = mc.getAttr("{0}.ty".format(jntPalm[1]))
        mc.select(handOffsetCtrl[1] + ".cv[:]")
        moveX = -handLength / 2
        mc.move(moveX, handLength * 0.5, 0, r=True, ls=True)

        # add the twist limits for the wrists:
        lowerTwistVal = "lowerArmTwist"
        upperTwistVal = "upperArmTwist"
        mc.addAttr(handOffsetCtrl[1],
                   longName=lowerTwistVal,
                   at="float",
                   k=True,
                   min=0,
                   max=1,
                   dv=1)
        mc.addAttr(handOffsetCtrl[1],
                   longName=upperTwistVal,
                   at="float",
                   k=True,
                   min=0,
                   max=1,
                   dv=1)

        # get the expression (this is a bit unique to me) then edit it
        armExprName = "expr" + leftRight + "armTwist"
        armExpr = mc.expression(armExprName, q=True, s=True)

        ctrlPalmName = "CTRL" + leftRight + "palm"
        armExpr = armExpr.replace("armEnd", "palm")
        armExpr = armExpr.replace("JNT" + leftRight + "palm", ctrlPalmName)
        editExpr = armExpr.splitlines()
        for i in range(len(editExpr)):
            if "lowerArm.rotate" in editExpr[i]:
                # if we're rotating the upper arm twists with the lower arm
                replaceTwistVal = upperTwistVal
            elif "palm.rotate" in editExpr[i]:
                # if we're rotating the lower arm twists with the palm
                replaceTwistVal = lowerTwistVal

            editExpr[i] = editExpr[i].replace(
                ";", " * {0}.{1};\n".format(ctrlPalmName, replaceTwistVal))
            # print(editExpr[i])

        armExprReplace = "".join(editExpr)
        # print(armExprReplace)
        mc.delete(armExprName)

        mc.expression(s=armExprReplace, n=armExprName)

        # change the rotation order
        toRotateChange = [handOffsetCtrl[1], jntPalmBase]
        CRU.changeRotateOrder(toRotateChange, "YZX")

        return handOffsetCtrl
Beispiel #55
0
def createMasterBodyCog(rig, master, body, cog, root, traj):
    """Creates top rig hierarchy """

    master_ctl = None
    master_offset_ctl = None
    body_ctl = None
    piv_inv = None
    root_jnt = None

    if master:
        # Create buffer and scene_offset nodes
        master_GRP = cmds.createNode("transform", name=MASTER.replace(CTL, GRP))
        scene_OFF = cmds.createNode("transform", name="sceneOffset_{}".format(GRP))

        # Master and master_offset
        master_ctl = master.name()
        master_ctl_parent = cmds.listRelatives(master_ctl, parent=True)
        if master_ctl_parent:
            cmds.parent(master_GRP, master_ctl_parent)

        master_offset_ctl = ""
        if cmds.objExists(MASTER_OFFSET):
            master_offset_ctl = MASTER_OFFSET

        attrs_show(TRS, node=master_ctl)
        attrs_show(TRS, node=master_offset_ctl)

        cmds.parent(scene_OFF, master_GRP)
        cmds.parent(master_ctl, scene_OFF)

        # Try to parent master_grp under rig node
        try:
            cmds.parent(master_GRP, rig['rigGroup'])
        except:
            pass

        # Setup global scale on master and connect to master_offset
        cmds.addAttr(master_ctl, ln="globalScale", min=0.0001, dv=1)
        cmds.setAttr("{}.globalScale".format(master_ctl), edit=True, l=False, k=True)

        for attr in ['sx', 'sy', 'sz']:
            cmds.connectAttr("{}.globalScale".format(master_ctl), "{}.{}".format(master_offset_ctl, attr))
            cmds.setAttr("{}.{}".format(master_offset_ctl, attr), lock=True)
            cmds.setAttr("{}.{}".format(master_ctl, attr), lock=True)

        # Set channels
        attrs_lock_hide(SV, node=master_ctl)
        attrs_lock_hide(SV, node=master_offset_ctl)

        # Meta types
        dragonfly.modules.add_metatype(master_ctl, dragonfly.meta_types.MTYPE_MASTER)
        dragonfly.modules.add_metatype(master_offset_ctl, dragonfly.meta_types.MTYPE_MASTER_OFFSET)
        dragonfly.modules.add_metatype(master_ctl, dragonfly.meta_types.MTYPE_CTL)
        dragonfly.modules.add_metatype(master_offset_ctl, dragonfly.meta_types.MTYPE_CTL)


    if body:
        # Create buffer
        body_BUF = cmds.createNode("transform", name=BODY.replace(CTL, BUF))

        # Body control
        body_ctl = body.name()
        match_nodes(body_ctl, body_BUF)
        cmds.parent(body_ctl, body_BUF)

        if cmds.objExists(MASTER_OFFSET):
            cmds.parent(body_BUF, MASTER_OFFSET)
        else:
            cmds.parent(body_BUF, MASTER)

        piv_inv = add_movable_pivot(BODY.replace("_{}".format(CTL), ""), body_ctl)

        # Set channels
        attrs_lock_hide(SV, node=body_ctl)

        # Meta type
        dragonfly.modules.add_metatype(body_ctl, dragonfly.meta_types.MTYPE_BODY)

    if cog:
        # Create buffer
        cog_BUF = cmds.createNode("transform", name=COG.replace(CTL, BUF))
        cog_ctl = cog.name()
        match_nodes(cog_ctl, cog_BUF)

        if body_ctl:
            cmds.parent(cog_BUF, BODY)
            cog_off = cmds.createNode("transform", name=COG.replace(CTL, OFF))
            match_nodes(cog_ctl, cog_off)
            cmds.parent(cog_off, cog_BUF)
            cmds.parent(cog_ctl, cog_off)
            cmds.parentConstraint(piv_inv, cog_BUF, mo=True)
        else:
            cmds.parent(cog_ctl, cog_BUF)

        # Set channels
        attrs_lock_hide(SV, node=cog_ctl)

        # Meta type
        dragonfly.modules.add_metatype(cog_ctl, dragonfly.meta_types.MTYPE_COG)


    if root:
        root_jnt = root.name()
        attrs_show(TRSV, node=root_jnt)

        if master_offset_ctl:
            cmds.parentConstraint(master_offset_ctl, root_jnt)
            cmds.scaleConstraint(master_offset_ctl, root_jnt)

        try:
            skel_grp = rig['skeletonGroup']
            if skel_grp:  cmds.parent(root_jnt, skel_grp)
        except:
            pass

        # Meta type
        dragonfly.modules.add_metatype(root_jnt, dragonfly.meta_types.MTYPE_ROOT)


    if traj:
        if master_ctl and root_jnt:
            traj = trajectoryControl(masterControl=master_ctl, rootJoints=[root_jnt])
            attrs_lock_hide(SV, node=traj)
            dragonfly.modules.add_metatype(traj, dragonfly.meta_types.MTYPE_TRAJECTORY)
Beispiel #56
0
def rbnSquash(midCtrl='',
              ctrlGrpName='',
              crvShape='',
              dtlCtrlList=[],
              skinJntNameList=[],
              side=''):
    squashRatio = [0.15, 0.5, 1.0, 0.5, 0.15]
    autoSquashName = midCtrl.split('_')[0]
    # globalCrv setup
    globalCrvName = autoSquashName + '_rbnGlobal' + side + '_crv'
    cifAutoGlobalNode = autoSquashName + '_rbnGlobal' + side + '_cif'
    cifAutoNode = midCtrl.split('_')[0] + '_rbn' + side + '_cif'
    mc.duplicate(crvShape, n=globalCrvName)
    mc.createNode('curveInfo', n=cifAutoGlobalNode)
    mc.createNode('curveInfo', n=cifAutoNode)
    mc.parent(globalCrvName, ctrlGrpName)
    mc.connectAttr(globalCrvName + 'Shape.worldSpace',
                   cifAutoGlobalNode + '.inputCurve')
    mc.connectAttr(crvShape + 'Shape.worldSpace', cifAutoNode + '.inputCurve')
    # autoSquash setup
    autoNodeDesc = 'rbnAutoSquash' + side
    mdvAutoNodeName = mc.createNode('multiplyDivide',
                                    n=autoSquashName + '_' + autoNodeDesc +
                                    '_mdv')
    addAutoNodeName = mc.createNode('addDoubleLinear',
                                    n=autoSquashName + '_' + autoNodeDesc +
                                    '_add')
    multAutoNodeName = mc.createNode('multDoubleLinear',
                                     n=autoSquashName + '_' + autoNodeDesc +
                                     '_mult')
    mc.setAttr(addAutoNodeName + '.input2', -1)
    mc.setAttr(mdvAutoNodeName + '.operation', 2)
    # midCtrl setup
    mc.addAttr(midCtrl,
               ln='autoSquash',
               at='double',
               min=0,
               max=1,
               dv=0,
               k=True)
    mc.addAttr(midCtrl, ln='squash', at='double', dv=0, k=True)
    mc.connectAttr(midCtrl + '.autoSquash', multAutoNodeName + '.input2')
    # autoSquash connect
    mc.connectAttr(cifAutoGlobalNode + '.arcLength',
                   mdvAutoNodeName + '.input1.input1X')
    mc.connectAttr(cifAutoNode + '.arcLength',
                   mdvAutoNodeName + '.input2.input2X')
    mc.connectAttr(mdvAutoNodeName + '.output.outputX',
                   addAutoNodeName + '.input1')
    mc.connectAttr(addAutoNodeName + '.output', multAutoNodeName + '.input1')

    for i in range(0, len(skinJntNameList)):
        # setup mdv, pma Node
        squashName = skinJntNameList[i].split('_')[0]
        mdvNodeName = squashName + '_rbnSquash' + side + '_mdv'
        pmaNodeName = squashName + '_rbnSquash' + side + '_pma'
        mc.createNode('multiplyDivide', n=mdvNodeName)
        mc.createNode('plusMinusAverage', n=pmaNodeName)
        mc.setAttr(pmaNodeName + '.input2D[0].input2Dx', 1)
        mc.setAttr(mdvNodeName + '.input2X', squashRatio[i])
        mc.setAttr(mdvNodeName + '.input2Y', squashRatio[i])
        # connect mdv, pma Node
        mc.connectAttr(mdvNodeName + '.outputX',
                       pmaNodeName + '.input2D[1].input2Dx')
        mc.connectAttr(mdvNodeName + '.outputY',
                       pmaNodeName + '.input2D[2].input2Dx')
        mc.connectAttr(mdvNodeName + '.outputZ',
                       pmaNodeName + '.input2D[3].input2Dx')
        mc.connectAttr(pmaNodeName + '.output2D.output2Dx',
                       skinJntNameList[i] + '.scale.scaleX')
        mc.connectAttr(pmaNodeName + '.output2D.output2Dx',
                       skinJntNameList[i] + '.scale.scaleZ')
        # dtlCtrl setup
        mc.addAttr(dtlCtrlList[i], ln='squash', at='double', dv=0, k=True)
        # dtlCtrl connect
        mc.connectAttr(dtlCtrlList[i] + '.squash',
                       mdvNodeName + '.input1.input1Z')
        # dtlCtrl connect
        mc.connectAttr(midCtrl + '.squash', mdvNodeName + '.input1.input1Y')
        # midCtrl connect
        mc.connectAttr(multAutoNodeName + '.output',
                       mdvNodeName + '.input1.input1X')
Beispiel #57
0
    def testGetVtValue(self):
        cmds.file(new=True, force=True)

        cmds.group(name="group1", empty=True)

        mat = UsdMaya.WriteUtil.GetVtValue("group1.matrix",
                Sdf.ValueTypeNames.Matrix4d)
        self.assertEqual(mat, Gf.Matrix4d(1.0))

        vec3f = UsdMaya.WriteUtil.GetVtValue("group1.scale",
                Sdf.ValueTypeNames.Vector3f)
        self.assertEqual(vec3f, Gf.Vec3f(1.0))
        self.assertIsInstance(vec3f, Gf.Vec3f)

        vec3d = UsdMaya.WriteUtil.GetVtValue("group1.scale",
                Sdf.ValueTypeNames.Vector3d)
        self.assertEqual(vec3d, Gf.Vec3d(1.0))
        self.assertIsInstance(vec3d, Gf.Vec3d)

        cmds.addAttr("group1", ln="myArray", dt="vectorArray")
        cmds.setAttr("group1.myArray", 3, (0, 1, 2), (1, 2, 3), (2, 3, 4),
                type="vectorArray")
        float3Array = UsdMaya.WriteUtil.GetVtValue("group1.myArray",
                Sdf.ValueTypeNames.Float3Array)
        self.assertEqual(float3Array,
                Vt.Vec3fArray([(0, 1, 2), (1, 2, 3), (2, 3, 4)]))
        point3Array = UsdMaya.WriteUtil.GetVtValue("group1.myArray",
                Sdf.ValueTypeNames.Point3dArray)
        self.assertEqual(point3Array,
                Vt.Vec3dArray([(0, 1, 2), (1, 2, 3), (2, 3, 4)]))

        # Strings can be strings, tokens, or asset paths.
        cmds.addAttr("group1", ln="myString", dt="string")
        cmds.setAttr("group1.myString", "a_b_c", type="string")
        string = UsdMaya.WriteUtil.GetVtValue("group1.myString",
                Sdf.ValueTypeNames.String)
        self.assertEqual(string, "a_b_c")
        token = UsdMaya.WriteUtil.GetVtValue("group1.myString",
                Sdf.ValueTypeNames.Token) # alas, this becomes a str in Python
        self.assertEqual(token, "a_b_c")
        token = UsdMaya.WriteUtil.GetVtValue("group1.myString",
                Sdf.ValueTypeNames.Asset)
        self.assertEqual(token, Sdf.AssetPath("a_b_c"))

        # Colors have display-to-linear conversion applied.
        cmds.addAttr("group1", ln="myColor", at="double3")
        cmds.addAttr("group1", ln="myColorX", p="myColor", at="double")
        cmds.addAttr("group1", ln="myColorY", p="myColor", at="double")
        cmds.addAttr("group1", ln="myColorZ", p="myColor", at="double")
        cmds.setAttr("group1.myColor", 0.5, 0.5, 0.5)
        color3f = UsdMaya.WriteUtil.GetVtValue("group1.myColor",
                Sdf.ValueTypeNames.Color3f)
        self.assertAlmostEqual(color3f[0], 0.2176376)
        vec3f = UsdMaya.WriteUtil.GetVtValue("group1.myColor",
                Sdf.ValueTypeNames.Vector3f)
        self.assertAlmostEqual(vec3f[0], 0.5)
Beispiel #58
0
def forearmTwistRig(color, rollGrpParent, fkArmJoint, ikArmJoint, suffix, name,
                    prefix, lowerArm):
    print "START Building the " + suffix + " lower arm twists---------------------------------------"

    print "suffix = " + suffix
    print "name = " + name
    print "prefix = " + prefix
    print "lowerArm = " + lowerArm

    # create a nice name
    name = prefix + name + suffix
    if name.find("_") == 0:
        name = name.partition("_")[2]
        lowerarm = prefix + lowerArm + suffix
        driver_lowerarm = "driver_" + prefix + lowerArm + suffix
        driver_hand = "driver_hand_" + name

        numRolls = 0
        for joint in [
                "_twist_01", "_twist_02", "_twist_03", "_twist_04",
                "_twist_05", "_twist_06"
        ]:
            if cmds.objExists("driver_" + prefix + lowerArm + joint + suffix):
                numRolls = numRolls + 1

        print "...There are a total of " + str(numRolls) + " to build."

        for i in range(int(numRolls)):
            print "...Building lower arm twist_0" + str(i + 1)
            driver_lowerarm_twist = "driver_" + prefix + lowerArm + "_twist_0" + str(
                i + 1) + suffix

            # create our roll group
            rollGrp = cmds.group(empty=True,
                                 name=lowerarm + "_roll_grp_0" + str(i + 1))
            cmds.parent(rollGrp, "arm_sys_grp")

            # Make sure the twist joint is exactly at the hand and aimed at the lowerarm
            #NOTE if the "side" method Jeremy is using in here(name) is intended to handle more than just "l" and "r" then the move part of this must be re-written to handle that accordingly.
            '''if i == 0:
                const = cmds.parentConstraint(driver_hand, driver_lowerarm_twist, weight=1, mo=False, sr=["x","y","z"])
                cmds.delete(const)
                cmds.select(driver_lowerarm_twist, r=True)
                if name == "l":
                    cmds.move(-0.995369, 0, 0, driver_lowerarm_twist, r = True)
                else:
                    cmds.move(0.995369, 0, 0, driver_lowerarm_twist, r = True)
                cmds.makeIdentity(driver_lowerarm_twist, r = 1, t = 1, s = 1, apply =True)'''

            # create a new heirarchy out of the driver skeleton
            driver_lowerarm_offset = cmds.duplicate(
                driver_lowerarm,
                po=True,
                name=driver_lowerarm + "_Offset_0" + str(i + 1))[0]
            cmds.parent(driver_lowerarm_offset, rollGrp)
            cmds.setAttr(driver_lowerarm_offset + ".rotateOrder", 1)
            cmds.setAttr(driver_lowerarm_offset + ".v", 1)

            driver_lowerarm_twist_offset = cmds.duplicate(
                driver_lowerarm_twist,
                po=True,
                name=driver_lowerarm_twist + "_Offset")[0]
            cmds.parent(driver_lowerarm_twist_offset, driver_lowerarm_offset)
            cmds.setAttr(driver_lowerarm_twist_offset + ".rotateOrder", 1)
            cmds.setAttr(driver_lowerarm_twist_offset + ".v", 1)

            driver_hand_offset = cmds.duplicate(driver_lowerarm_twist_offset,
                                                po=True,
                                                name=driver_hand +
                                                "_Offset_0" + str(i + 1))[0]
            const = cmds.parentConstraint(driver_hand,
                                          driver_hand_offset,
                                          weight=1,
                                          mo=False,
                                          sr=["x", "y", "z"])
            cmds.delete(const)
            cmds.setAttr(driver_hand_offset + ".rotateOrder", 1)
            cmds.setAttr(driver_hand_offset + ".v", 1)

            # create the manual twist control
            if i == 0:
                twistCtrl = utils.createControl("circle", 15,
                                                lowerarm + "_twist_anim")
            else:
                twistCtrl = utils.createControl(
                    "circle", 15, lowerarm + "_twist" + str(i + 1) + "_anim")
            cmds.setAttr(twistCtrl + ".ry", -90)
            cmds.setAttr(twistCtrl + ".sx", 0.8)
            cmds.setAttr(twistCtrl + ".sy", 0.8)
            cmds.setAttr(twistCtrl + ".sz", 0.8)
            cmds.makeIdentity(twistCtrl, r=1, s=1, apply=True)

            # move the manual control to the correct location
            constraint = cmds.parentConstraint(driver_lowerarm_twist_offset,
                                               twistCtrl)[0]
            cmds.delete(constraint)

            # create a group for the manual control and parent the twist to it.
            twistCtrlGrp = cmds.group(empty=True, name=twistCtrl + "_grp")
            constraint = cmds.parentConstraint(driver_lowerarm_twist_offset,
                                               twistCtrlGrp)[0]
            cmds.delete(constraint)

            cmds.parent(twistCtrl, twistCtrlGrp)
            cmds.parent(twistCtrlGrp, rollGrp)
            cmds.makeIdentity(twistCtrl, t=1, r=1, s=1, apply=True)
            cmds.parentConstraint(driver_lowerarm_twist_offset, twistCtrlGrp)

            # set the manual controls visibility settings
            cmds.setAttr(twistCtrl + ".overrideEnabled", 1)
            cmds.setAttr(twistCtrl + ".overrideColor", color)
            for attr in [".sx", ".sy", ".sz"]:
                cmds.setAttr(twistCtrl + attr, lock=True, keyable=False)
            cmds.setAttr(twistCtrl + ".v", keyable=False)

            # add attr on rig settings for manual twist control visibility
            cmds.select("Rig_Settings")
            if i == 0:
                cmds.addAttr(longName=(name + "twistCtrlVisLower"),
                             at='bool',
                             dv=0,
                             keyable=True)
            cmds.connectAttr("Rig_Settings." + name + "twistCtrlVisLower",
                             twistCtrl + ".v")

            # add attr to rig settings for the twist ammount values
            cmds.select("Rig_Settings")
            cmds.addAttr(longName=(name + "ForearmTwist" + str(i + 1) +
                                   "Amount"),
                         defaultValue=0.5,
                         minValue=0,
                         maxValue=1,
                         keyable=True)
            for u in range(int(i + 1)):
                cmds.setAttr(
                    "Rig_Settings." + name + "ForearmTwist" + str(u + 1) +
                    "Amount", (1.0 / (i + 2.0) * ((2.0 - u) + (i - 1.0))))

            # Create a locator and group for the up vector of the aim for the twist.
            forearmTwistUp = cmds.spaceLocator(n="forearmTwistUp_0" +
                                               str(i + 1) + "_" + name)[0]
            constraint = cmds.parentConstraint(driver_hand_offset,
                                               forearmTwistUp)[0]
            cmds.delete(constraint)
            forearmTwistUpGrp = cmds.duplicate(driver_hand_offset,
                                               po=True,
                                               name=forearmTwistUp + "_grp")[0]
            cmds.parent(forearmTwistUpGrp, rollGrp)
            cmds.parent(forearmTwistUp, forearmTwistUpGrp)
            cmds.setAttr(forearmTwistUpGrp + ".rotateOrder", 1)
            cmds.setAttr(forearmTwistUp + ".v", 0)

            # constrain the up group into the rig so that it takes the correct ammount of the twist
            forearmGrpPrntConst = cmds.parentConstraint(driver_lowerarm_offset,
                                                        driver_hand_offset,
                                                        forearmTwistUpGrp,
                                                        mo=True)[0]
            cmds.setAttr(forearmGrpPrntConst + ".interpType", 2)
            cmds.move(0, 0, 6, forearmTwistUp, r=True)

            twistAimConst = cmds.aimConstraint(driver_hand_offset,
                                               driver_lowerarm_twist_offset,
                                               weight=1,
                                               mo=True,
                                               aimVector=(1, 0, 0),
                                               upVector=(0, 0, 1),
                                               worldUpType="object",
                                               worldUpObject=forearmTwistUp)[0]

            # constrain the offsets back to the original driver skeleton
            cmds.parentConstraint(driver_hand, driver_hand_offset, mo=True)
            cmds.parentConstraint(driver_lowerarm,
                                  driver_lowerarm_offset,
                                  mo=True)

            # hook up the nodes to drive the twist based on the values on the rig settings node.
            reverseNode = cmds.shadingNode("reverse",
                                           asUtility=True,
                                           name=forearmGrpPrntConst +
                                           "_reverse")
            cmds.connectAttr("Rig_Settings." + name + "ForearmTwist" +
                             str(i + 1) + "Amount",
                             forearmGrpPrntConst + "." + driver_hand_offset +
                             "W1",
                             f=True)
            cmds.connectAttr("Rig_Settings." + name + "ForearmTwist" +
                             str(i + 1) + "Amount",
                             reverseNode + ".inputX",
                             f=True)
            cmds.connectAttr(reverseNode + ".outputX",
                             forearmGrpPrntConst + "." +
                             driver_lowerarm_offset + "W0",
                             f=True)

            #constrain driver joint to twist joint
            cmds.parentConstraint(twistCtrl, driver_lowerarm_twist, mo=True)

    print ".END Building the " + suffix + " lower arm twists---------------------------------------"
Beispiel #59
0
def lidSurface_create(curveList, spans=4, attributeObject='', collisionObject='', side='', prefix=''):
    """
    Generate a lidSurface setup from the specified curve list and input parameters
    @param curveList: List of curves to generate the lidSurface from
    @type curveList: list
    @param spans: Number of verticle spans form each lid surface
    @type spans: int
    @param attributeObject: Object that will hold attributes form manipulating the lidSurface node
    @type attributeObject: str
    @param collisionObject: Nurbs surface object that will be used as a collision object for the lid surfaces
    @type collisionObject: str
    @param side: The side of the face the eyelid is on. ("lf" or "rt")
    @type side: str
    @param prefix: Name prefix for all created nodes
    @type prefix: str
    """

    # NameUtil
    nameUtil = gLib.common.namingConvention.NamingConvention()
    # Check prefix
    if not prefix: prefix = nameUtil.stripSuffix(crvList[0], '_')
    # Check side
    if not side: side = prefix.split('_')[0]

    # Check curveList
    for crv in curveList:
        if not cmds.objExists(crv):
            raise UserInputError('Curve "' + crv + '" does not exist!')
        if not gLib.rig.utilities.curve.isCurve(crv):
            raise UserInputError('Object "' + crv + '" is not a valid nurbs curve!')

    # Create lidSurface node
    lidSurface = nameUtil.appendName(prefix, nameUtil.node['lidSurface'])
    lidSurface = cmds.createNode('lidSurface', n=lidSurface)

    # Set spans
    cmds.setAttr(lidSurface + '.spans', spans)

    # Connect curevList
    for i in range(len(curveList)):
        cmds.connectAttr(curveList[i] + '.worldSpace', lidSurface + '.inputCurve[' + str(i) + ']', f=True)

    # Check Attribute Object
    if cmds.objExists(attributeObject):
        # Check attributes
        if not cmds.objExists(attributeObject + '.' + side + 'TopLid'):
            cmds.addAttr(attributeObject, ln=side + 'TopLid', min=-1, max=1, dv=0, k=True)
        if not cmds.objExists(attributeObject + '.' + side + 'LowLid'):
            cmds.addAttr(attributeObject, ln=side + 'LowLid', min=-1, max=1, dv=0, k=True)
        if not cmds.objExists(attributeObject + '.' + side + 'LidMeet'):
            cmds.addAttr(attributeObject, ln=side + 'LidMeet', min=0, max=1, dv=0.5, k=True)
        # Connect Attributes
        cmds.connectAttr(attributeObject + '.' + side + 'TopLid', lidSurface + '.top', f=True)
        cmds.connectAttr(attributeObject + '.' + side + 'LowLid', lidSurface + '.bottom', f=True)
        cmds.connectAttr(attributeObject + '.' + side + 'LidMeet', lidSurface + '.split', f=True)

    # Check Collision Object
    if cmds.objExists(collisionObject):
        if not gLib.rig.utilities.surface.isSurface(collisionObject):
            raise UserInputError('Collision object "' + crv + '" is not a valid nurbs surface!')
        # cmds.connectAttr(collisionObject+'.worldMatrix[0]',lidSurface+'.collisionMatrix',f=True)
        cmds.connectAttr(collisionObject + '.worldSpace', lidSurface + '.collisionGeometry', f=True)

    # Create lid surfaces
    topLid_srf = nameUtil.appendName(prefix + '_tp01', nameUtil.node['surface'])
    topLid_srf = cmds.nurbsPlane(ch=0, n=topLid_srf)[0]
    lowLid_srf = nameUtil.appendName(prefix + '_lw01', nameUtil.node['surface'])
    lowLid_srf = cmds.nurbsPlane(ch=0, n=lowLid_srf)[0]

    # Attach lid surfaces
    cmds.connectAttr(lidSurface + '.topLidSurface', topLid_srf + '.create', f=True)
    cmds.connectAttr(lidSurface + '.lowLidSurface', lowLid_srf + '.create', f=True)

    # Return result
    return (topLid_srf, lowLid_srf)
Beispiel #60
0
def create(geo, prefix=''):
    """
    """
    # Check prefix
    if not prefix: prefix = geo

    # Create Deformer
    sMod = cmds.softMod(geo, n=prefix + '_softMod')
    sModHandle = sMod[1]
    sMod = sMod[0]
    sModBase = cmds.duplicate(sModHandle, po=True,
                              n=prefix + '_softModBase')[0]

    # Get Handle pivot
    piv = cmds.xform(sModHandle, q=True, ws=True, rp=True)

    # Initiate Control Builder
    ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()

    # Create Base control
    base_grp = cmds.createNode('transform', n=prefix + '_softModBase_grp')
    base_ctrl = cmds.createNode('transform',
                                n=prefix + '_softModBase_ctrl',
                                p=base_grp)
    base_ctrlShape = ctrlBuilder.controlShape(base_ctrl, 'box', scale=2)

    # Create Offset control
    offset_grp = cmds.createNode('transform',
                                 n=prefix + '_softModOffset_grp',
                                 p=base_ctrl)
    offset_ctrl = cmds.createNode('transform',
                                  n=prefix + '_softModOffset_ctrl',
                                  p=offset_grp)
    offset_ctrlShape = ctrlBuilder.controlShape(offset_ctrl,
                                                'sphere',
                                                scale=0.25)

    # Create Falloff control
    falloff_grp = cmds.createNode('transform',
                                  n=prefix + '_softModFalloff_grp',
                                  p=base_ctrl)
    falloff_ctrl = cmds.createNode('transform',
                                   n=prefix + '_softModFalloff_ctrl',
                                   p=falloff_grp)
    falloff_ctrlShape = ctrlBuilder.controlShape(falloff_ctrl,
                                                 'circle',
                                                 scale=1)
    falloff_loc = cmds.spaceLocator(n=prefix + '_softModFalloff_loc')[0]
    cmds.parent(falloff_loc, falloff_ctrl)
    cmds.addAttr(falloff_ctrl, ln='radius', min=0.001, dv=1, k=True)
    cmds.setAttr(falloff_loc + '.v', 0)

    # Move hierarchy into place
    cmds.move(piv[0], piv[1], piv[2], base_grp, a=True)

    # Connect to deformer
    cmds.connectAttr(falloff_loc + '.worldPosition[0]',
                     sMod + '.falloffCenter',
                     f=True)
    cmds.connectAttr(falloff_ctrl + '.radius', sMod + '.falloffRadius', f=True)
    cmds.connectAttr(sModBase + '.worldInverseMatrix[0]',
                     sMod + '.bindPreMatrix',
                     f=True)

    # Parent and constrain softMod elements
    cmds.parentConstraint(offset_ctrl, sModHandle, mo=True)
    cmds.scaleConstraint(offset_ctrl, sModHandle, mo=True)
    cmds.parentConstraint(base_ctrl, sModBase, mo=True)
    cmds.scaleConstraint(base_ctrl, sModBase, mo=True)
    cmds.parent(sModHandle, sModBase)
    cmds.parent(sModBase, base_grp)

    # Return result
    return sMod