Exemple #1
0
def selectBaseObjectButton(*args):
	selectedObject = cmds.ls(sl=True, fl=True)
	pickBaseObject(selectedObject)
	global isObj
	isObj = False
	if 'transform' in cmds.ls(sl=True, fl=True, st=True):
		isObj = True
Exemple #2
0
def export_skin(file_path=None, shapes=None):
    """Exports the skinClusters of the given shapes to disk in a pickled list of skinCluster data.

    :param file_path: Path to export the data.
    :param shapes: Optional list of dag nodes to export skins from.  All descendent nodes will be searched for
    skinClusters also.
    """
    if shapes is None:
        shapes = cmds.ls(sl=True) or []

    # If no shapes were selected, export all skins
    skins = get_skin_clusters(shapes) if shapes else cmds.ls(type='skinCluster')
    if not skins:
        raise RuntimeError('No skins to export.')

    if file_path is None:
        file_path = cmds.fileDialog2(dialogStyle=2, fileMode=0, fileFilter='Skin Files (*{0})'.format(EXTENSION))
        if file_path:
            file_path = file_path[0]
    if not file_path:
        return
    if not file_path.endswith(EXTENSION):
        file_path += EXTENSION

    all_data = []
    for skin in skins:
        skin = SkinCluster(skin)
        data = skin.gather_data()
        all_data.append(data)
        logging.info('Exporting skinCluster %s (%d influences, %d vertices)',
                     skin.node, len(data['weights'].keys()), len(data['blendWeights']))
    fh = open(file_path, 'wb')
    pickle.dump(all_data, fh, pickle.HIGHEST_PROTOCOL)
    fh.close()
Exemple #3
0
def edgeLoopWeights(edgeList):
    """
    """
    # Check Edge List
    if not edgeList: raise Exception('Invalid or empty edge list!')
    edgeList = cmds.filterExpand(edgeList, ex=True, sm=32) or []
    if not edgeList: raise Exception('Invalid edge list! List of polygon edges required...')

    # Get Mesh from Edges
    mesh = list(set(cmds.ls(edgeList, o=True) or []))
    if len(mesh) > 1:
        raise Exception('Edges from multiple mesh shapes were supplied! ' + str(mesh))
    mesh = mesh[0]

    for edge in edgeList:
        # Get Edge ID
        edgeID = glTools.utils.component.index(edge)

        # Get Vertices from Edge
        edgeVerts = cmds.polyListComponentConversion(edge, fe=True, tv=True)

        # Get Average Vertex Weights
        cmds.select(edgeVerts)
        glTools.tools.copyPasteWeights.averageWeights()

        # Select Edge Loop Vertices
        cmds.polySelect(mesh, edgeLoop=edgeID)
        loopEdges = cmds.ls(sl=1, fl=1)
        loopVerts = cmds.polyListComponentConversion(loopEdges, fe=True, tv=True)
        cmds.select(loopVerts)
        glTools.tools.copyPasteWeights.pasteWeights()

    # Return Result
    return mesh
Exemple #4
0
def blendAttrs(targ1=None, targ2=None, driven=None, blendAttr=None, translate=1, rotate=1):
    '''
    sets up blending of translation / rotation values from targs 1 & 2 on the driven node.
    If a blendAttr is supplied, this is connected to the blender value
    
    '''
    if not targ1 and not targ2 and not driven:
        if len(cmds.ls(sl=1)) == 3:
            targ1 = cmds.ls(sl=1)[0]
            targ2 = cmds.ls(sl=1)[1]
            driven = cmds.ls(sl=1)[2]
        else:
            return showDialog( 'Argument Error', 'Please supply or select targ1, targ2 and driven nodes' )
    
    if translate:
        t_bc = cmds.createNode('blendColors', name='%s_translate_bc' % driven)
        cmds.connectAttr('%s.t' % targ2, '%s.color1' % t_bc)
        cmds.connectAttr('%s.t' % targ1, '%s.color2' % t_bc)
        if blendAttr:
            cmds.connectAttr(blendAttr, '%s.blender' % t_bc)
        cmds.connectAttr('%s.output' % t_bc, '%s.t' % driven)
            
    if rotate:
        r_bc = cmds.createNode('blendColors', name='%s_rotate_bc' % driven)
        cmds.connectAttr('%s.rotate' % targ2, '%s.color1' % r_bc)
        cmds.connectAttr('%s.rotate' % targ1, '%s.color2' % r_bc)
        if blendAttr:
            cmds.connectAttr(blendAttr, '%s.blender' % r_bc)
        cmds.connectAttr('%s.output' % r_bc, '%s.rotate' % driven)
	def _validate_item_for_alembic_cache_publish(self, item):
		"""
		Validate that the item is valid to be exported 
		to an alembic cache
		"""
		errors = []
		# check that the group still exists:
		if not cmds.objExists(item["name"]):
			errors.append("This group couldn't be found in the scene!")
		
		else:
			# print "\n\n### %s ###\n\n" %item["name"]
			# Deselect all
			cmds.select(deselect=True)
			# Use selection to get all the children of current "Alembic" objectset
			cmds.select(item["name"], hierarchy=True, add=True)
			# Get only the selected items. (if necessary take only certain types to export!)
			sel=cmds.ls(selection=True, showType=True)
			
			meshesFound = False
			for s in sel:
				if cmds.ls(s, type="mesh"):
					meshesFound = True
					break
			
			if not meshesFound:
				errors.append("This group doesn't appear to contain any meshes!")
			cmds.select(deselect=True)			
			
		# finally return any errors
		return errors
Exemple #6
0
    def getRoot(self, node=None):
        if not node and len(cmds.ls(sl=1)) > 0:
            node = cmds.ls(sl=1)[0]

        fullPath = cmds.ls(node, l=1)[0]
        root = fullPath.split('|')[1]
        return root
Exemple #7
0
def _ls(nodeType = '', topTransform = True, stringFilter = '', unlockNode = False):
	if nodeType:
		nodes = cmds.ls(type = nodeType)
		if nodes:
			final_nodes = []
			for each in nodes:
				each = cmds.ls(each, long = True)[0]
				top_transform = cmds.listRelatives(each, parent = True, fullPath = True) if topTransform else None
				final_node = top_transform[0] if top_transform else each

				if unlockNode:
					try:    cmds.lockNode(final_node, lock = False)
					except: mel.eval('warning "Failed to unlock %s, skipping...";' % final_node)

				if stringFilter:
					if stringFilter in final_node:
						if final_node not in final_nodes:
							final_nodes.append(final_node)
				else:
					if final_node not in final_nodes:
						final_nodes.append(final_node)

			return final_nodes

		return []
Exemple #8
0
def exportAlembicData( prefix, exportTargets, startFrame, endFrame, step, path ):
    
    import sgBFunction_base
    sgBFunction_base.autoLoadPlugin( 'AbcExport' )
    sgBFunction_base.autoLoadPlugin( 'AbcImport' )
    
    if prefix:
        prefix += '_'
    
    topTransforms = []
    visValues = []
    for tr in cmds.ls( tr=1 ):
        if cmds.listRelatives( tr, p=1 ): continue
        topTransforms.append( tr )
        visValues.append( cmds.getAttr( tr+'.v' ) )
        cmds.setAttr( tr+'.v', 0 )

    sgBFunction_fileAndPath.makeFolder( path )
    
    for target in exportTargets:
        target = cmds.ls( target, l=1 )[0]
        
        cmds.showHidden( target, a=1 )
        
        targetName = target.split( '|' )[-1]
        filePath = path + '/' + prefix + targetName.replace( ':', '_' ) + '_s' + str( step ).replace( '.', '_' ) + '.abc'
        cmds.AbcExport( target, j="-frameRange %s %s -step %s -writeVisibility -uvWrite -dataFormat ogawa -root %s -file %s" %( startFrame, endFrame, step, target, filePath ) )
        for tr in topTransforms:
            cmds.setAttr( tr+'.v', 0 )

    for i in range( len( topTransforms ) ):
        cmds.setAttr( topTransforms[i] + '.v', visValues[i] )
Exemple #9
0
 def orderedVertsEdgeLoop(cls):
     """
     #select 2 adjasent vertices ( corner and direction vertex)
     #list vertexes on edge loop( for curves )   
     """
     myVert = cmds.ls( os=1, fl=1 )
     if len(myVert)==2:
         firstVert = myVert[0]
         secondVert = myVert[1]
         
         cmds.select (firstVert,secondVert, r =1)
         mel.eval('ConvertSelectionToContainedEdges')        
         firstEdge = cmds.ls( sl=1 )[0]
         
         cmds.polySelectSp( firstEdge, loop =1 )
         edges = cmds.ls( sl=1, fl=1 )
         edgeDict = cls.getEdgeVertDict(edges) #{edge: [vert1, vert2], ...}
         ordered = [firstVert, secondVert]
         for i in range( len(edges)-2 ):            
             del edgeDict[firstEdge]
             #print edgeDict
             for x, y in edgeDict.iteritems():
                 if secondVert in y:                    
                     xVerts = y
                     xVerts.remove(secondVert)
                     firstEdge = x
         
             secondVert = xVerts[0]
             ordered.append( secondVert )
         return ordered
     
     else:
         print 'select 2 adjasent vertex!!'            
def addVrayObjectIds(shapes=None):
    """ Add a vray_objectID attribute to selected meshes

    :param shapes: Shapes to apply the attribute to. If shapes is None it will get
                   the shapes related to the current selection.
    """
    if shapes is None:
        shapes = mc.ls(sl=1, s=1, dag=1, lf=1, o=1, long=True)

    if shapes:
        # Can only add objectIds to mesh, nurbsSurface so lets filter it
        shapes = mc.ls(shapes, type=("mesh", "nurbsSurface"))

    if shapes:
        result = mc.promptDialog(
            title="Object ID value",
            message="Object ID:",
            button=["OK", "Cancel"],
            defaultButton="OK",
            cancelButton="Cancel",
            dismissString="Cancel",
        )

        if result == "OK":
            value = int(mc.promptDialog(query=True, text=True))

            for shape in shapes:
                mc.vray("addAttributesFromGroup", shape, "vray_objectID", 1)
                mc.setAttr("{0}.{1}".format(shape, "vrayObjectID"), value)
def maya_move(angular_velocity, time_step):
            
    objects = cmds.ls(sl=True)
    if objects == []:
        print('* Please select at least an object.')
        return
        
    trajectory = cmds.ls('trajectory')
    
    for i, o in enumerate(objects):
        x = cmds.getAttr(o + '.translateX')
        y = cmds.getAttr(o + '.translateY')
        z = cmds.getAttr(o + '.translateZ')
    
        loc = [x, y, z]
        state = make_state(loc)
                
        state = simulate_circle(state, angular_velocity, time_step)
        
        old_loc = loc
        loc = get_location(state)
        
        cmds.select(o)
        cmds.move(loc[0], loc[1], loc[2])
        
        # draw trajectory for the first object
        if i == 0:
            if trajectory == []:
                cv = cmds.curve(point=[old_loc, loc], degree=1)                
                cmds.rename(cv, 'trajectory')
            else:
                cmds.curve('trajectory', point=[loc], degree=1, append=True)
        
    # keep all objects selected
    cmds.select(objects)
Exemple #12
0
def parent(parent=True):
    if parent:
        # make member of second selection
        cmds.character(cmds.ls(sl=True)[0], include=cmds.ls(sl=True)[1])
    else:
        # remove membership from second selection
        cmds.character(cmds.ls(sl=True)[0], rm=cmds.ls(sl=True)[1])
    def __init__(self):
        # Get our joint lists from a json file.
        print os.environ["RDOJO_DATA"]
        data_path = os.environ["RDOJO_DATA"] + 'data/rig/arm.json'
        # Use our readJson function
        data = utils.readJson(data_path)
        # Load the json into a dictionary
        self.module_info = json.loads( data )
        """ NOTE: If we wanted to build our arm from some set of joints
        in the scene, we could overwrite self.module_info['positions']"""
        # Make a new dictionary to store information about the arm rig.
        self.rig_info = {}

        # Here we will see if we have a selection to get new positions from.
        if len(cmds.ls(sl=True, type='joint')) == numjnts :
            sel=cmds.ls(sl=True, type='joint')
            positions = []
            for s in sel:
                positions.append(cmds.xform(s, q=True, ws=True, t=True))
            self.rig_info['positions']=positions

        else:
            self.rig_info['positions']=self.module_info['positions']

        """ Instead of the else:, we could just return a message that the selection
        does not meet requirements for an arm. """


        """ What if we want a left and a right arm?  For now we will set
        a temporary variable to override the name, but later we will build
        this into the UI """
        self.instance = '_L_'

        # Run rig_arm function
        self.rig_arm()
 def importAndActivate(self, active=True):
     '''
     If self was instantiated with filepath then this will import that wav
     into Maya and activate it on the timeline. Note that if there is already
     an instance of a sound node in Maya that points to this path them the 
     class will bind itself to that node.
     
     :param active: do we set the imported audio to be active on the timerange in Maya
     
     >>> # example of use:
     >>> audio = r9Audio.AudioNode(filepath = 'c:/my_audio.wav')
     >>> audio.importAndActivate()
     '''
     if not self.isLoaded:
         a=cmds.ls(type='audio')
         cmds.file(self.path, i=True, type='audio', options='o=0')
         b=cmds.ls(type='audio')
   
         if not a == b:
             self.audioNode = (list(set(a) ^ set(b))[0])
         else:
             matchingnode = [audio for audio in a if cmds.getAttr('%s.filename' % audio) == self.path]
             if matchingnode:
                 self.audioNode = matchingnode[0]
             else:
                 log.warning("can't find match audioNode for path : %s" % self.path)
                 return
         self.isLoaded=True
     else:
         log.info('given Audio Path is already loaded in the Maya Scene')
     if active:
         self.setActive()
 def __uicb_setReferenceBwavNode(self, *args):
     '''
     : PRO_PACK : set the internal reference offset used to offset the audionode. 
     
     .. note::
         If you pass this a bwav then it caches that bwav for use as the offset. 
         If you pass it a node, and that node has the timecode attrs, then it caches the offset itself.
     '''
     selectedAudio=cmds.ls(sl=True, type='audio')
     self.__bwav_reference = None
     self.__cached_tc_offset = None
     if selectedAudio:
         if not len(selectedAudio)==1:
             log.warning("Please only select 1 piece of Audio to use for reference")
             return
         reference=AudioNode(selectedAudio[0])
         if reference.isBwav():
             self.__bwav_reference=selectedAudio[0]
             cmds.text('bwavRefTC', edit=True,
                       label='frame %s == %s' % (reference.startFrame,reference.bwav_timecodeFormatted()))
         else:
             raise IOError("selected Audio node is NOT a Bwav so can't be used as reference")
     else:
         selectedNode = cmds.ls(sl=True,l=True)
         if len(selectedNode)==1:
             relativeTC = self.pro_audio.Timecode(selectedNode[0]).getTimecode_from_node()
             actualframe = cmds.currentTime(q=True)
             self.__cached_tc_offset = actualframe - self.pro_audio.timecode_to_frame(relativeTC)
             cmds.text('bwavRefTC', edit=True,
                       label='frame %s == %s' % (cmds.currentTime(q=True), relativeTC))
         else:
             log.warning("No reference audio track selected for reference")
         return
def setPlanes(*args):
    """sets clipping planes for cameras based on float fields in UI. Depending on radio button, it will either do all camera or only selected"""

    all = cmds.radioButtonGrp("camRBG", q=True, sl=True)
    far = cmds.floatFieldGrp("farFFG", q=True, v1=True)
    near = cmds.floatFieldGrp("nearFFG", q=True, v1=True)

    cams = []
    if all==1:
        cams.extend(cmds.ls(type="camera"))
    elif all==2:
        transf = cmds.ls(sl=True, type="transform")
        for each in transf:
            shape = cmds.listRelatives(each, s=True)
            if shape:
                if cmds.objectType(shape) == "camera":
                    cams.extend(shape)
    #for each, set shape.farClipPlane 100000
    if cams:
        print cams
        for cam in cams:
            try:
                cmds.setAttr("%s.farClipPlane"%cam, far)
                cmds.setAttr("%s.nearClipPlane"%cam, near)

            except:
                cmds.warning("Couldn't change the farClipPlane of %s"%cam)
def multObjShapeUpdate():
    sel_objs = cmds.ls(sl=True,fl=True)
    if len(sel_objs)>0:
        files_to_import = cmds.fileDialog2(fileFilter =  '*.obj', dialogStyle = 2, caption = 'import multiple object files', fileMode = 4,okc="Import")
        if len(files_to_import) == len(sel_objs):
            object_names = [file_to_import.split('/')[-1].split('.obj')[0] for file_to_import in files_to_import]
            if len(sel_objs) == len([x for x in object_names if x in sel_objs]):
                for file_to_import in files_to_import:
                    object_name  = file_to_import.split('/')[-1].split('.obj')[0]
                    returnedNodes = cmds.file('%s' % file_to_import, i = True, type = "OBJ", rnn=True, ignoreVersion = True, options = "mo=0",  loadReferenceDepth  = "all"  )
                    cmds.delete(cmds.ls(returnedNodes,type="objectSet"))
                    geo = cmds.listRelatives(cmds.ls(returnedNodes,g=1)[0],p=1)
                    cmds.rename( geo, "newShape_{0}".format(object_name))
                new_shapes = [s for s in cmds.listRelatives(cmds.ls(g=1),p=1) if "newShape_" in s]
                cur_shapes = sel_objs
                for new in new_shapes:
                    for cur in cur_shapes:
                        if new.split("newShape_")[1] == cur:
                            blendshapeNd = cmds.blendShape(new,cur)[0]
                            cmds.setAttr("{0}.{1}".format(blendshapeNd,new),1)
                cmds.delete(cur_shapes,ch=True)
                cmds.delete(new_shapes)
                cmds.confirmDialog(m="---===All Shapes Updated!===---")
            else:
                cmds.confirmDialog(m="--==Not Matching The Name!==--")
        else:
            cmds.confirmDialog(m="--==Please Select The Same Number Of Objects!==--")
    else:
        cmds.confirmDialog(m="--==Please Select Something!==--")
Exemple #18
0
 def removeLayTex(self, argsv):
     # get shapes of selection:
     args = cmds.ls(sl=1)
     shapesInSel = cmds.ls(dag=1,o=1,s=1,sl=1)
     shapeIndex = 0
     for arg in args :
         # get shading groups from shapes:
         shadingGrps = cmds.listConnections(shapesInSel[shapeIndex],type='shadingEngine')
         # get the shaders:
         shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1) 
         shader = shaders[0]
         #print cmds.listRelatives (p=True, arg)
         
         layeredTex = cmds.listConnections(shader, type='layeredTexture')
         layeredTex = layeredTex[0]
         
         if (not layeredTex == None):
             fileTex = cmds.listConnections(layeredTex, type='file')
             fileTex = fileTex[0]
             
             if (not fileTex == None):
                 cmds.delete(layeredTex)
                 print 'Connecting ' + shader + '.color to ' + fileTex + '.outColor'
                 cmds.connectAttr(fileTex+'.outColor', shader+'.color', f=1)
             else:
                 print ('Object ' + arg + ' does not have a file texture attached, skipping')
         else:
             print ('Object ' + arg + ' does not have a layered texture attached, skipping')
         shapeIndex += 1
Exemple #19
0
 def renameShTx(self, argsv):
     # get shapes of selection:
     args = cmds.ls(sl=1)
     shapesInSel = cmds.ls(dag=1,o=1,s=1,sl=1)
     shapeIndex = 0
     for arg in args :
         # get shading groups from shapes:
         shadingGrps = cmds.listConnections(shapesInSel[shapeIndex],type='shadingEngine')
         # get the shaders:
         shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1)
         shader = shaders[0]
         #print cmds.listRelatives (p=True, arg)
         fileColor = cmds.listConnections(shader+'.color', type='file')
         if (not fileColor == None):
             cmds.rename(fileColor[0], arg+'_COLOR_TEXTURE')
             
         bump = cmds.listConnections(shader+'.normalCamera', type='bump2d')
         if (not bump == None):
             fileBump = cmds.listConnections(bump[0]+'.bumpValue', type='file')
             if (cmds.getAttr(bump[0]+'.bumpInterp') == 1):
                 cmds.rename(fileBump[0], arg+'_NORM_TEXTURE')
             else:
                 cmds.rename(fileBump[0], arg+'_BUMP_TEXTURE')
         
         if cmds.objExists(shader+'.specularColor'):
             fileSpec = cmds.listConnections(shader+'.specularColor', type='file')
             if (not fileSpec== None):
                 cmds.rename(fileSpec[0], arg+'_SPEC_TEXTURE')
         
         if (not shadingGrps[shapeIndex]==None):
             cmds.rename(shadingGrps[shapeIndex], arg+'_SG')
             cmds.rename(shader, arg+'_MTL')
         shapeIndex += 1
def run():
    """Detect overlapping (lamina) faces. Lamina faces are faces that share all of their edges. 
    ---
    Returns True/False, the number of isolated vertices and a list of the isolated vertices
    has_isolatedvertices2() -> (boolean, int, [mesh:v[id],])
    """
    t0 = float(time.time())
    verbose = cmds.optionVar(query='checkmateVerbosity')
    result=False
    # meshes = cmds.ls(type='mesh')
    meshes = [x for x in cmds.ls(typ='mesh', noIntermediate=True) if not cm.tests.shapes.mesh.isEmpty(x)]
    try:
        cmds.select(meshes)
    except TypeError:
    	print "# Warning: No meshes in scene"
    cmds.selectType( pf=True ) 
    cmds.polySelectConstraint(
        mode=3, # all and next
        type=0x0008, # faces
        topology=2, # lamina
        )
    sel=cmds.ls(sl=True, fl=True)
    result =  (len(sel) > 0) or False
    cmds.polySelectConstraint(disable=True)
    try:
        cmds.select(sel)
    except TypeError:
    	pass 
    # print execution time
    print '%-24s : %.6f seconds' % ('f.lamina.run()', (float(time.time())-t0))
    return (result, len(sel), sel)
def printDataFromSelection( filepath=DEFAULT_PATH, tolerance=1e-4 ):
	miscData,geoAndData = presets.PresetPath(filepath).unpickle()
	selVerts = cmd.ls( cmd.polyListComponentConversion( cmd.ls( sl=True ), toVertex=True ), fl=True )
	selGeo = {}
	for v in selVerts:
		idx = v.rfind('.')
		geo = v[ :idx ]
		vec = Vector( cmd.xform( v, q=True, t=True, ws=True ) )
		try:
			selGeo[ geo ].append( ( vec, v ) )
		except KeyError:
			selGeo[ geo ] = [ ( vec, v ) ]

	#make sure the geo selected is actually in the file...
	names = selGeo.keys()
	for geo in names:
		try:
			geoAndData[ geo ]
		except KeyError:
			selGeo.pop( item )

	for geo,vecAndVert in selGeo.iteritems():
		joints, jointHierarchies, weightData = geoAndData[ geo ]
		weightData = sortByIdx( weightData )
		for vec, vertName in vecAndVert:
			try:
				vertData = findBestVector( vec, weightData, tolerance )
				jointList, weightList = vertData.joints, vertData.weights
				tmpStr = []
				for items in zip( jointList, weightList ):
					tmpStr.append( '(%s %0.3f)' % items )
				print '%s: %s' % ( vertName, '  '.join( tmpStr ) )
			except AttributeError:
				print '%s no match'
Exemple #22
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)
Exemple #23
0
def getMaterials(nodes=None):
    """ Returns the materials related to nodes

    :param nodes: The nodes to get the related materials from.
                  If nodes is None the current selection will be used.

    :rtype: list
    """
    # Get selected nodes if None provided
    if nodes is None:
        nodes = mc.ls(sl=1)

    # Get materials from list
    materials = mc.ls(nodes, mat=1, long=True)

    # Get materials related to nodes (material from object)
    # And add those materials to the material list we already have
    if nodes:
        nodes_history = mc.listHistory(nodes,f=1)
        if nodes_history:
            nodes_connections = mc.listConnections(nodes_history)
            if nodes_connections:
                connected_materials = mc.ls(nodes_connections, mat=True, long=True)
                if connected_materials:
                    # Use a set so we don't have any duplicates
                    materials = set(materials)
                    materials.update(connected_materials)
                    materials = list(materials)

    return materials
Exemple #24
0
def connectLoresVis(toggleAttr="allTransA_ctrl.loGeoVis"):
    """
	Connect lores geometry visibility to the specified visibility toggle attribute
	@param toggleAttr: Visibility toggle attribute
	@type toggleAttr: str
	"""
    # Check visibility toggle attribute
    if not mc.objExists(toggleAttr):
        raise Exception('Visibility toggle attribute "' + toggleAttr + '" does not exist!')

        # Get all joint list
    jointList = mc.ls(type="joint")
    if not jointList:
        return

    # Iterate over all joints
    for joint in jointList:

        # Get all joint mesh shapes
        allShapes = mc.listRelatives(joint, s=True, pa=True)
        if not allShapes:
            continue
        meshShapes = mc.ls(allShapes, type="mesh")
        if not meshShapes:
            continue

        # Connect mesh shape visibility to vis toggle attr
        for meshShape in meshShapes:
            mc.connectAttr(toggleAttr, meshShape + ".v", f=True)
Exemple #25
0
def colourLoresGeo():
    """
	Set default colouring for lores geometry,
	"""
    # Get all joint list
    jointList = mc.ls(type="joint")
    if not jointList:
        return

    # Iterate over all joints
    for joint in jointList:

        # Get all joint mesh shapes
        allShapes = mc.listRelatives(joint, s=True, pa=True)
        if not allShapes:
            continue
        meshShapes = mc.ls(allShapes, type="mesh")
        if not meshShapes:
            continue

        # Colour mesh shape
        for meshShape in meshShapes:

            mc.setAttr(meshShape + ".overrideEnabled", 1)
            if joint.startswith("cn_"):
                mc.setAttr(meshShape + ".overrideColor", 24)
            if joint.startswith("lf_"):
                mc.setAttr(meshShape + ".overrideColor", 15)
            if joint.startswith("rt_"):
                mc.setAttr(meshShape + ".overrideColor", 4)
Exemple #26
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)
Exemple #27
0
	def uiSetFlags(self):
		'''
		Gets the channel state data from the UI and then sets the flags.
		'''
		# Get channel state flag values
		channelState = []
		for attr in self.channel:
			channelState.append(mc.radioButtonGrp('rbg'+attr.upper(),q=1,sl=1)-2)
		
		# Get list of objects to set flags for
		objType = mc.radioButtonGrp('rbgObjType',q=1,sl=1)
		objectList = []
		
		if objType == 1: objectList = mc.ls(sl=1)
		elif objType == 2:
			doit = mc.confirmDialog(title='Confirm Set Flags on ALL Transforms', 
						m='Are you sure you want to mass edit all the channel state attributes?',
						button=('Yes','No'),
						defaultButton='No',
						cancelButton='No',
						dismissString='NO')
			if doit == 'No': return
			objectList = mc.ls('*.channelState',o=True)
		elif objType == 3:
			selType = mc.textField('tfType',q=1,text=1)
			objectList = mc.ls(type=selType)
		
		# Set Flags
		self.setFlags(channelState,objectList)
Exemple #28
0
    def selectPaintWeightsInfluence(self,infl):
        '''
        tries to select influence (provided as string) in current maya's paint weights context and UI
        if skin paint context is not available, nothing happens
        '''
        if not Utils.isCurrentlyPaintingWeights():
            return
        
        # influence name can come in any form ('joint3', 'joint2|joint3', 'joint1|joint2|joint3')
        # get the absolute shortest possible (but still unique) and longest
        try:
            longName = cmds.ls(infl,l=True)[0]
            shortName = cmds.ls(longName,l=False)[0]

            log.info("selecting in paint weights: influence %s" % str(infl))
        
            # try to work around with the mess in the earlier versions of 
            # maya's paint weights UI:
            if Utils.getMayaVersion()<Utils.MAYA2011:
                itemName = Utils.mel('artAttrSkinShortName("%s")'%shortName)
                Utils.mel('artSkinSelectInfluence("artAttrSkinPaintCtx","%s","%s");' % (shortName,itemName));
            else:
                Utils.mel('artSkinSelectInfluence("artAttrSkinPaintCtx","%s");' % shortName);
                
            # show paint weights interface
            cmds.toolPropertyWindow()
        except:
            # problems listing given influence.. just die here
            Utils.displayError('problem selecting influence %s' % infl)
Exemple #29
0
def check():
	'''
	Non-Unique Checker looks for non unique node names. 
	It will separate shape, dag and dep nodes when reporting.
	
	@version history: 	03/30/07 : Gregory Smith : initial release
				06/13/07 : Ramiro Gomez : updated header format
				04/25/08 : Ramiro Gomez : initial python transfer
	@keyword: rig, model, naming
	@appVersion: 8.5, 2008
	'''

	##Create variables
	dagErrors=[] ##hold all the nonunique items
	shapeErrors=[] ##hold all the nonunique items
	depErrors=[] ##hold all the nonunique items
	
	dag = mc.ls(dag=True)
	shapes = mc.ls(geometry=True)
	dep = mc.ls(dep=True)
	
	for item in shapes:
		while dag.count(item): dag.remove(item)
			
	for item in shapes:
		while dep.count(item): dep.remove(item)
			
	for item in dag:
		while dep.count(item): dep.remove(item)
			
	##Print header statement
	print 'Non-Unique Checker'
	print '==========================================\n'

	print 'DAG NODES'
	print '------------'
	for item in dag:
		if item.count('|'): dagErrors.append(item)
	print '\n'.join(sorted(dagErrors)) + '\n'
	
	print 'DEP NODES'
	print '------------'
	for item in dep:
		if item.count('|'): depErrors.append(item)
	print '\n'.join(sorted(depErrors)) + '\n'
	
	print 'SHAPE NODES'
	print '------------'
	for item in shapes:
		if item.count('|'): shapeErrors.append(item)
	print '\n'.join(sorted(shapeErrors)) + '\n'
	
	del dep
	del dag
	del shapes
	
	mc.select(cl=True)
	
	print '=========================================='
	print ('Non-Unique Check located ' + str(len(dagErrors) + len(depErrors) + len(shapeErrors)) + ' errors.')
Exemple #30
0
    def gather(self, selection):

        data = {}

        if selection:
            transforms = cmds.ls(sl=True, long=True)
        else:
            transforms = cmds.ls(long=True, transforms=True)

        shading_groups = []
        for t in transforms:
            sgs = utils.get_shading_groups(t)
            if sgs:
                shading_groups.extend(sgs)

        shading_groups = set(shading_groups)

        for sg in shading_groups:
            members = cmds.sets(sg, query=True)
            if not members:
                continue

            _id = utils.add_id(sg)
            members = utils.short_names(members)
            data[str(sg)] = {
                'meta_id': _id,
                'members': members,
            }

        return {'shadingGroups': data}
import maya.cmds as cmds
from functools import partial
import random

numToMake = 20
object = cmds.ls(selection=True)
width = cmds.getAttr(
    "%s.distance" % (cmds.listRelatives("distanceDimension1", shapes=True)[0]))

for num in xrange(numToMake - 1):
    dupObj = cmds.duplicate(object)
    cmds.xform(dupObj[0],
               translation=[width, 0, 0],
               relative=True,
               objectSpace=True)
    cmds.xform(dupObj[0], rotation=[0, 360 / numToMake, 0], relative=True)
    object = dupObj
Exemple #32
0
def testObj(obj):
    sel = cmds.ls(sl=True, type="transform")
    if len(sel):
        return sel[0]
    raise RuntimeError, "Only one object should be selected."
import os
import re

import maya.cmds as cmds

refs = cmds.ls(type='reference')

for ref in refs:
    #getting reference data
    path = cmds.referenceQuery(ref, f=True)
    name = os.path.basename( path )

    #generate regex file version pattern
    versionPattern = r'(([v])([0-9]{3})).*'
    startStr = re.findall(versionPattern, name)[0][0]
    startStr = name.split(startStr)[0]
    pattern = r'(\b' + startStr + ')' + versionPattern

    #finding versions
    versions = []
    for f in os.listdir(os.path.dirname(path)):
        if re.match(pattern, f):
            versions.append(f)

    #finding latest version
    count = 0
    latestName = None
    for version in versions:
         versionNumber = re.findall(versionPattern, version)[0][-1]
         if count < int(versionNumber):
             count = int(versionNumber)
Exemple #34
0
            'offset', 'selection'
    ], nodeType):
        #print 'Skipping ' + nodeType + ' from nodeTypes...'
        pass
    else:
        nodeTypesFiltered.append(nodeType)

#with open("c:/filepathDebug.txt", "a") as myfile:
#	myfile.truncate()

#for nodeType in nodeTypes:
for nodeType in nodeTypesFiltered:
    #with open("c:/filepathDebug.txt", "a") as myfile:
    #	myfile.write(str(nodeType) + '\n')
    #print nodeType # USE THIS TO IDENTIFY ERROROUS QUERIES
    nodes = cmds.ls(type=nodeType)
    for node in nodes:
        attributes = cmds.listAttr(node, write=True, hasData=True)
        for attribute in attributes:
            try:
                if findFirstMatchInString(['C:', 'R:', 'X:'],
                                          cmds.getAttr(node + '.' +
                                                       attribute)):
                    print 'Found invalid drive letter in : ' + cmds.getAttr(
                        node + '.' + attribute)
                    errors += 1
            except:
                pass

print '\n-------Summary -------'
print 'Found ' + str(len(nodeTypes)) + ' possible node types.'
    def om_all_mesh_vertex(self):
        sList = om.MSelectionList()
        om.MGlobal.getActiveSelectionList(sList)
        iter = om.MItSelectionList(sList)
        loop = 0
        om_add_nodes = []
        while not iter.isDone():
            loop += 1
            if loop >= 10000:
                print 'too many loop :'
                return []
            meshDag = om.MDagPath()
            component = om.MObject()
            try:
                iter.getDagPath(meshDag, component)
                #print 'get dag node :', meshDag.fullPathName()
            except:  #2016ではノード出したばかりの状態でシェイプがなぜか帰ってくるのでエラー回避
                iter.next()
                continue
            mesh_path_name = meshDag.fullPathName()
            om_add_nodes += [mesh_path_name]
            iter.next()
        #print 'om add nodes :', om_add_nodes
        om_add_nodes = [
            cmds.listRelatives(node, p=True, f=True)[0]
            if cmds.nodeType(node) == 'mesh' else node for node in om_add_nodes
        ]
        #print 'om add nodes :', om_add_nodes

        if cmds.selectMode(q=True, co=True):
            #コンポーネント選択の時でもこのポイントがハイライトされた時表示されるように末端まで取る
            self.hl_nodes = cmds.ls(hl=True, l=True)
            self.hl_nodes = common.search_polygon_mesh(self.hl_nodes,
                                                       fullPath=True,
                                                       serchChildeNode=True)
            add_node = common.search_polygon_mesh(cmds.ls(sl=True,
                                                          l=True,
                                                          tr=True),
                                                  fullPath=True,
                                                  serchChildeNode=True)
            if add_node:
                self.hl_nodes += add_node
            if om_add_nodes:
                self.hl_nodes += om_add_nodes
        else:
            self.hl_nodes = cmds.ls(sl=True, l=True, tr=True) + cmds.ls(
                hl=True, l=True, tr=True)
            self.hl_nodes = common.search_polygon_mesh(self.hl_nodes,
                                                       fullPath=True,
                                                       serchChildeNode=True)
            if om_add_nodes:
                self.hl_nodes += om_add_nodes
        self.hl_nodes = list(set(self.hl_nodes))

        for node in self.hl_nodes[:]:

            sList = om.MSelectionList()
            sList.add(node)

            meshDag = om.MDagPath()
            component = om.MObject()

            try:
                sList.getDagPath(0, meshDag, component)
                #print 'get dag node :', meshDag.fullPathName()
            except Exception as e:  #2016ではノード出したばかりの状態でシェイプがなぜか帰ってくるのでエラー回避
                #iter.next()
                print 'get dag path error :'
                continue

            skinFn, vtxArray, skinName = self.adust_to_vertex_list(
                meshDag, component)
            if skinFn is None:
                continue
            self.dag_skin_id_dict[meshDag] = [skinFn, vtxArray, skinName]
 def light_name_eval(self):
     self.light_names = []
     self.light_names = cmds.ls(type='VRayLightRectShape')
Exemple #37
0
    def create_edit_crv(crv_type, name, edit=False, add=False):
        """
        Create or edit curves.

        :param crv_type: type of the curve to create
        :type crv_type: str

        :param name: name of the curve to create
        :type name: str

        :param edit: edit the selected curves instead of creating new ones
        :type edit: bool

        :param add: add to the selected shape (True) or replace it (False)
        :type add: bool

        :return:
        """
        if not name:
            name = 'ctrl'

        if not crv_type or crv_type == 'None':
            crv_type = 'circle'

        # get selection
        selection = mc.ls(sl=True)
        print 1

        crv_list = list()
        print 2

        if len(selection) > 0:
            print 3
            for obj in selection:
                print 4
                position = mc.xform(obj, q=True, matrix=True, ws=True)
                print 5
                print position

                crv_list += CurveManager.create_crv(crv_type=crv_type,
                                                    name=name)
                print 6
                print crv_list

                mc.xform(name, matrix=position, ws=True)
                print 7

                if edit:
                    print 8
                    if add:
                        print 9
                        add = True
                    else:
                        print 10
                        add = False

                    print 11
                    CurveManager.modify_crv_shape(target=obj,
                                                  source=name,
                                                  delete=True,
                                                  add=add)
                    print 12
        else:
            print 13
            crv_list += CurveManager.create_crv(crv_type=crv_type, name=name)
            print 14

        return crv_list
Exemple #38
0
 def getFullNodePath(nodeName):
     result = cmds.ls(nodeName,l=True)
     if result is None or len(result)==0:
         raise MessageException("node %s was not found" % nodeName)
     
     return result[0]
Exemple #39
0
    def createRibbon(self, *args):
        temp = len(args[0])
        if temp > 3:
            #Storing names from GUI
            prefix = args[0][0]
            numJnts = 5  #args[0][1]
            width = args[0][2]
            aimAxis = args[0][3]
            upAxis = args[0][4]
            topPrnt = args[0][5]
            btmPrn = args[0][6]
            type = args[0][7]
            mo = args[0][8]

        else:
            #Storing names from GUI
            prefix = mc.textFieldGrp(self.prefixField, query=True, text=True)
            numJnts = 5  #mc.intFieldGrp(self.numJntsField,query=True,value1=True)
            width = mc.intFieldGrp(self.widthField, query=True, value1=True)
            aimAxis = mc.radioButtonGrp(self.aimAxisField, query=True, sl=True)
            upAxis = mc.radioButtonGrp(self.upAxisField, query=True, sl=True)
            topPrnt = mc.textFieldButtonGrp(self.topField,
                                            query=True,
                                            text=True)
            btmPrnt = mc.textFieldButtonGrp(self.btmField,
                                            query=True,
                                            text=True)
            type = mc.radioButtonGrp(self.typeField, query=True, sl=True)
            mo = mc.radioButtonGrp(self.moField, query=True, sl=True)

        #Now, some error checking. Make sure name is entered and that it's unique
        # If another chain exists any where in the scene, can't use that same name because it causes
        # errors with the follicle creation

        if (len(prefix) < 1):
            mel.eval("warning \"Name field empty. Please enter a name.\"")
            return (0)

        if (mc.objExists(prefix + "_topNode")):
            mc.select(prefix + "_topNode")

        tempObjects = mc.ls(sl=True)

        if (len(tempObjects) > 1):
            mel.eval(
                "warning \"Name is not unique. Please select a unique name.\"")
            mc.select(clear=True)
            return (0)

        #Setting up variables
        if (aimAxis == 1):
            aimAxis = "X"
            aim = "X"
        if (aimAxis == 2):
            aimAxis = "Y"
            aim = "Y"
        if (aimAxis == 3):
            aimAxis = "Z"
            aim = "Z"

        if (upAxis == 1):
            upAxis = "X"
            up = "X"
        if (upAxis == 2):
            upAxis = "Y"
            up = "Y"
        if (upAxis == 3):
            upAxis = "Z"
            up = "Z"

        #
        #Making the Nurbs plane
        #
        if (aimAxis == "X"):  #X selected
            tempName = mc.nurbsPlane(pivot=[0, 0, 0],
                                     axis=[0, 1, 0],
                                     width=width,
                                     lengthRatio=.2,
                                     degree=3,
                                     u=numJnts,
                                     v=1,
                                     ch=1)
            planeName = (prefix + "_rbbn_" + str(tempName[0]))
            mc.rename(tempName[0], planeName)
            mc.select(planeName, r=True)

        elif (aimAxis == "Y"):  #Y selected
            tempName = mc.nurbsPlane(pivot=[0, 0, 0],
                                     axis=[0, 1, 0],
                                     width=width,
                                     lengthRatio=.2,
                                     degree=3,
                                     u=numJnts,
                                     v=1,
                                     ch=1)
            planeName = (prefix + "_rbbn_" + str(tempName[0]))
            mc.rename(tempName[0], planeName)

            #orient surface along axis
            mc.setAttr((planeName + ".rotateAxis"), (90), (0), (90))
            mc.select(planeName, r=True)

        elif (aimAxis == "Z"):  #Z selected
            tempName = mc.nurbsPlane(pivot=[0, 0, 0],
                                     axis=[0, 0, 1],
                                     width=width,
                                     lengthRatio=.2,
                                     degree=3,
                                     u=numJnts,
                                     v=1,
                                     ch=1)
            planeName = (prefix + "_rbbn_" + str(tempName[0]))
            mc.rename(tempName[0], planeName)

            #orient surface along axis
            mc.setAttr((planeName + ".rotateAxis"), 0, 90, 90)
            mc.select(planeName, r=True)

        #Resetting up variables
        if (aimAxis == "X"):
            aimAxis = 1.0, 0, 0

        if (aimAxis == "Y"):
            aimAxis = 0, 1.0, 0

        if (aimAxis == "Z"):
            aimAxis = 0, 0, 1.0

        if (upAxis == "X"):
            upAxis = 1.0, 0, 0

        if (upAxis == "Y"):
            upAxis = 0, 1.0, 0

        if (upAxis == "Z"):
            upAxis = 0, 0, 1.0

        #
        #Create follicles
        #
        mc.select(planeName, r=True)
        mel.eval("createHair " + str(numJnts) + " 1 2 0 0 0 0 " +
                 str(numJnts) + " 0 2 1 1")

        #      At this point, the created hairSystemShape1 is selected, which is annoying, because
        #    even for hairSystem2, it's shape node is hairSystemShape1!!! So some work needs to be
        #    done so that we can grab the hairSystem name with an ls
        #    and using some pickWalking and slicing, so we can select the newly created hairSystem
        #    and create names for the other nodes created.

        mc.pickWalk(direction='Up')  #From shape to transform of hair system...
        hairSystem = []  #Clear list so it doesn't grow

        hairSystem = mc.ls(sl=True,
                           fl=True)  #Stores: hairSystemX (default name)
        hSystem = hairSystem[0]  #Convert list item to string
        hOutputCurves = hSystem + "OutputCurves"
        hFollicles = hSystem + "Follicles"

        #Determine hairSystem number to give Follicle group a unique name
        num = len(hSystem)
        num = num - 1
        hSysNum = hSystem[num:]

        #rename hairSystemXFollicles
        follicleGrp = (prefix + "Follicles" + hSysNum)  #New follicle grp name
        mc.rename(hFollicles, follicleGrp)

        mc.delete(hSystem, hOutputCurves)

        #Delete follicle curves
        hFollicles = mc.listRelatives(
            follicleGrp, c=True)  #Store all children ( follicles )
        for each in hFollicles:
            crv = mc.listRelatives(
                each,
                c=True)  #Store each child of each follicle (curve1, etc...)
            mc.delete(crv[1])  #Delete the curves
        #
        #Create control curves and joints: 5: Top,mid1,mid2,mid3,Btm AND Twist control
        #
        conCurves = []
        conJoints = []
        x = 0

        while (x < 5):
            if (aim == "X"):
                conCurves.append(mc.circle(nr=(1, 0, 0), r=2))
                conJoints.append(mc.joint(p=(0, 0, 0), rad=.2))
            if (aim == "Y"):
                conCurves.append(mc.circle(nr=(0, 1, 0), r=2))
                conJoints.append(mc.joint(p=(0, 0, 0), rad=.2))
            if (aim == "Z"):
                conCurves.append(mc.circle(nr=(0, 0, 1), r=2))
                conJoints.append(mc.joint(p=(0, 0, 0), rad=.2))
            x = x + 1

        #
        #Snap controllers: 5: Top,mid1,mid2,mid3,Btm
        #
        ##First row of CV's
        mc.select(planeName + ".cv[0][0:3]", r=True)
        temp = mc.cluster()
        temp2 = mc.pointConstraint(temp, conCurves[0], mo=False)
        mc.delete(temp, temp2)

        ##mid1 row of CV's
        mc.select(planeName + ".cv[" + str((numJnts / 2) + 0) + "][0:3]",
                  r=True)
        mc.select(planeName + ".cv[" + str((numJnts / 2) + 1) + "][0:3]",
                  add=True)
        temp = mc.cluster()
        temp2 = mc.pointConstraint(temp, conCurves[1], mo=False)
        mc.delete(temp, temp2)

        ##mid2 row of CV's
        mc.select(planeName + ".cv[" + str((numJnts / 2) + 1) + "][0:3]",
                  r=True)
        mc.select(planeName + ".cv[" + str((numJnts / 2) + 2) + "][0:3]",
                  add=True)
        temp = mc.cluster()
        temp2 = mc.pointConstraint(temp, conCurves[2], mo=False)
        mc.delete(temp, temp2)

        ##mid3 row of CV's
        mc.select(planeName + ".cv[" + str((numJnts / 2) + 2) + "][0:3]",
                  r=True)
        mc.select(planeName + ".cv[" + str((numJnts / 2) + 3) + "][0:3]",
                  add=True)
        temp = mc.cluster()
        temp2 = mc.pointConstraint(temp, conCurves[3], mo=False)
        mc.delete(temp, temp2)

        ##Last row of CV's
        mc.select(planeName + ".cv[" + str(numJnts + 2) + "][0:3]", r=True)
        temp = mc.cluster()
        temp2 = mc.pointConstraint(temp, conCurves[4], mo=False)
        mc.delete(temp, temp2)

        mc.select(clear=True)

        #Binding control top/btm joints to surface here
        bindList = []
        bindList.append(conJoints[0])
        bindList.append(conJoints[4])
        mc.skinCluster(bindList, planeName, dr=4)

        mc.select(clear=True)

        #
        # Rename controllers and joints
        #
        x = 0
        for jnt, crv in zip(conJoints, conCurves):
            tempJnt = prefix + '_skin_jnt_' + str(x)
            tempCrv = prefix + '_ctrl_' + str(x)
            mc.rename(jnt, tempJnt)
            conJoints[x] = tempJnt
            #print crv[0]
            mc.rename(crv[0], tempCrv)
            conCurves[x] = tempCrv
            x = x + 1

        #
        #Zero controls
        #
        zeroNodes = []
        x = 0
        for each in conCurves:
            zeroNode = mc.group(em=True)

            pos = mc.xform(each, q=1, ws=True, t=1)
            mc.xform(zeroNode, ws=True, t=[pos[0], pos[1], pos[2]])

            rot = mc.xform(each, q=1, ws=True, ro=1)
            mc.xform(zeroNode, ws=True, ro=[rot[0], rot[1], rot[2]])

            mc.parent(each, zeroNode, a=True)

            #Rename
            temp = prefix + '_zero_' + str(x)
            mc.rename(zeroNode, temp)
            zeroNodes.append(temp)
            x = x + 1

        #
        # Parent mid controllers to follicles
        #
        mc.parent(zeroNodes[1], hFollicles[1])
        mc.parent(zeroNodes[2], hFollicles[2])
        mc.parent(zeroNodes[3], hFollicles[3])

        #
        # Grp controllers
        #
        ctrlGrp = mc.group(zeroNodes[0],
                           zeroNodes[4],
                           name=prefix + '_ControlsGrp')
        #Get follicles Grp
        mc.select(hFollicles[0], r=True)
        mc.pickWalk(direction='Up')
        sel = mc.ls(sl=True, fl=True)
        noTouchy = mc.group(sel[0], planeName, name=prefix + '_NoTouchy')
        mc.group(noTouchy, ctrlGrp, name=prefix + '_topNode')

        #Parent top/btm controls to user specified objects.
        if type == 1:  #Constraint
            if mo == 1:  #Maintain offset
                mc.parentConstraint(topPrnt, zeroNodes[0], mo=True)
                mc.parentConstraint(btmPrnt, zeroNodes[4], mo=True)
            else:
                mc.parentConstraint(topPrnt, zeroNodes[0], mo=False)
                mc.parentConstraint(btmPrnt, zeroNodes[4], mo=False)

        if type == 2:  #Put in hierarchy
            if mo == 1:  #Maintain offset
                mc.parent(zeroNodes[0], topPrnt)
                mc.parent(zeroNodes[4], btmPrnt)
            else:
                #First, snap them to location, and then parent them
                pos = mc.xform(topPrnt, q=1, ws=True, t=1)
                mc.xform(zeroNodes[0], ws=True, t=[pos[0], pos[1], pos[2]])
                rot = mc.xform(topPrnt, q=1, ws=True, ro=1)
                mc.xform(zeroNodes[0], ws=True, ro=[rot[0], rot[1], rot[2]])
                mc.parent(zeroNodes[0], topPrnt)

                pos = mc.xform(btmPrnt, q=1, ws=True, t=1)
                mc.xform(zeroNodes[4], ws=True, t=[pos[0], pos[1], pos[2]])
                rot = mc.xform(btmPrnt, q=1, ws=True, ro=1)
                mc.xform(zeroNodes[4], ws=True, ro=[rot[0], rot[1], rot[2]])
                mc.parent(zeroNodes[4], btmPrnt)

        if type == 3:
            pass

        mc.select(clear=True)
Exemple #40
0
def import_skin(file_path=None, shape=None, to_selected_shapes=False, enable_remap=True):
    """Creates a skinCluster on the specified shape if one does not already exist
    and then import the weight data.
    """

    if file_path is None:
        file_path = shortcuts.get_open_file_name(
            "Skin Files (*{})".format(EXTENSION), key=KEY_STORE
        )
    if not file_path:
        return

    # Read in the file
    with open(file_path, "r") as fh:
        data = json.load(fh)

    # Some cases the skinningMethod may have been set to -1
    if data.get("skinningMethod", 0) < 0:
        data["skinningMethod"] = 0

    selected_components = []
    if to_selected_shapes:
        shape = cmds.ls(sl=True)
        if shape:
            components = cmds.filterExpand(sm=31) or []
            selected_components = [
                int(re.search("(?<=\[)\d+", x).group(0)) for x in components
            ]
            shape = shape[0].split(".")[0]
    if shape is None:
        shape = data["shape"]
    if not cmds.objExists(shape):
        logging.warning("Cannot import skin, {} does not exist".format(shape))
        return

    # Make sure the vertex count is the same
    mesh_vertex_count = cmds.polyEvaluate(shape, vertex=True)
    imported_vertex_count = len(data["blendWeights"])
    if mesh_vertex_count != imported_vertex_count:
        raise RuntimeError(
            "Vertex counts do not match. Mesh {} != File {}".format(
                mesh_vertex_count, imported_vertex_count
            )
        )

    # Check if the shape has a skinCluster
    skins = get_skin_clusters(shape)
    if skins:
        skin_cluster = SkinCluster(skins[0])
    else:
        # Create a new skinCluster
        joints = data["weights"].keys()

        unused_imports, no_match = get_joints_that_need_remapping(joints)

        # If there were unmapped influences ask the user to map them
        if unused_imports and no_match and enable_remap:
            mapping_dialog = WeightRemapDialog(file_path)
            mapping_dialog.set_influences(unused_imports, no_match)
            result = mapping_dialog.exec_()
            remap_weights(mapping_dialog.mapping, data["weights"])

        # Create the skinCluster with post normalization so setting the weights does not
        # normalize all the weights
        joints = [x for x in data["weights"].keys() if cmds.objExists(x)]
        kwargs = {}
        if data["maintainMaxInfluences"]:
            kwargs["obeyMaxInfluences"] = True
            kwargs["maximumInfluences"] = data["maxInfluences"]
        skin = cmds.skinCluster(
            joints, shape, tsb=True, nw=2, n=data["name"], **kwargs
        )[0]
        skin_cluster = SkinCluster(skin)

    skin_cluster.set_data(data, selected_components)
    logging.info("Imported %s", file_path)
Exemple #41
0
 def topLoad(self, *args):
     sel = mc.ls(sl=True, fl=True)
     mc.textFieldGrp(self.topField, e=True, text=sel[0])
Exemple #42
0
#connect2dPlacement node to fileTexture

#Select the 2dPlacementNode, then select the fileTextures and run this!!!

import maya.cmds as mc
sel = mc.ls(selection=True)
connexList = []


def connectMe():

    connexList = mc.ls(selection=True)
    idx = len(connexList)
    print connexList
    for i in range(idx):
        if i == 0:
            pass
        else:
            mc.connectAttr(connexList[0] + ".mirrorU",
                           connexList[i] + ".mirrorU",
                           f=True)
            mc.connectAttr(connexList[0] + ".mirrorV",
                           connexList[i] + ".mirrorV",
                           f=True)
            mc.connectAttr(connexList[0] + ".stagger",
                           connexList[i] + ".stagger",
                           f=True)
            mc.connectAttr(connexList[0] + ".wrapU",
                           connexList[i] + ".wrapU",
                           f=True)
            mc.connectAttr(connexList[0] + ".wrapV",
Exemple #43
0
def export_base():
    sel = cmds.ls(selection=True)
    _export([sel[0]], base=True)
Exemple #44
0
 def btmLoad(self, *args):
     sel = mc.ls(sl=True, fl=True)
     mc.textFieldGrp(self.btmField, e=True, text=sel[0])
Exemple #45
0
def duplicate_and_mirror():
    objs = cmds.ls(sl=True)
    for obj in objs:
        ret = cmds.duplicate(obj, returnRootsOnly=True)
        cmds.scale(-1, 1, 1, obj)
        print("duplicate_and_mirror done for {0}".format(ret))
Exemple #46
0
def tween(percentage, obj=None, attrs=None, selection=True):
    # if obj is not given and selection is set to False, error early
    if not obj and not selection:
        raise ValueError("No object given to tween")

    # if no obj is specified, get it from the first selection
    if not obj:
        obj = cmds.ls(selection=True)[0]

    # if no attrs specified, use all
    if not attrs:
        attrs = cmds.listAttr(obj, keyable=True)

    currentTime = cmds.currentTime(query=True)

    for attr in attrs:

        # construct the full name of the attribute with its objects
        attrFull = '%s.%s' % (obj, attr)

        keyframes = cmds.keyframe(attrFull, query=True)

        # if there are no keyframs continue
        if not keyframes:
            continue

        previousKeyframes = []
        for k in keyframes:
            if k < currentTime:
                previousKeyframes.append(k)

        laterKeyframes = [frame for frame in keyframes if frame > currentTime]

        # if no keyframes before after continue
        if not previousKeyframes and not laterKeyframes:
            continue

        if previousKeyframes:
            previousFrame = max(previousKeyframes)
        else:
            previousFrame = None

        nextFrame = min(laterKeyframes) if laterKeyframes else None

        print previousFrame
        print nextFrame

        if not previousFrame or not nextFrame:
            continue

        previousValue = cmds.getAttr(attrFull, time=previousFrame)
        nextValue = cmds.getAttr(attrFull, time=nextFrame)

        print previousValue
        print nextValue

        difference = nextValue - previousValue
        weightedDifference = (difference * percentage) / 100.0
        currentValue = previousValue + weightedDifference

        cmds.setKeyframe(attrFull, time=currentTime, value=currentValue)
Exemple #47
0
def freeze_all_selected():
    objs = cmds.ls(sl=True)
    for obj in objs:
        cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1)
        print("Freeze transformations done for {0}".format(obj))
Exemple #48
0
def export_selected():
    sel = cmds.ls(selection=True)
    _export(sel)
Exemple #49
0
    maya.standalone.initialize()

    cmds.loadPlugin('mtoa')

    cmds.file(force=True, new=True)
    cmds.file(rename='render_test.ma')
    cmds.file(force=True, type='mayaAscii', save=True)

    cmds.polyCube()
    cmds.polyCube()
    cmds.polyCube()
    cmds.polyCube()

    # Make a world group
    cmds.select(clear=True)
    cmds.select(cmds.ls('pCube*'), visible=True)
    cmds.group(name='World')

    # Create a camera
    cmds.delete(cmds.ls('camera*'))
    name = cmds.camera(worldCenterOfInterest=[0, 1, 0],
                       worldUp=[0, 1, 0],
                       position=[1, 0, 1])
    cmds.lookThru(name)

    # Create area light
    light_name = mtoa.utils.createLocator('aiAreaLight', asLight=True)
    cmds.setAttr(light_name[0] + '.aiTranslator', 'quad', type='string')
    cmds.setAttr(light_name[0] + '.intensity', 300)
    cmds.setAttr(light_name[0] + '.aiSamples', 2)
    cmds.setAttr(light_name[1] + '.translateX', 10)
Exemple #50
0
def freeze_and_center():
    objs = cmds.ls(sl=True)
    for obj in objs:
        cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1)
        cmds.CenterPivot(obj)
        print("Freeze and Center done for {0}".format(obj))
Exemple #51
0
    def execute(self, **kwargs):
        """
        Main hook entry point
        :returns:       A list of any items that were found to be published.  
                        Each item in the list should be a dictionary containing 
                        the following keys:
                        {
                            type:   String
                                    This should match a scene_item_type defined in
                                    one of the outputs in the configuration and is 
                                    used to determine the outputs that should be 
                                    published for the item
                                    
                            name:   String
                                    Name to use for the item in the UI
                            
                            description:    String
                                            Description of the item to use in the UI
                                            
                            selected:       Bool
                                            Initial selected state of item in the UI.  
                                            Items are selected by default.
                                            
                            required:       Bool
                                            Required state of item in the UI.  If True then
                                            item will not be deselectable.  Items are not
                                            required by default.
                                            
                            other_params:   Dictionary
                                            Optional dictionary that will be passed to the
                                            pre-publish and publish hooks
                        }
        """

        items = []

        # get the main scene:
        scene_name = cmds.file(query=True, sn=True)
        if not scene_name:
            raise TankError("Please Save your file before Publishing")

        scene_path = os.path.abspath(scene_name)
        name = os.path.basename(scene_path)

        # create the primary item - this will match the primary output 'scene_item_type':
        items.append({"type": "work_file", "name": name})

        ## Now find the fx stuff to export as secondary
        ## Make sure the groups are visible and good for calculating
        grps = ['Shot_FX_hrc', 'OCEAN_hrc', 'fluids_hrc', 'FLUID_EMITTERS_hrc']
        for eachGrp in grps:
            if cmds.objExists(eachGrp):
                cmds.setAttr('%s.visibility' % eachGrp, 1)

        ## FLUIDS
        for each in cmds.ls(transforms=True):
            myType = ''
            try:
                myType = cmds.getAttr('%s.type' % each)
            except:
                pass
            #debug(app = None, method = 'shotFX_ScanSceneHook', message = 'myType: %s' % myType, verbose = False)
            if myType:
                ## FLUIDS -- Now get the fluid containers
                if myType == 'oceanWakeFoamTexture' or myType == 'oceanWakeTexture':
                    debug(app=None,
                          method='shotFX_ScanSceneHook',
                          message='fx_caches: %s' % each,
                          verbose=False)
                    items.append({
                        "type": "fx_caches",
                        "name": '%sShape' % each
                    })
                    ## Otherwise grab the fluids group
                elif myType == 'fx':
                    if each != 'ocean_srf':
                        debug(app=None,
                              method='shotFX_ScanSceneHook',
                              message='fx_caches: %s' % each,
                              verbose=False)
                        items.append({
                            "type": "fx_caches",
                            "name": '%s' % each
                        })
                else:
                    pass

        ## NPARTICLES
        getNParticles = cmds.ls(type='nParticle')
        if getNParticles:
            for eachNpart in cmds.ls(type='nParticle'):
                ## Now put the fx nodes to be cached into items, remember the type is set to match the shot_step.yml secondary output type!
                debug(app=None,
                      method='shotFX_ScanSceneHook',
                      message='nparticle_caches: %s' % eachNpart,
                      verbose=False)
                cmds.setAttr('%s.visibility' % eachNpart, 1)
                items.append({"type": "nparticle_caches", "name": eachNpart})

        ## FX RENDERS
        nParticleShapes = [nPart for nPart in cmds.ls(type='nParticle')]
        if nParticleShapes:
            items.append({"type": "fx_renders", "name": "Render Final"})

        ## Check if the ocean exists..if it does do some work...
        if cmds.objExists('OCEAN_hrc'):
            ## Hide the preview planes
            cmds.setAttr('oceanPreviewPlane_prv.visibility', 0)
            cmds.setAttr('animPreviewPlane_prv.visibility', 0)
            ## Now set the ocean preview plane res to something very low and fast to calc
            cmds.setAttr('OCEAN_hrc.oceanRes', 1)
            ## Now make sure the wakes are calculating
            try:
                cmds.setAttr('OCEAN_hrc.oceanCalcOnOff', 1)
            except RuntimeError:
                pass
        else:
            raise TankError(
                "MAYA OCEAN IS MISSING FROM YOUR SHOT!!! YOU SHOULD FIX THIS BEFORE PUBLISHING TO LIGHTING!!!!!!"
            )
            cleanup.turnOnModelEditors()

        ## Check if cacheFiles exist and if yes, delete all of those.
        [cmds.delete(cache) for cache in cmds.ls(type='cacheFile')]
        [cmds.delete(cache) for cache in cmds.ls(type='cacheBlend')]

        ## Cleanup panels so nParticles don't keep crashing on export.
        for each in cmds.lsUI(panels=True):
            if 'outlinerPanel' in each or 'nodeEditorPanel' in each:
                cmds.deleteUI(each, panel=True)
        debug(app=None,
              method='shotFX_ScanSceneHook',
              message='FINISHED...',
              verbose=False)
        ## NOW MOVE ON TO PUBLISHING STEPS
        return items
Exemple #52
0
    def validate(self, settings, item):
        """
        Validates the given item to check that it is ok to publish. Returns a
        boolean to indicate validity.

        :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
        :returns: True if item is valid, False otherwise.
        """

        path = _session_path()

        # ---- ensure the session has been saved

        if not path:
            # the session still requires saving. provide a save button.
            # validation fails.
            error_msg = "The Maya session has not been saved."
            self.logger.error(
                error_msg,
                extra=_get_save_as_action()
            )
            raise Exception(error_msg)

        # get the normalized path
        path = sgtk.util.ShotgunPath.normalize(path)

        # check that there is still geometry in the scene:
        if not cmds.ls(geometry=True, noIntermediate=True):
            error_msg = (
                "Validation failed because there is no geometry in the scene "
                "to be exported. You can uncheck this plugin or create "
                "geometry to export to avoid this error."
            )
            self.logger.error(error_msg)
            raise Exception(error_msg)

        # get the configured work file template
        work_template = item.parent.properties.get("work_template")
        publish_template = item.properties.get("publish_template")

        # get the current scene path and extract fields from it using the work
        # template:
        work_fields = work_template.get_fields(path)

        # ensure the fields work for the publish template
        missing_keys = publish_template.missing_keys(work_fields)
        if missing_keys:
            error_msg = "Work file '%s' missing keys required for the " \
                        "publish template: %s" % (path, missing_keys)
            self.logger.error(error_msg)
            raise Exception(error_msg)

        # create the publish path by applying the fields. store it in the item's
        # properties. This is the path we'll create and then publish in the base
        # publish plugin. Also set the publish_path to be explicit.
        item.properties["path"] = publish_template.apply_fields(work_fields)
        item.properties["publish_path"] = item.properties["path"]


        # use the work file's version number when publishing
        if "version" in work_fields:
            item.properties["publish_version"] = work_fields["version"]

        # run the base class validation
        return super(MayaSessionGeometryPublishPlugin, self).validate(
            settings, item)
 def assertUsingMayaReferenceVariant():
     self.assertEqual(1, len(mc.ls('cubeNS:pCube1')))
     self.assertFalse(stage.GetPrimAtPath('/usd_top/pCube1_usd').IsValid())
     self.assertEqual('mayaReference',
                      mayaLoadingStyle.GetVariantSelection())
Exemple #54
0
 def __init__(self, NodeList):
     self.objs=cmds.ls(sl=True, l=True)
     self.NodeList=NodeList
     self.managedHIK = False
def create_rig():
    selected_obj = cmds.ls(sl=True)
    
    if (len(selected_obj)==0):
        cmds.inViewMessage( amg='Please select Mesh to create a <hl>Prop Rig</hl>.', pos='botCenter', fade=True)
        
        
    else:
        locator_pos = cmds.xform(loc, q=True, t=True, ws=True)  #locator position) 
        innerCtrl = cmds.circle(r = 60,n=('Ctrl'))    #made inner ctrl
        cmds.setAttr('Ctrl.rotateX',90)
        innerCtrlGrp = create_group(str(innerCtrl[0]))      #create offset grp on ctrl
        cmds.xform(innerCtrl[0], translation=locator_pos, ws=True) #set inner ctrl on locator position
        cmds.makeIdentity(innerCtrl[0], apply=True, t=1, r=1, s=1 ) #freeze inner ctrl
        
        jnt = cmds.joint(n=('Joint'))    #create jnt
        cmds.xform(jnt, translation=locator_pos, ws=True)  #set jnt on locator position
        jointGrp = create_group(str(jnt))  #create offset grp on jnt
        
        cmds.parentConstraint(innerCtrl,jointGrp,mo=True)   #constrain innerctrl with jnt offset grp
        
        
        #create global ctrl,rename it,make offset grp 
        global_ctrl = mel.eval("curve -d 1 -p -5 0 0 -p -3 0 -2 -p -3 0 -1 -p -1 0 -1 -p -1 0 -3 -p -2 0 -3 -p 0 0 -5 -p 2 0 -3 -p 1 0 -3 -p 1 0 -1 -p 3 0 -1 -p 3 0 -2 -p 5 0 0 -p 3 0 2 -p 3 0 1 -p 1 0 1 -p 1 0 3 -p 2 0 3 -p 0 0 5 -p -2 0 3 -p -1 0 3 -p -1 0 1 -p -3 0 1 -p -3 0 2 -p -5 0 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 18 -k 19 -k 20 -k 21 -k 22 -k 23 -k 24 ;")
        
        global_ctrl_NN = cmds.rename(global_ctrl,('Global_Ctrl'))
        global_ctrl_NN_Grp = create_group(str(global_ctrl_NN))
        cmds.setAttr('Global_Ctrl.scale',20,20,20)
        cmds.makeIdentity(global_ctrl_NN, apply=True, t=1, r=1, s=1 )

        try:
            sknCls = cmds.skinCluster(jnt,selected_obj)
        except:
            cmds.warning( 'select a mesh first')
            print 'select a mesh first'
             
        #organising   
        cmds.parent(innerCtrlGrp,global_ctrl_NN)
        world_grp = cmds.group(global_ctrl_NN_Grp,jointGrp)
        world_grp_NN = cmds.rename(world_grp,('World'))

        geoGrp = cmds.group(selected_obj)
        geoGrpNN = cmds.rename(geoGrp,('Geo'))
        cmds.parent(geoGrpNN,world_grp_NN)
        cmds.delete(loc) 
        
        #creating attributes
       
            
        cmds.addAttr('Global_Ctrl' ,longName="GlobalScale" ,at= "float",defaultValue= 1.0,minValue= 0,k=1,dv=1)
        cmds.addAttr('Global_Ctrl',longName= "Mesh_Display",at= "enum",en= "Normal:Template:Reference")
        cmds.addAttr('Global_Ctrl',longName= "Ctrl_Visibility",at="bool",k= 1,dv=1)
        cmds.addAttr('Global_Ctrl',longName= "Mesh_Visibility",at= "bool",k= 1,dv=1)
    

        cmds.setAttr('Global_Ctrl'+".Mesh_Display",keyable=False,channelBox= True) 
        
        cmds.connectAttr('Global_Ctrl'+'.Ctrl_Visibility',innerCtrlGrp+'.visibility',f=True)
        cmds.connectAttr('Global_Ctrl'+'.Mesh_Visibility',geoGrpNN+'.visibility',f=True)
        cmds.setAttr("Geo.overrideEnabled",1)
        cmds.connectAttr('Global_Ctrl'+'.Mesh_Display','Geo'+'.overrideDisplayType')
        cmds.connectAttr('Global_Ctrl'+'.GlobalScale','Global_Ctrl'+'.scaleX')
        cmds.connectAttr('Global_Ctrl'+'.GlobalScale','Global_Ctrl'+'.scaleY')
        cmds.connectAttr('Global_Ctrl'+'.GlobalScale','Global_Ctrl'+'.scaleZ')
    def testMeshTranslator_variantswitch(self):
        mc.AL_usdmaya_ProxyShapeImport(file='./testMeshVariants.usda')
        self.assertTrue(Tf.Type.Unknown != Tf.Type.FindByName(
            'AL::usdmaya::fileio::translators::Mesh'))
        # test initial state has no meshes
        self.assertEqual(len(mc.ls(type='mesh')), 0)

        stage = translatortestutils.getStage()
        stage.SetEditTarget(stage.GetSessionLayer())

        variantPrim = stage.GetPrimAtPath("/TestVariantSwitch")
        variantSet = variantPrim.GetVariantSet("MeshVariants")

        # the MeshA should now be in the scene
        variantSet.SetVariantSelection("ShowMeshA")
        mc.AL_usdmaya_TranslatePrim(
            ip="/TestVariantSwitch/MeshA", fi=True,
            proxy="AL_usdmaya_Proxy")  # force the import
        self.assertEqual(len(mc.ls('MeshA')), 1)
        self.assertEqual(len(mc.ls('MeshB')), 0)
        self.assertEqual(len(mc.ls(type='mesh')), 1)

        #######
        # the MeshB should now be in the scene

        variantSet.SetVariantSelection("ShowMeshB")

        #print stage.ExportToString()
        mc.AL_usdmaya_TranslatePrim(
            ip="/TestVariantSwitch/MeshB", fi=True,
            proxy="AL_usdmaya_Proxy")  # force the import
        self.assertEqual(len(mc.ls('MeshA')), 0)
        self.assertEqual(len(mc.ls('MeshB')), 1)
        self.assertEqual(len(mc.ls(type='mesh')), 1)

        # the MeshA and MeshB should be in the scene
        variantSet.SetVariantSelection("ShowMeshAnB")
        mc.AL_usdmaya_TranslatePrim(ip="/TestVariantSwitch/MeshB",
                                    fi=True,
                                    proxy="AL_usdmaya_Proxy")
        mc.AL_usdmaya_TranslatePrim(ip="/TestVariantSwitch/MeshA",
                                    fi=True,
                                    proxy="AL_usdmaya_Proxy")

        self.assertEqual(len(mc.ls('MeshA')), 1)
        self.assertEqual(len(mc.ls('MeshB')), 1)
        self.assertEqual(len(mc.ls(type='mesh')), 2)

        # switch variant to empty
        variantSet.SetVariantSelection("")
        self.assertEqual(len(mc.ls(type='mesh')), 0)
# ****************************************** S K I D     S E T D R E S S     T O O L S ******************************************

import maya.cmds as cmds
import maya.mel as mel
import os, shutil, datetime
import commonTools

referenceNodes = cmds.ls(type='reference')

# ****************************************** F U N C T I O N S ******************************************


def RNfromSelection():
    '''This will select every master reference node for selected geometries that has a controller'''
    # 1. controllers from selection
    ctrls = []
    for n in cmds.ls(selection=True, referencedNodes=True):
        if not 'ctrl' in n:
            pass
        else:
            ctrls.append(n)
    # 2. master reference node from ctrl
    rn = []
    for ctrl in ctrls:
        n = cmds.referenceQuery(ctrl, referenceNode=True, p=True)
        rn.append(n)
    return rn


def allRN():
    # Returns all Reference nodes in the scnene
#scripts from dragon rig makin' at Buck

#create quick select set for selected controls

import maya.cmds as cmds

sel = cmds.ls(sl=True)

cmds.sets(text="gCharacterSet", name="headControls")

for obj in sel:
    cmds.sets("headControls", e=True, add=obj)


#apply a series of blend shapes to a series of objects

import maya.cmds as cmds

sel = cmds.ls(sl=True)

for x in range(0, len(sel)):
    num = (x%10)+1
    thisTarget = "lf_stripWaveDriver%02d_geo"%num

    BS = cmds.blendShape(thisTarget, sel[x], origin="local")
    cmds.blendShape(BS, e=True, w=[(0,1)])


#to create bend deformers on each of the driving cards and orient them correctly

import maya.cmds as cmds
def parse_objects(map_attr):
    """Parse attribute returned from `filePathEditor` into XGen object names

    (NOTE) Remember to refresh filePathEditor by calling
           `cmds.filePathEditor(refresh=True)`, or the
           fxmodule index might not return correctly.

    >>> cmds.filePathEditor(refresh=True)
    >>> maps = cmds.filePathEditor(q=1, listFiles="", withAttribute=1)
    ["descriptionShape.primitive.ClumpingFXModule(1).HeadPoint", ...]
    >>> parse_objects(maps[0])
    ('CY_Mon_Hair', 'description', 'Clumping2', 'pointDir', 0)

    Args:
        map_attr (str): An attribute path returned from `cmds.filePathEditor`

    Returns:
        tuple: Names of palette, description, object, attr, attr-index

    """
    address = map_attr.split(".")

    # The description shape name in `map_attr` string is a short name,
    # and since we only need the description transform short name, it
    # doesn't matter which shape node we get from `cmds.ls`.
    desc_shape = cmds.ls(address[0])[0]
    description = str(cmds.listRelatives(desc_shape,
                                         parent=True)[0])  # get short name
    palette = get_palette_by_description(description)

    if address[1] == "glRenderer":
        subtype = "GLRenderer"
    else:
        # primitive, generator
        subtype = xg.getActive(palette, description,
                               str(address[1].capitalize()))

    if len(address) < 4:
        # Example: descriptionShape.generator.mask

        attr = address[2]
        attr, attr_indx = _parse_attribute(attr, subtype)

        return palette, description, subtype, attr, attr_indx

    else:
        # Example: descriptionShape.primitive.ClumpingFXModule(1).HeadPoint

        modifier_cls, mod_indx = address[2][:-1].split("(")
        mod_indx = int(mod_indx)

        attr = address[3]
        attr, attr_indx = _parse_attribute(attr, subtype)

        try:
            module = xg.fxModules(palette, description)[mod_indx]
        except IndexError:
            raise IndexError("Object not found, possible `filePathEditor` "
                             "not refreshed: {}".format(map_attr))
        else:
            if xg.fxModuleType(palette, description, module) == modifier_cls:

                return palette, description, module, attr, attr_indx

        raise Exception("Object not found, this is a bug: {}".format(map_attr))
Exemple #60
0
def resize_masterShape(self,sizeBy=None,resize=False):
    try:
        
        _short = self.p_nameShort        
        _str_func = '[{0}] resize_masterShape'.format(_short)
        log.debug("|{0}| >> ".format(_str_func)+ '-'*80)
        _sel = mc.ls(sl=True)
        _bb = False
        _bb = self.baseSize
        
        if resize:
            if _sel:
                _bb = TRANS.bbSize_get(_sel,False)
            #elif self.getBlockChildren():
            #    sizeBy = mc.ls(self.getBlockChildren(asMeta=False))
            #    _bb = TRANS.bbSize_get(sizeBy,False)
            self.baseSize = _bb

        log.debug("|{0}| >> _bb: {1}".format(_str_func,_bb))

        mHandleFactory = self.asHandleFactory(_short)
        mc.delete(self.getShapes())
        
        _average = MATH.average([_bb[0],_bb[2]])
        _size = _average * 1.5
        _offsetSize = _average * .01    
        _blockScale = self.blockScale
        mFormNull = self.atUtils('stateNull_verify','form')
        mNoTransformNull = self.atUtils('noTransformNull_verify','form')
        
        if resize or self.controlOffset == .9999:
            self.controlOffset = _offsetSize
            
        #Main curve ===========================================================================
        _crv = CURVES.create_fromName(name='circle',direction = 'y+', size = 1)
        mCrv = cgmMeta.asMeta(_crv)
        SNAP.go(mCrv.mNode,self.mNode,rotation=False)
        TRANS.scale_to_boundingBox(mCrv.mNode, [_bb[0],None,_bb[2]])
        
        
        #mDup = mCrv.doDuplicate(po=False)
        #mDup.p_position = MATH.list_add(mDup.p_position, [0,_offsetSize,0])
        
        RIG.shapeParent_in_place(self.mNode,_crv,False)
        #RIG.shapeParent_in_place(self.mNode,mDup.mNode,False)
        
        mHandleFactory.color(self.mNode,'center','main',transparent = False)
        
        #Bounding box ==================================================================
        if self.getMessage('bbHelper'):
            self.bbHelper.delete()
            
        _bb_shape = CURVES.create_controlCurve(self.mNode,'cubeOpen', size = 1, sizeMode='fixed')
        _bb_newSize = MATH.list_mult(self.baseSize,[_blockScale,_blockScale,_blockScale])
        TRANS.scale_to_boundingBox(_bb_shape,_bb_newSize)
        mBBShape = cgmMeta.validateObjArg(_bb_shape, 'cgmObject',setClass=True)
        mBBShape.p_parent = mFormNull
        
        mBBShape.inheritsTransform = False
        mc.parentConstraint(self.mNode,mBBShape.mNode,maintainOffset=False)
        
        SNAPCALLS.snap( mBBShape.mNode,self.mNode,objPivot='axisBox',objMode='y-')
        
        CORERIG.copy_pivot(mBBShape.mNode,self.mNode)
        self.doConnectOut('baseSize', "{0}.scale".format(mBBShape.mNode))
        #mHandleFactory.color(mBBShape.mNode,controlType='sub')
        mBBShape.setAttrFlags()
        
        mBBShape.doStore('cgmName', self)
        mBBShape.doStore('cgmType','bbVisualize')
        mBBShape.doName()
        mBBShape.template = True
        self.connectChildNode(mBBShape.mNode,'bbHelper')
        
        #Offset visualize ==================================================================
        if self.getMessage('offsetHelper'):
            self.offsetHelper.delete()
            
        #Need to guess our offset size based on bounding box volume
        
        mShape = self.getShapes(asMeta=True)[0]
        l_return = mc.offsetCurve(mShape.mNode, distance = 1, ch=True )
        #pprint.pprint(l_return)
        mHandleFactory.color(l_return[0],'center','sub',transparent = False)
        
        mOffsetShape = cgmMeta.validateObjArg(l_return[0], 'cgmObject',setClass=True)
        mOffsetShape.p_parent = mNoTransformNull
        #mOffsetShape.doSnapTo(self)
        #mc.pointConstraint(self.mNode,mOffsetShape.mNode,maintainOffset=True)        
        #mc.orientConstraint(self.mNode,mOffsetShape.mNode,maintainOffset=True)        
        mOffsetShape.inheritsTransform = False
        
        mOffsetShape.dagLock()
        
        _arg = '{0}.distance = -{1}.controlOffset'.format(l_return[1],
                                                          self.mNode)
        NODEFACTORY.argsToNodes(_arg).doBuild()
        #self.doConnectOut('controlOffset',"{0}.distance".format(l_return[1]))
        
        mOffsetShape.doStore('cgmName', self)
        mOffsetShape.doStore('cgmType','offsetVisualize')
        mOffsetShape.doName()        
        
        self.connectChildNode(mOffsetShape.mNode,'offsetHelper')                
        
        
        
        
        return
        #Offset visualize ==================================================================
        if self.getMessage('offsetHelper'):
            self.offsetHelper.delete()
        
        mShape = self.getShapes(asMeta=True)[0]
        l_return = mc.offsetCurve(mShape.mNode, distance = 1, ch=True )
        #pprint.pprint(l_return)
        mHandleFactory.color(l_return[0],'center','sub',transparent = False)
        
        mOffsetShape = cgmMeta.validateObjArg(l_return[0], 'cgmObject',setClass=True)
        mOffsetShape.p_parent = mFormNull
        
        mOffsetShape.inheritsTransform = False
        mc.parentConstraint(self.mNode,mOffsetShape.mNode,maintainOffset=False)        
        
        #mOffsetShape.setAttrFlags()
        
        _arg = '{0}.distance = -{1}.controlOffset * {1}.blockScale'.format(l_return[1],
                                                                           self.mNode)
        NODEFACTORY.argsToNodes(_arg).doBuild()
        #self.doConnectOut('controlOffset',"{0}.distance".format(l_return[1]))
        
        mOffsetShape.doStore('cgmName', self)
        mOffsetShape.doStore('cgmType','offsetVisualize')
        mOffsetShape.doName()        
        
        self.connectChildNode(mOffsetShape.mNode,'offsetHelper')        
        
        return

        _crv = CURVES.create_fromName(name='squareOpen',direction = 'y+', size = 1)    
        TRANS.scale_to_boundingBox(_crv, [_bb[0],None,_bb[2]])
    
        mHandleFactory.color(_crv,'center','sub',transparent = False)
    
        mCrv = cgmMeta.validateObjArg(_crv,'cgmObject')
        l_offsetCrvs = []
        for shape in mCrv.getShapes():
            offsetShape = mc.offsetCurve(shape, distance = -_offsetSize, ch=True )[0]
            mHandleFactory.color(offsetShape,'center','main',transparent = False)
            l_offsetCrvs.append(offsetShape)
    
        RIG.combineShapes(l_offsetCrvs + [_crv], True)
        SNAP.go(_crv,self.mNode)    
    
        RIG.shapeParent_in_place(self.mNode,_crv,True)
    
        self.baseSize = _bb
        
        
        
        #Bounding box ==================================================================
        if self.getMessage('offsetVisualize'):
            self.bbVisualize.delete()
            
        _bb_shape = CURVES.create_controlCurve(self.mNode,'cubeOpen', size = 1.0, sizeMode='fixed')
        mBBShape = cgmMeta.validateObjArg(_bb_shape, 'cgmObject',setClass=True)
        mBBShape.p_parent = mFormNull
        
        SNAPCALLS.snap( mBBShape.mNode,self.mNode,objPivot='axisBox',objMode='y-')
        
        
        CORERIG.copy_pivot(mBBShape.mNode,self.mNode)
        self.doConnectOut('baseSize', "{0}.scale".format(mBBShape.mNode))
        mHandleFactory.color(mBBShape.mNode,controlType='sub')
        mBBShape.setAttrFlags()
        
        mBBShape.doStore('cgmName', self)
        mBBShape.doStore('cgmType','bbVisualize')
        mBBShape.doName()    
        
        self.connectChildNode(mBBShape.mNode,'bbHelper')
        
        
        return True
    
    except Exception,err:
        cgmGEN.cgmExceptCB(Exception,err,localDat=vars())