Example #1
0
def surfaceArea(surface,worldSpace=True):
	'''
	Calculates the surface area of a specified nurbs surface.
	@param surface: Nurbs surface to calculate the surface area for
	@type surface: str
	@param worldSpace: Calculate the surface area in world or local space units
	@type worldSpace: bool
	'''
	# Check Surface
	if not mc.objExists(surface): raise UserInputError('Object '+surface+' does not exist!')
	if mc.objectType(surface) == 'transform':
		surfaceShape = mc.listRelatives(surface,s=True,ni=True)[0]
		if mc.objectType(surfaceShape) != 'nurbsSurface':
			raise UserInputError('Object '+surface+' is not a valid nurbs surface!')
		surface = surfaceShape
	
	# Get MFnNurbsSurface
	surfaceFn = getSurfaceFn(surface)
	# Get surface area
	area = 0.0
	if worldSpace: area = surfaceFn.area(OpenMaya.MSpace.kWorld)
	else: area = surfaceFn.area(OpenMaya.MSpace.kObject)
	
	# Return result
	return area
Example #2
0
    def doIt(self, argList):
        # get objects from argument list (size >= 2)
        try:
            obj = misc.getArgObj(self.syntax(), argList)
            if (len(obj) < 2):
                cmds.error("Select at least 2 objects!")
                return
            if (cmds.objectType(obj[0]) != 'transform' or cmds.objectType(obj[1]) != 'transform'):
                cmds.error("Object is not of type transform!")
                return
        except:
            cmds.warning("No objects selected or only one object given!")
            return

        argData = om.MArgParser(self.syntax(), argList)

        # read all arguments and set default values
        keepCD = argData.flagArgumentBool('keepConvexDecomposition', 0) if (argData.isFlagSet('keepConvexDecomposition')) else True
        nvol = argData.flagArgumentDouble('normVolume', 0) if (
            argData.isFlagSet('normVolume')) else 100.0
        norm = argData.flagArgumentBool('norm', 0) if (
            argData.isFlagSet('norm')) else True
        s_file = os.path.abspath(argData.flagArgumentString('saveFile', 0)) if (argData.isFlagSet('saveFile')) else ""
        save = False
        if s_file != "":
            o_file = open(s_file, 'w')
            o_file.write("i0, i1, name0, name1, its_volume, dice\n")
            save = True

        # get all flags for vhacd over static parsing method
        vhacd_par = vhacd.vhacd.readArgs(argData)
        if (vhacd_par is None):
            cmds.error("V-HACD: one or more arguments are invalid!")
            return

        #norm the volume
        if norm:
            for o in obj:
                v = cmds.getVolume(o)
                scale_factor = (nvol/ v) ** (1./3)
                # cmds.xform(o, scale=[scale_factor, scale_factor, scale_factor])
                cmds.scale(scale_factor, scale_factor, scale_factor, o, relative=True)
                cmds.makeIdentity(o, apply=True)

        intersection_matrix = np.matrix(str(cmds.intersection(obj, kcd=keepCD, matlabOutput=True, **vhacd_par)))
        dice_matrix = np.matrix(intersection_matrix)

        for i in range(0, intersection_matrix.shape[0]):
            for j in range(i, intersection_matrix.shape[1]):
                its_volume = intersection_matrix[i, j]
                dice_matrix[i, j] = (its_volume*2)/(intersection_matrix[i, i]+intersection_matrix[j, j])
                if save:
                    o_file.write(",".join((str(i), str(j), obj[i], obj[j], str(its_volume), str(dice_matrix[i, j]))))
                    o_file.write("\n")
                    o_file.flush()

        if save:
            o_file.close()

        self.setResult(str(dice_matrix))
Example #3
0
def attachCurves(name, identifier, jobInfo, isConstant=False):
	cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._attach.attachCurves")
	if cmds.objExists( name ):
		curObj = cmds.connectionInfo(name+".visibility", sfd=True)
		if curObj and cmds.objectType(curObj) == "ExocortexAlembicCurvesDeform":
			attachTimeAndFile(curObj, jobInfo, isConstant)
			return

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

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

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

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

	cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._attach.attachCurves")
	pass
Example #4
0
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'
Example #5
0
	def getShapes(self,transform,getIntermediate=0):
		'''
		Return a list of shapes under a specified transform
		@param transform: Transform to query
		@type transform: str
		@param getIntermediate: Return intermediate shapes.
		@type getIntermediate: bool
		'''
		# Initialize arrays
		returnShapes = []
		
		# Check for shape input
		if (mc.objectType(transform) == 'mesh') or (mc.objectType(transform) == 'nurbsCurve') or (mc.objectType(transform) == 'nurbsSurface'):
			# Get transform parent
			transform = mc.listRelatives(transform,p=1)[0] # Get element[0] from parent list
		
		# Get shape lists
		if mc.objectType(transform) == 'transform':
			allShapes = mc.listRelatives(transform,s=1)
			for shape in allShapes:
				if mc.getAttr(shape+'.intermediateObject') == getIntermediate:
					returnShapes.append(shape)
		else:
			raise UserInputError('Unable to find shape node for '+transform+'!')
		# Return result
		return returnShapes
Example #6
0
def setDrawOverrideColor( obj, color=17 ):
	"""
	edit the given object's shape node override color
	"""
	shapes = []
	if not cmd.objectType( obj, i='nurbsCurve' ) or not cmd.objectType( obj, i='nurbsSurface' ) or not cmd.objectType( obj, i='mesh' ):
		shapes.append( obj )
	for s in listRelatives( obj, s=True, pa=True ) or []:
		shapes.append( s )

	if shapes:
		for s in shapes:
			conns = cmd.listConnections( '%s.drawOverride' % s, s=True )
			if not conns:
				if not color == 0:
					cmd.setAttr ('%s.overrideEnabled' % s, e=True, l=False )
					cmd.setAttr ('%s.overrideEnabled' % s, 1 )

					cmd.setAttr ('%s.overrideColor' % s, e=True, l=False )
					cmd.setAttr ('%s.overrideColor' % s, color )
				else:
					cmd.color( s )

					cmd.setAttr ('%s.overrideColor' % s, e=True, l=False )
					cmd.setAttr ('%s.overrideColor' % s, color )

					cmd.setAttr ('%s.overrideEnabled' % s, e=True, l=False )
					cmd.setAttr ('%s.overrideEnabled' % s, 0 )


#end
Example #7
0
	def __init__(self,deformer=''):
		'''
		DeformerData class initializer.
		@param deformer: Deformer to initialize data for
		@type deformer: str
		'''
		# Check deformer
		if not deformer: return
		
		# Initialize class data members
		self.deformerName = ''
		self.deformerType = ''
		self.deformerData = {}
		
		# Check deformer
		if not glTools.utils.deformer.isDeformer(deformer):
			raise Exception('Object '+deformer+' is not a valid deformer! Unable to instantiate DeformerData() class!!')
		
		# Get basic deformer info
		self.deformerName = deformer
		self.deformerType = mc.objectType(deformer)
		self.envelope = mc.getAttr(deformer+'.envelope')
		
		# Get geometry affected by deformer
		affectedGeo = glTools.utils.deformer.getAffectedGeometry(deformer,returnShapes=1)
		
		# Build data lists for each affected geometry
		for geo in affectedGeo.iterkeys():
			geo = str(geo)
			self.deformerData[geo] = {}
			self.deformerData[geo]['index'] = affectedGeo[geo]
			self.deformerData[geo]['geometryType'] = str(mc.objectType(geo))
			self.deformerData[geo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(deformer,geo)
			self.deformerData[geo]['weights'] = glTools.utils.deformer.getWeights(deformer,geo)
Example #8
0
def getShape(crv):
    """If crv is a shape node, return it.  If it is
    a transform with a single shape parent, return the shape.

    @param crv: the shape or transform node
    @raise RuntimeError: if node is not a shape and has multiple
      or no shape children
    """

    if MC.objectType(crv, isAType='geometryShape'):
        return crv

    result = None
    shapes = MC.listRelatives(crv) or []
    for shape in shapes:
        #ni flag broken?
        if MC.getAttr('%s.intermediateObject' % shape):
            continue

        if MC.objectType(shape, isAType='geometryShape'):
            if result is not None:
                raise RuntimeError("Multiple shapes under '%s'" % crv)
            result = shape

    if result is None:
        raise RuntimeError("No shapes under '%s'" % crv)
    return result
Example #9
0
def altFrame(*args):
    # cmds.nodeType(sel), object type
    # optimize, real slow
    pnl = cmds.getPanel(withFocus=True)
    typ = cmds.getPanel(typeOf=pnl)
    if typ == 'modelPanel':
        sel = cmds.ls(sl=True, fl=True)
        gs = ac.GraphSelection()
        locs = []
        if sel:
            for item in sel:
                if cmds.objectType(item, i='transform') or cmds.objectType(item, i='joint'):
                    loc = cn.locator(obj=item, ro='zxy', X=0.35, constrain=False, shape=False)[0]
                    locs.append(loc)
                else:
                    try:
                        print cmds.listRelatives(item, parent=True)[0], '_______________'
                        loc = cn.locator(obj=cmds.listRelatives(item, parent=True)[0], ro='zxy', X=0.35, constrain=False, shape=False)
                        print loc, '_____________________'
                        loc = loc[0]
                        locs.append(loc)
                    except:
                        message('didnt frame object: ' + item)
            cmds.select(locs)
            mel.eval("fitPanel -selected;")
            cmds.delete(locs)
            gs.reselect()
        else:
            message('select an object')
    else:
        mel.eval("fitPanel -selected;")
    def __add_atributes_to_yeti_nodes(self):

        #get all the transform of the yeti nodes
        objs = cmds.ls(type='pgYetiMaya', transforms=True)
        objs = objs + cmds.ls(type='pgYetiGroom', transforms=True)
        yetinodes = []
        for i in objs:
            if cmds.objectType(i, isType='pgYetiMaya') or cmds.objectType(i, isType='pgYetiGroom'):
                yetinodes.append(i)

        cmds.select(cl=True)

        long_name = "connectedMeshName"
        nice_name = "Connected Mesh Name"
        long_name_u = "connectedMeshUUID"
        nice_name_u = "Connected Mesh UUID"

        # add the name and uuid of the connected mesh to the yeti node
        for i in yetinodes:
            inputGeometryList = cmds.listConnections(i + ".inputGeometry", s=True, sh=True)
            count = 0
            for geo in inputGeometryList:
                object_uuid = cmds.ls(geo, uuid=True)[0]
                object_name = geo
                transform = cmds.listRelatives(i, parent=True)[0]

                cmds.addAttr(transform, ln=long_name + '' + str(count), nn=nice_name, dt="string")
                cmds.setAttr(transform + '.' + long_name + '' + str(count), object_name, type="string")
                cmds.setAttr(transform + '.' + long_name + '' + str(count), lock=True, type="string")

                cmds.addAttr(transform, ln=long_name_u + '' + str(count), nn=nice_name_u, dt="string")
                cmds.setAttr(transform + '.' + long_name_u + '' + str(count), object_uuid, type="string")
                cmds.setAttr(transform + '.' + long_name_u + '' + str(count), lock=True, type="string")
                count += 1
Example #11
0
    def lights_in_scene(self):
        """List Lights in scene """

        cmds.select(clear=True)

        self.lights = cmds.ls(type="light")
        if self.lights is False:
            cmds.error("No light in scene")
        cmds.select(self.lights, add=True)
        self.all_lights = cmds.ls(sl=True)

        self.list_spot = []
        self.list_vray = []
        self.list_standard = []

        for s in self.all_lights:
            if cmds.objectType(s, isType='spotLight'):
                self.list_spot.append(s)
            elif cmds.objectType(s, isType='VrayLight'):
                self.list_vray.append(s)
            else:
                self.list_standard.append(s)
        cmds.select(clear=True)
        self.sp_len = len(self.list_spot)
        self.vr_len = len(self.list_vray)
        self.sd_len = len(self.list_standard)

        cmds.select(self.all_lights[-1])
Example #12
0
 def getParentConstraintDic (self, parentConstraint) :
     returnedDic = {'alias':{}, "object":None }
     aliasDic={}
     if cmds.objectType(parentConstraint)=="parentConstraint":
         WA = cmds.parentConstraint (parentConstraint, q = True, weightAliasList = True)
         TL = cmds.parentConstraint (parentConstraint, q = True, targetList = True)
     
     elif cmds.objectType(parentConstraint)=="orientConstraint":
         WA = cmds.orientConstraint (parentConstraint, q = True, weightAliasList = True)
         TL = cmds.orientConstraint (parentConstraint, q = True, targetList = True)
     
     elif cmds.objectType(parentConstraint)=="pointConstraint":
         WA = cmds.pointConstraint (parentConstraint, q = True, weightAliasList = True)
         TL = cmds.pointConstraint (parentConstraint, q = True, targetList = True)
     
     else:
         "error No constraint Type identified"
     
     if len(WA) == len(TL):
         for eachWAIndex in range(0,len(WA)):
             aliasDic[WA[eachWAIndex]] = TL[eachWAIndex]
     
     returnedDic["object"] = cmds.listConnections(parentConstraint + ".constraintRotateX")[0]
     returnedDic["alias"] = aliasDic
     return returnedDic
Example #13
0
def transferUvHierarchy( fromTopGroup, toTopGroup):
    fromChildren = cmds.listRelatives( fromTopGroup, ad=True, type='mesh', fullPath=True)[1:]
    toChildren = cmds.listRelatives( toTopGroup, ad=True, type='mesh', fullPath=True)[1:]
    
    print fromChildren
    tmp = copy.copy(fromChildren)
    for fChild in tmp:
        split = fChild.split("|")[1:]
        #print split
        split[0] = toTopGroup
        tChild = "|" + "|".join( split)
        print fChild, tChild
        if tChild in toChildren:
            
            fromChildren.remove( fChild)
            toChildren.remove( tChild)
            cmds.select( fChild, r=True)
            tShapes = getShapes(tChild)
            print 'transfered \n%s \n | \n%s' % (fChild, tChild)
            tChildShapeOrig = tShapes[0]+'Orig'
            
            if (cmds.objectType(fChild) == 'transform' and cmds.objectType(tChild) == 'transform' and cmds.objectType(tChildShapeOrig) == 'mesh'):
                cmds.select( tChildShapeOrig, add=True)
                cmds.transferAttributes( transferPositions=0, transferNormals=0, transferUVs=2, transferColors=0, sampleSpace=4, sourceUvSpace="map1", targetUvSpace="map1", searchMethod=3, flipUVs=0, colorBorders=1)
    print toChildren
    print fromChildren
    def blendShapeWeightCopy(self):
        sels = cmds.ls(sl = True)
        if len(sels) >= 2:
            sourceObj = sels[0]
            sourceShape = cmds.listRelatives(sourceObj,s = True)[0]
            sourceBlendShape = cmds.listConnections(sourceShape + '.inMesh',scn = True,destination = False)

            destinationObjs = sels[1:]

            for destinationObj in destinationObjs:
                destinationShape = cmds.listRelatives(destinationObj,s = True)[0]
                destinationBlendShape = cmds.listConnections(destinationShape + '.inMesh',scn = True,destination = False)
                print sourceBlendShape,destinationBlendShape
                if sourceBlendShape != None:
                    if cmds.objectType(sourceBlendShape[0])== 'blendShape':
                        if destinationBlendShape != None:
                            if cmds.objectType(destinationBlendShape[0])== 'blendShape':
                                vtxs = cmds.ls(sourceShape + '.vtx[0:]',fl = True)
                                vtxNum = len(vtxs)
                                for x in range(vtxNum):
                                    weight = cmds.getAttr('%s.it[0].bw[%d]'%( sourceBlendShape[0] , int(x)))
                                    cmds.setAttr('%s.it[0].bw[%d]'%( destinationBlendShape[0] , int(x)),weight)
                            else:
                                cmds.warning(destinationBlendShape + ' There is no blendShape')
                        else:
                            cmds.warning(destinationBlendShape + ' There is no blendShape')
                    else:
                        cmds.warning(sourceObj + ' There is no blendShape')
                else:
                    cmds.warning(sourceObj + ' There is no blendShape')
        else:
            cmds.warning('plase select at least two model')
Example #15
0
	def getSingleIndexComponentList(self,componentList=[]):
		'''
		Convert a 2 or 3 value index to a single value index.
		getSingleIndexComponentList(componentList=[]): Returns a flat list of integer component index values.
		
		@param componentList: A list of component names. if empty will default to selection.
		@type componentList: list
		'''
		
		# Clear flattenedIndexList
		singleIndexList = {}
		
		# Get selection if componentList is empty
		if not componentList: componentList = mc.ls(sl=True,fl=True)
		
		# Set active selection
		#if componentList: mc.select(componentList)
		#else: return {}
		if not componentList: return singleIndexList
		
		# Get component selection
		componentSel = self.getComponentIndexList(componentList)
		
		# Iterate through shape keys
		shapes = componentSel.keys()
		for shape in shapes:
			indexList = componentSel[shape]
			
			if mc.objectType(shape) == 'transform':
				shape = self.selectionUtils.getShapes(shape)[0]
			
			if (mc.objectType(shape) == 'mesh') or (mc.objectType(shape) == 'nurbsCurve'):
				singleIndexList[shape] = indexList
			
			elif mc.objectType(shape) == 'nurbsSurface':
				# Get nurbsSurface function set
				surfList = OpenMaya.MSelectionList()
				surfObj = OpenMaya.MObject()
				OpenMaya.MGlobal.getSelectionListByName(shape,surfList)
				surfList.getDependNode(0,surfObj)
				surfFn = OpenMaya.MFnNurbsSurface(surfObj)
				# CV count in V direction
				numV = surfFn.numCVsInV()
				# Check for periodic surface
				if surfFn.formInV() == surfFn.kPeriodic:
					numV -= surfFn.degreeV()
				singleIndexList[shape] = []
				for i in range(len(indexList)):
					singleIndexList[shape].append((indexList[i][0] * numV) + indexList[i][1])
				
			elif (mc.objectType(shape) == 'lattice'):
				sDiv = mc.getAttr(shape+'.sDivisions')
				tDiv = mc.getAttr(shape+'.tDivisions')
				singleIndexList[shape] = []
				for i in range(len(indexList)):
					singleIndexList[shape].append(indexList[i][0] + (indexList[i][1] * sDiv) + (indexList[i][2] * sdiv * tDiv) )
		
		# Return result
		return singleIndexList
Example #16
0
 def setNewFolder(self, folder):
     if not self.tex_file:
         return False
     if mc.objExists(self.name):
         if mc.objectType(self.name) == 'file':
             mc.setAttr('%s.fileTextureName' % self.name, os.path.join(folder, os.path.basename(self.tex_file)), type = 'string')
         elif mc.objectType(self.name) == 'aiImage':
             mc.setAttr('%s.filename' % self.name, os.path.join(folder, os.path.basename(self.tex_file)), type = 'string')
def put_obj(obj,rl):
    if type(obj) == types.ListType:
        for x in obj:
            p = cmds.listRelatives(x, shapes=True)
            if (cmds.objectType(x) =="transform" or cmds.objectType(x) == "mesh" or cmds.objectType(x) == "nurbsSurface"):
                cmds.editRenderLayerMembers(rl,x,noRecurse=True)
    else :
        cmds.editRenderLayerMembers(rl,obj,noRecurse=True)
Example #18
0
def RMRemoveChildren (Node):
    Children = cmds.listRelatives(Node,children=True)
    returnArray=[]
    for eachChildren in Children:
        if cmds.objectType(eachChildren) != "mesh" and cmds.objectType(eachChildren) != "nurbsCurve":
            cmds.parent(eachChildren , world = True)
            returnArray.append(eachChildren)
    return returnArray
def is_visible(node,
               displayLayer=True,
               intermediateObject=True,
               parentHidden=True,
               visibility=True):
    """Is `node` visible?

    Returns whether a node is hidden by one of the following methods:
    - The node exists (always checked)
    - The node must be a dagNode (always checked)
    - The node's visibility is off.
    - The node is set as intermediate Object.
    - The node is in a disabled displayLayer.
    - Whether any of its parent nodes is hidden.

    Roughly based on: http://ewertb.soundlinker.com/mel/mel.098.php

    Returns:
        bool: Whether the node is visible in the scene

    """

    # Only existing objects can be visible
    if not cmds.objExists(node):
        return False

    # Only dagNodes can be visible
    if not cmds.objectType(node, isAType='dagNode'):
        return False

    if visibility:
        if not cmds.getAttr('{0}.visibility'.format(node)):
            return False

    if intermediateObject and cmds.objectType(node, isAType='shape'):
        if cmds.getAttr('{0}.intermediateObject'.format(node)):
            return False

    if displayLayer:
        # Display layers set overrideEnabled and overrideVisibility on members
        if cmds.attributeQuery('overrideEnabled', node=node, exists=True):
            if cmds.getAttr('{0}.overrideEnabled'.format(node)) and \
               cmds.getAttr('{0}.overrideVisibility'.format(node)):
                return False

    if parentHidden:
        parents = cmds.listRelatives(node, parent=True, fullPath=True)
        if parents:
            parent = parents[0]
            if not is_visible(parent,
                              displayLayer=displayLayer,
                              intermediateObject=False,
                              parentHidden=parentHidden,
                              visibility=visibility):
                return False

    return True
Example #20
0
    def test_existingNodeMaintainsType(self):
        name = 'myControl'
        node = MC.createNode('joint', name=name)
        ctl = control.makeControl(name)
        self.assertTrue(MC.objectType(ctl, isType='joint'))
        MC.delete(ctl)

        node = MC.createNode('transform', name=name)
        ctl = control.makeControl(name)
        self.assertTrue(MC.objectType(ctl, isType='transform'))
	def renderAllLights(self, renderLights=[],useGroups=False):  
		lights = cmds.ls(dag=True,visible=True,lights=True, type='mentalrayIblShape')  
		#Check if there is any lights selected to only do those
		if renderLights == [] or renderLights == None:
			renderLights = cmds.ls( dag=True,  sl=True , lights=True, type='mentalrayIblShape')
		#if there isn't any light selected just get all the lights
		if renderLights == []:
			renderLights = lights

		lightNames = ""
		for light in renderLights:
			lightNames = lightNames + light + '\n' 
				

		windowName = 'ProgressWindow'
		if cmds.window(windowName, exists=True):
			cmds.deleteUI(windowName)
			
		window = cmds.window(windowName,t="Progress Report")
		
		cmds.columnLayout()
		cmds.iconTextStaticLabel( st='textOnly', l='Rendering Lights:' )
		cmds.iconTextStaticLabel( st='textOnly', l=lightNames )
		cmds.iconTextStaticLabel( st='textOnly', l='Process Bar' )
		progressControl = cmds.progressBar(maxValue=len(renderLights), width=300)
		cmds.showWindow( window )    
		
		lights = self.sortLightsByType(lights)
		#-Revised--hide ibl node that is at the end of lights list (sorted previously)
		if cmds.objectType( lights[-1], isType='mentalrayIblShape' ) == True:
			cmds.setAttr('%s.visibleInFinalGather' % lights[-1], 0)
			cmds.setAttr('%s.visibleInEnvironment' % lights[-1], 0)
				
		cmds.hide(lights)
		lightCount = 0

		if useGroups==True:
			renderLightsGroups = self.groupLightsByName(renderLights)
			cmds.progressBar(progressControl,edit=True, maxValue=len(renderLightsGroups.keys()), width=300)
			for group in renderLightsGroups:
				self.renderOnlyThisLight(renderLightsGroups[group]) 
				progressInc = cmds.progressBar(progressControl, edit=True, pr=lightCount+1) 
				lightCount+=1
		else:
			print renderLights
			for light in renderLights:
				self.renderOnlyThisLight(light) 
				progressInc = cmds.progressBar(progressControl, edit=True, pr=lightCount+1) 
				lightCount+=1
					
		cmds.showHidden(lights)  
		#-Revised--since we sorted the lights by type we know that the lastone will be the IBL
		if cmds.objectType( lights[-1], isType='mentalrayIblShape' ) == True:
			cmds.setAttr('%s.visibleInFinalGather' % lights[-1], 1)
			cmds.setAttr('%s.visibleInEnvironment' % lights[-1], 1)
Example #22
0
 def print_part(obj, tab=0):
     t = ""
     if mc.objectType(obj, isType='mesh'):
         t = "#"
     elif mc.objectType(obj, isType='transform'):
         t = "+"
     print "|" + "----" * tab + t + obj.split("|")[-1]
     children = mc.listRelatives(obj, children=True, fullPath=True)
     if children:
         for c in children:
             print_part(c, tab + 1)
Example #23
0
def createIntermediate(shape):
    """
	Create and connect an intermediate shape for the specified geoemtry shape
	@param shape: Shape or create intermediate shape for
	@type shape: str
	"""
    # Check Shape
    if not mc.objExists(shape):
        raise Exception('Object "' + shape + '" does not exist!!')

    # Check Geometry Type
    geoType = mc.objectType(shape)
    if geoType == "transform":
        shapes = getShapes(shape, intermediates=False)
        if not shapes:
            raise Exception('Object "' + shape + '" has no valid shapes!!')
        shape = shapes[0]
        geoType = mc.objectType(shape)

    geoDict = {"mesh": ("outMesh", "inMesh"), "nurbsSurface": ("local", "create"), "nurbsCurve": ("local", "create")}
    if not geoDict.has_key(geoType):
        raise Exception("Invalid shape type (" + geoType + ') for "' + shape + '"!!')

    # Get transform
    transform = str(mc.listRelatives(shape, p=True)[0])

    # Rename current shape as intermediate
    shapeOrig = mc.rename(shape, shape + "Orig")
    """
	ind = 1
	shapeOrig = shape.replace('Shape','ShapeOrig')
	while(mc.objExists(shapeOrig)):
		shapeOrig =  shape.replace('Shape','ShapeOrig'+ind)
		ind += 1
	shapeOrig = mc.rename(shape,shape.replace('Shape','ShapeOrig'))
	"""
    # Create new shape
    shape = mc.createNode(geoType, n=shape, p=transform)
    mc.reorder(shape, f=True)

    # Connect shapes
    mc.connectAttr(shapeOrig + "." + geoDict[geoType][0], shape + "." + geoDict[geoType][1], f=True)

    # Set shapeOrig as intermediate
    mc.setAttr(shapeOrig + ".intermediateObject", 1)

    # Connect to existing shader
    shader = mc.listConnections(shapeOrig, type="shadingEngine")
    if shader:
        mc.sets(shapeOrig, rm=shader[0])
        mc.sets(shape, fe=shader[0])

        # Return result
    return shapeOrig
Example #24
0
def getDeformerSetMemberIndices(deformer, geometry=''):
    """
    Return a list of deformer set member vertex indices
    @param deformer: Deformer to set member indices for
    @type deformer: str
    @param geometry: Geometry to query deformer set membership for.
    @type geometry: str
    """
    # Check geometry
    geo = geometry
    if cmds.objectType(geometry) == 'transform':
        try:
            geometry = cmds.listRelatives(geometry, s=True, ni=True, pa=True)[0]
        except:
            raise Exception('Object "' + geo + '" is not a valid geometry!')
    # Get geometry type
    geometryType = cmds.objectType(geometry)

    # Get deformer set members
    deformerSetMem = getDeformerSetMembers(deformer, geometry)

    # ==========================
    # - Get Set Member Indices -
    # ==========================
    memberIdList = []

    # Single Index
    if geometryType == 'mesh' or geometryType == 'nurbsCurve' or geometryType == 'particle':
        memberIndices = OpenMaya.MIntArray()
        singleIndexCompFn = OpenMaya.MFnSingleIndexedComponent(deformerSetMem[1])
        singleIndexCompFn.getElements(memberIndices)
        memberIdList = list(memberIndices)

    # Double Index
    if geometryType == 'nurbsSurface':
        memberIndicesU = OpenMaya.MIntArray()
        memberIndicesV = OpenMaya.MIntArray()
        doubleIndexCompFn = OpenMaya.MFnDoubleIndexedComponent(deformerSetMem[1])
        doubleIndexCompFn.getElements(memberIndicesU, memberIndicesV)
        for i in range(memberIndicesU.length()):
            memberIdList.append([memberIndicesU[i], memberIndicesV[i]])

    # Triple Index
    if geometryType == 'lattice':
        memberIndicesS = OpenMaya.MIntArray()
        memberIndicesT = OpenMaya.MIntArray()
        memberIndicesU = OpenMaya.MIntArray()
        tripleIndexCompFn = OpenMaya.MFnTripleIndexedComponent(deformerSetMem[1])
        tripleIndexCompFn.getElements(memberIndicesS, memberIndicesT, memberIndicesU)
        for i in range(memberIndicesS.length()):
            memberIdList.append([memberIndicesS[i], memberIndicesT[i], memberIndicesU[i]])

    # Return result
    return memberIdList
Example #25
0
 def findSkinCluster(cls, sl = ''):
     """
     finding skin cluster of sl object
     """
     if cmds.objectType(sl) == 'transform':
         sl = cmds.listRelatives(sl)[0]
     sels = cmds.listConnections(sl)
     for sel in sels:
         if cmds.objectType(sel) == 'skinCluster':
             skinCls = sel
     return skinCls
Example #26
0
def isLayer(obj):
	'''
	Check if the specified object is a valid layer type
	@param obj: Object to check as layer
	@type obj: bool
	'''
	if not mc.objExists(obj): return False
	if mc.objectType(obj) == 'displayLayer': return True
	if mc.objectType(obj) == 'renderLayer': return True
	if mc.objectType(obj) == 'animLayer': return True
	return False
Example #27
0
 def set_to_tx(self):
     if not self.tex_file:
         return False
     tex_file_list = self.tex_file.split('.')
     tex_file_list[-1] = 'tx'
     new_tex_file = string.join(tex_file_list, '.')
     if mc.objExists(self.__node_name):
         if mc.objectType(self.__node_name) == 'file':
             mc.setAttr('%s.fileTextureName' % self.__node_name, new_tex_file, type='string')
         elif mc.objectType(self.__node_name) == 'aiImage':
             mc.setAttr('%s.filename' % self.__node_name, new_tex_file, type='string')
Example #28
0
def clearWeights(objectList=None):
	'''
	Reset the skinCluster weight values (set to 0.0) for the specified objects/components
	@param objectList: List of objects/components whose skinCluster weights will be reset
	@type objectList: list
	'''
	# Define valid geometry list
	geometryList = ['mesh','nurbsCurve','nurbsSurface','lattice']
	
	# Get selection
	if objectList: mc.select(objectList)
	objectList = mc.ls(sl=True,fl=True)
	
	# Get component selection
	compSel = mc.filterExpand(sm=(28,31,46))
	if compSel: mc.select(compSel,d=True)
	else: compSel = []
	
	# Get object selection
	objSel = mc.ls(sl=True)
	for obj in objSel:
		objType = mc.objectType(obj)
		if objType == 'transform':
			try:
				obj = mc.listRelatives(obj,s=True,ni=True)[0]
				objType = mc.objectType(obj)
			except: continue
		if not geometryList.count(objType): continue
		compSel.extend(glTools.utils.component.getComponentStrList(obj))
	
	if not compSel: return
	mc.select(compSel)
	objPath = OpenMaya.MDagPath()
	compObj = OpenMaya.MObject()
	objSel = OpenMaya.MSelectionList()
	OpenMaya.MGlobal.getActiveSelectionList(objSel)
	
	# Iterate through selection
	for i in range(objSel.length()):
		# Get geometry MDagPath and component MObject
		objSel.getDagPath(i,objPath,compObj)
		if compObj.isNull(): continue
		
		# Find related skinCluster
		skinCluster = findRelatedSkinCluster(objPath.partialPathName())
		skinClusterFn = getSkinClusterFn(skinCluster)
		
		# Get skinCluster influence count
		influenceArray = OpenMaya.MDagPathArray()
		influenceCount = skinClusterFn.influenceObjects(influenceArray)
		
		# Clear skinCluster weights to 0.0
		for i in range(influenceCount):
			skinClusterFn.setWeights(objPath,compObj,i,0.0,False)
Example #29
0
def getSingleIndexComponentList(componentList=[]):
	'''
	Convert a 2 or 3 value component index to a single value index.
	Returns a flat list of integer component index values.
	@param componentList: A list of component names. if empty will default to selection.
	@type componentList: list
	'''
	# Check Component List
	if not componentList: componentList = mc.ls(sl=True)
	if not componentList: return singleIndexList
	
	# Initialize Result
	singleIndexList = {}
	
	# Get Component Selection
	componentSel = getComponentIndexList(componentList)
	
	# Iterate Through Shape Keys
	shapeList = componentSel.keys()
	for shape in shapeList:
		
		# Get Shape Component Indices
		indexList = componentSel[shape]
		
		# Check Transform
		if mc.objectType(shape) == 'transform':
			shape = mc.listRelatives(shape,ni=True,pa=True)[0]
		
		# Check Mesh or Curve
		if (mc.objectType(shape) == 'mesh') or (mc.objectType(shape) == 'nurbsCurve'):
			singleIndexList[shape] = indexList
			
		# Check Surface
		elif mc.objectType(shape) == 'nurbsSurface':
			# Get nurbsSurface function set
			surfList = OpenMaya.MSelectionList()
			surfObj = OpenMaya.MObject()
			OpenMaya.MGlobal.getSelectionListByName(shape,surfList)
			surfList.getDependNode(0,surfObj)
			surfFn = OpenMaya.MFnNurbsSurface(surfObj)
			# CV count in V direction
			numV = surfFn.numCVsInV()
			# Check for periodic surface
			if surfFn.formInV() == surfFn.kPeriodic: numV -= surfFn.degreeV()
			singleIndexList[shape] = [(i[0]*numV)+i[1] for i in indexList]
			
		# Check Lattice
		elif (mc.objectType(shape) == 'lattice'):
			sDiv = mc.getAttr(shape+'.sDivisions')
			tDiv = mc.getAttr(shape+'.tDivisions')
			singleIndexList[shape] = [i[0]+(i[1]*sDiv)+(i[2]*sDiv*tDiv) for i in indexList]
	
	# Return Result
	return singleIndexList
Example #30
0
def __getConnectionCluster(*args):
    try:
        nodes = cmds.ls(sl=True)
        cluster = cmds.listConnections("%s.worldMatrix" %nodes[0],type="cluster")[0]
        mesh = cmds.listConnections("%s.outputGeometry" %cluster,s=False,d=True,type="mesh",sh=True)[0]
        if not cmds.objectType(cluster) == "cluster" or not cmds.objectType(mesh) == "mesh":
            raise
        return (cluster,mesh)
    except:
        om.MGlobal.displayError("Select ClusterHandle.")
        raise
    def print_selection_types(type):
        selection = cmds.ls(selection=True)
        type_list = []
        if type == "selection" and len(selection) > 0:
            for obj in selection:
                if cmds.objectType(obj) not in type_list:
                    type_list.append(cmds.objectType(obj))
                try: # Too handle elements without shapes
                    shape_node = cmds.listRelatives(obj, shapes=True, fullPath=True) or []
                except:
                    pass
                if shape_node != [] and cmds.objectType(shape_node[0]) not in type_list:
                    type_list.append(cmds.objectType(shape_node[0])+ " (Shape Node)") 

        if type == "all":
            #type_list = cmds.ls(nodeTypes=True) # Too see every type available
            everything_in_scene = cmds.ls()
            for obj in everything_in_scene:
                if cmds.objectType(obj) not in type_list:
                    type_list.append(cmds.objectType(obj))
                try: # Too handle elements without shapes
                    shape_node = cmds.listRelatives(obj, shapes=True, fullPath=True) or []
                except:
                    pass
                if shape_node != [] and cmds.objectType(shape_node[0]) not in type_list:
                    type_list.append(cmds.objectType(shape_node[0]) + " (Shape Node)")

        if type_list != []:
            print("#" * 80)
            print(" " * 30 + " Types:")
            for type in type_list:
                print(type)
            print("#" * 80)
            cmds.headsUpMessage( 'Open Script Editor to see the list of types', verticalOffset=150 , time=5.0)
        else:
            cmds.warning("Nothing selected (or no types to be displayed)")
Example #32
0
def LabelJoints(*args, **kwargs):

    sel = cmds.ls(sl=True)
    #
    if sel is None or len(sel) == 0:
        cmds.warning('Not executed, please check selected mesh')
        return

    mainSkin = [
        item for item in cmds.listHistory(sel[0])
        if cmds.objectType(item, isType='skinCluster')
    ][0]
    jntList = [itm for itm in cmds.skinCluster(mainSkin, q=1, inf=1)]

    tempJDict = helpersMain.match_strings(jntList, filter='_L_', replace='_R_')
    helpersMain.rename_sibilings(tempJDict)

    jntList = [itm for itm in cmds.skinCluster(mainSkin, q=1, inf=1)]

    if any([itm for itm in jntList if ':' in itm]):
        jntList = [itm.split(':')[-1] for itm in jntList]

    for jnt in jntList:
        prefix = jnt.split('_')[0]
        cmds.setAttr(jnt + '.type', 18)
        cmds.setAttr(jnt + '.otherType', prefix, type='string')

        if '_L_' in jnt:
            cmds.setAttr(jnt + '.side', 1)

        elif '_R_' in jnt:
            cmds.setAttr(jnt + '.side', 2)

        else:
            cmds.setAttr(jnt + '.side', 0)

    #
    om.MGlobal.displayInfo("Labeling Done")
Example #33
0
def smartRenameIt(name='ob', suffix='GP'):
    import maya.cmds as cmd
    parent = []
    num = 0
    index = ''
    obLib = {
        'transform': 'GEO',
        'nurbsCurve': 'CTL',
        'joint': 'JNT',
        'clusterHandle': 'CLR',
        'locator': 'LOC',
        'ikHandle': 'IK',
        'aimConstraint': 'amC',
        'pointConstraint': 'ptC',
        'orientConstraint': 'orC',
        'parentConstraint': 'paC',
        'mesh': 'GEO'
    }

    obs = cmd.ls(sl=True)
    for one in obs:
        num += 1
        index = '%02d' % num
        objectType = cmd.objectType(one)
        type = obLib[objectType]
        if type == 'JNT' and one == obs[-1]:
            prnt = cmd.listRelatives(obs[-1], p=True)
            try:
                if prnt[0] == obs[-2]:
                    index = 'end'
            except:
                pass
        if type == 'GEO':
            child = cmd.listRelatives(one, s=True)
            if child is None:
                type = 'GP'
        newName = '%s_%s_%s' % (name, index, type)
        cmd.rename(one, newName)
Example #34
0
def get_shape(path):
    """
    For a given node path, get its Dag object.
    Does validation against the scene.
    """
    nodes = mc.ls(path, long=True)

    # Make sure our given path is unique
    if not nodes:
        raise RuntimeError("No node matches name: %s" % (path))
    if len(nodes) > 1:
        raise RuntimeError("More than one node has name: %s" % (path))

    path = nodes[0]

    # Check if we're actually given a mesh.
    if mc.objectType(path) != 'mesh':
        shapes = mc.listRelatives(path,
                                  shapes=True,
                                  children=True,
                                  type="mesh",
                                  fullPath=True)
        if not shapes:
            raise RuntimeError("There are no shapes under %s" % (path))

        if len(shapes) > 1:
            raise RuntimeError("There is more than one shape under %s" %
                               (path))

        # logger.debug("%s is not a mesh. Using %s", node, shapes[0])
        path = shapes[0]

    # Finally convert to a dag object
    sel = om.MSelectionList()
    sel.add(path)
    dag = sel.getDagPath(0)

    return dag
Example #35
0
    def assertConstrained(self, parent=None, child=None, type=None):
        ''' 
        Check if child is constrained to parent in Maya scene. 
        
        parent -- Parent transform in scene.
        child -- Child transform in scene.
        type -- parent|point|orient|scale|aim|geometry
        '''
        if self.logger:
            self.logger.info('assertConstrained(): Start...')

        const = None
        cons = cmds.listConnections(child)

        if not cons:
            if self.logger:
                self.logger.error('%s not %s constrained to %s' %
                                  (child, type, parent))
            raise AssertionError('%s not %s constrained to %s' %
                                 (child, type, parent))

        for each in cons:
            if cmds.objectType(each) == type + 'Constraint':
                const = each
                break

        cons = cmds.listConnections(const)
        for each in cons:
            if each == parent:
                if self.logger:
                    self.logger.info('assertConstrained(): End.')
                return True

        if self.logger:
            self.logger.error('%s not %s constrained to %s' %
                              (child, type, parent))
        raise AssertionError('%s not %s constrained to %s' %
                             (child, type, parent))
Example #36
0
def snapToCurve(curve,obj,uValue=0.0,useClosestPoint=False,snapPivot=False):
	'''
	Snap an object (or transform pivot) to a specified point on a curve.
	@param curve: Curve to snap to
	@type curve: str
	@param obj: Object to move to point on curve
	@type obj: str
	@param uValue: Paramater value of the curve to snap to
	@type uValue: float
	@param useClosestPoint: Use the closest point on the curve instead of the specified uv parameter
	@type useClosestPoint: bool
	@param snapPivot: Move only the objects pivot to the curve point
	@type snapPivot: bool
	'''
	# Check curve
	if not isCurve(curve): raise Exception('Object '+curve+' is not a valid curve!!')
	# Check uValue
	minu = mc.getAttr(curve+'.minValue')
	maxu = mc.getAttr(curve+'.maxValue')
	# Closest Point
	if useClosestPoint:
		pos = glTools.utils.base.getPosition(obj)
		uValue = closestPoint(curve,pos)
	# Verify surface parameter
	if uValue < minu or uValue > maxu:
		raise Exception('U paramater '+str(uValue)+' is not within the parameter range for '+curve+'!!')
	
	# Get curve point position
	pnt = mc.pointPosition(curve+'.u['+str(uValue)+']')
	
	# Snap to Curve
	piv = mc.xform(obj,q=True,ws=True,rp=True)
	if snapPivot: mc.xform(obj,piv=pnt,ws=True)
	else:
		if mc.objectType(obj) == 'transform':
			mc.move(pnt[0]-piv[0],pnt[1]-piv[1],pnt[2]-piv[2],obj,r=True,ws=True)
		else:
			mc.move(pnt[0],pnt[1],pnt[2],obj,ws=True,a=True)
Example #37
0
def get_current_camera():
    """Returns the currently active camera.
    Searched in the order of:
        1. Active Panel
        2. Selected Camera Shape
        3. Selected Camera Transform
    Returns:
        str: name of active camera transform
    """

    # Get camera from active modelPanel  (if any)
    panel = cmds.getPanel(withFocus=True)
    if cmds.getPanel(typeOf=panel) == "modelPanel":
        cam = cmds.modelEditor(panel, query=True, camera=True)
        # In some cases above returns the shape, but most often it returns the
        # transform. Still we need to make sure we return the transform.
        if cam:
            if cmds.nodeType(cam) == "transform":
                return cam
            # camera shape is a shape type
            elif cmds.objectType(cam, isAType="shape"):
                parent = cmds.listRelatives(cam, parent=True, fullPath=True)
                if parent:
                    return parent[0]

    # Check if a camShape is selected (if so use that)
    cam_shapes = cmds.ls(selection=True, type="camera")
    if cam_shapes:
        return cmds.listRelatives(cam_shapes, parent=True, fullPath=True)[0]

    # Check if a transform of a camShape is selected
    # (return cam transform if any)
    transforms = cmds.ls(selection=True, type="transform")
    if transforms:
        cam_shapes = cmds.listRelatives(transforms, shapes=True, type="camera")
        if cam_shapes:
            return cmds.listRelatives(cam_shapes, parent=True,
                                      fullPath=True)[0]
Example #38
0
def setNotRenderable(objList):
    """Receive a list of objects, find its shapes if necessary and set all as not renderable.
    """
    # declare a list of attributes for render:
    renderAttrList = [
        "castsShadows", "receiveShadows", "motionBlur", "primaryVisibility",
        "smoothShading", "visibleInReflections", "visibleInRefractions",
        "doubleSided", "miTransparencyCast", "miTransparencyReceive",
        "miReflectionReceive", "miRefractionReceive", "miFinalGatherCast",
        "miFinalGatherReceive"
    ]
    shapeTypeList = ['nurbsCurve', 'nurbsSurface', 'mesh', 'subdiv']
    # find all children shapes:
    if objList:
        for obj in objList:
            objType = cmds.objectType(obj)
            # verify if the object is the shape type:
            if objType in shapeTypeList:
                # set attributes as not renderable:
                for attr in renderAttrList:
                    try:
                        cmds.setAttr(obj + "." + attr, 0)
                    except:
                        #print "Error: Cannot set not renderable ", attr, "as zero for", obj
                        pass
            # verify if the object is a transform type:
            elif objType == "transform":
                # find all shapes children of the transform object:
                shapeList = cmds.listRelatives(obj, shapes=True, children=True)
                if shapeList:
                    for shape in shapeList:
                        # set attributes as not renderable:
                        for attr in renderAttrList:
                            try:
                                cmds.setAttr(shape + "." + attr, 0)
                            except:
                                #print "Error: Cannot set not renderable ", attr, "as zero for", shape
                                pass
Example #39
0
def orientTo():
    """Match specified joint orientation to a target transform.

    Select one source joint and one or more target joints.

    Args:
        None
    Returns:
        None.
    Raises:
        Logs warning if less than 2 objects are selected.
        Logs warning if selections contain non-joint type.
    """
    sel = cmds.ls(sl=1)
    if len(sel) < 2:
        LOG.warning(
            'Please select one source joint and one or more target joints.')
        return

    for jnt in sel:
        if not cmds.objectType(jnt, isType="joint"):
            LOG.warning('Please select joints only.')

    for i in xrange(1, len(sel)):
        # Find unparent children
        children = cmds.listRelatives(sel[i], children=1, type='transform')
        if children and (len(children) > 0):
            # Unparent and get names of the objects(possibly renamed)
            children = cmds.parent(children, w=1)

        oCons = cmds.orientConstraint(sel[0], sel[i])
        cmds.delete(oCons)

        cmds.joint(sel[i], edit=True, zso=1)
        cmds.makeIdentity(sel[i], apply=1, r=True)

        if children and (len(children) > 0):
            cmds.parent(children, sel[i])
Example #40
0
    def Vertex_Inst(self):
        random.seed(1998)
        result = cmds.ls(orderedSelection=True)
        vertex_name = cmds.filterExpand(expand=True, selectionMask=25)
        inst_obj = result[0]
        instance_group_name = cmds.group(empty=True,
                                         name=inst_obj + '_instance_grp#')
        cmds.xform(instance_group_name, centerPivots=True)
        if cmds.objectType(inst_obj) == 'transform':
            for vertex in vertex_name:
                instance_result = cmds.instance(inst_obj,
                                                name=inst_obj + '_instance#')

                cmds.parent(instance_result, instance_group_name)
                self.rnd_rotation(instance_result)
                self.rnd_scaling(instance_result)
                x_ver, y_ver, z_ver = cmds.pointPosition(vertex)
                cmds.move(x_ver, y_ver, z_ver)

        else:
            print("Oops")

        cmds.hide(inst_obj)
Example #41
0
def extractCtlShapes(topnode):
    """Extract all ctl shapes
    """
    name = topnode
    allNodes = cmds.listRelatives(topnode, ad=True, f=True)
    ctlShapeList = []
    for node in allNodes:
        if cmds.objectType(node) == "nurbsCurve":
            ctlShapeList = ctlShapeList + [node]

    cmds.select(cl=True)
    ctlSet = cmds.sets(n="{0}CtlShapes_set".format(name))
    ctlGroup = cmds.group(n="{0}CtlShapes_grp".format(name), w=True, em=True)

    for ctlShape in ctlShapeList:
        if "ctl" in ctlShape.split("|")[-1]:
            shape = cmds.instance(ctlShape)
            dupe = cmds.duplicate(shape,
                                  n=ctlShape.split("|")[-1].replace(
                                      "_ctl", "Extracted_ctl"))[0]
            cmds.delete(shape)
            cmds.parent(dupe, ctlGroup)
            cmds.sets(dupe, add=ctlSet)
Example #42
0
def getWeights(deformer,geometry=''):
	'''
	Get the weights for the specified deformer. Weights returned as a python list object
	@param deformer: Deformer to get weights for
	@type deformer: str
	@param geometry: Target geometry to get weights from
	@type geometry: str
	'''
	# Get geoShape
	geoShape = geometry
	if geometry and mc.objectType(geoShape) == 'transform':
		geoShape = mc.listRelatives(geometry,s=True,ni=True)[0]
	
	# Get deformer function set and members
	deformerFn = getDeformerFn(deformer)
	deformerSetMem = getDeformerSetMembers(deformer,geoShape)
	
	# Get weights
	weightList = OpenMaya.MFloatArray()
	deformerFn.getWeights(deformerSetMem[0],deformerSetMem[1],weightList)
	
	# Return result
	return list(weightList)
Example #43
0
def getAffectedJoints(ikh):
    ''' Get a list of joints affected by a specified ikHandle
    :param ikh str: IK Handle to query affected joints for
    '''
    # Check ikHandle
    if not cmds.objExists(ikh): raise Exception('IK handle {0} does not exist!'.format(ikh))
    if cmds.objectType(ikh) != 'ikHandle': raise Exception('Object {0} is not a valid ikHandle!'.format(ikh))
    
    # Get startJoint
    startJoint = cmds.listConnections(ikh+'.startJoint',s=True,d=False)[0]
    # Get endEffector
    endEffector = cmds.listConnections(ikh+'.endEffector',s=True,d=False)[0]
    endJoint = cmds.listConnections(endEffector+'.translateX',s=True,d=False)[0]
    
    # Get list of joints affected by ikHandle
    ikJoints = [endJoint]
    while ikJoints[-1] != startJoint:
        ikJoints.append(cmds.listRelatives(ikJoints[-1],p=True)[0])
    # Reverse joint list
    ikJoints.reverse()
    
    # Return ik joints list
    return ikJoints
Example #44
0
def addNewRigToSet( newRigRoot, currentRigRootOrCameraSet, objectSet=None ): 
	"""
	This is the main function for adding cameras/rigs to a camera
	set. Given a valid stereo rig, add that rig to the specified
	camera set. The second argument to this function can either be the
	existing rig root that we are layering or the current camera set.
	
	If it is the camera set then simply append the newRigRoot to the
	camera set. If it is a rig then create a new camera set attach
	the current rig to the set and then append the newRigRoot to
	that set.

	We return the camera set on exit. 
	"""
	cameraSet = None
	if currentRigRootOrCameraSet:
		if cmds.objectType( currentRigRootOrCameraSet, isa="cameraSet" ):
			cameraSet = currentRigRootOrCameraSet
		else:
			cameraSet = cmds.createNode( 'cameraSet' )
			__attachToCameraSet( currentRigRootOrCameraSet, cameraSet, objectSet )
	__attachToCameraSet( newRigRoot, cameraSet, objectSet )
	return cameraSet 
Example #45
0
	def cleanupShaderAssign(self) :
		initial = cmds.ls(sl=True)
		cmds.select(cl=True)
		shaders = self.getShaders()
		variations = {}
		supported = ['lambert', 'phong', 'blinn']
		for s in shaders :
			if not cmds.objectType(s) in supported :
				continue
			col = tuple(cmds.getAttr(s+'.color'))
			if col not in variations.keys() :
				variations[col] = s
		for v in variations :
			print('%s: %s' % (variations[v],str(v)))
		for s in shaders :
			if s not in variations.keys() :
				col = tuple(cmds.getAttr(s+'.color'))
				engine = cmds.listConnections(s, type='shadingEngine')[0]
				cmds.select(engine)
				cmds.hyperShade(assign=variations[col])
				print('%s -> %s' % (s,variations[col]))
		if len(initial) > 0 :
			cmds.select(initial)
Example #46
0
def action_SaveWeights(savePath=''):
    savePath = ''
    selectionList = mc.ls(sl=True, objectsOnly=True)
    if not savePath:
        savePath = dirPath()
    for obj in selectionList:
        if mc.objectType(obj, isType="transform"):
            mc.select(obj)
            xmlName = str(obj) + ".xml"
            try:
                mesh = mc.ls(sl=True, objectsOnly=True)
                meshSkinCluster = str(
                    mc.ls(mc.listHistory(mesh), type='skinCluster')[0])
                mc.deformerWeights(xmlName,
                                   ex=True,
                                   path=savePath,
                                   deformer=meshSkinCluster)
            except:
                e = sys.exc_info()[1]
                print "Skipping mesh: {obj}: ".format(obj=obj) + str(e)
    print "----------------------------------------"
    print savePath.replace("/", "\\")
    return savePath
Example #47
0
    def Generate(cls, nodes):
        originalRange = getPlaybackRange()
        keyTimeDataDict = {}

        nodesWithKeys = set()

        attrs = cls._ATTRS
        keyServer = NodeKeyServer(nodes, attrs=attrs)
        for keyTime in keyServer:
            nodesAtTime = keyServer.getNodes()
            keyTimeDataDict[keyTime] = nodeDataDict = {}
            for node in nodesAtTime:
                nodesWithKeys.add(node)

                #skip non-transform nodes...  duh
                if not cmd.objectType(node, isAType='transform'):
                    continue

                pos = xform(node, q=True, ws=True, rp=True)
                rot = xform(node, q=True, ws=True, ro=True)
                nodeDataDict[node] = pos, rot, getAttr('%s.ro' % node)

        return cls(keyTimeDataDict, originalRange)
Example #48
0
 def editCmd(self):
     """"""
     self.influence = sel = self.__selectInfluence()
     
     if cmds.objectType( self.influence, isType='joint' ):
         self._type =  'joint'
         deformers = cmds.listConnections('%s.wm' % self.influence, d=1, s=0, t='skinCluster', et=1)
         
     elif cmds.listRelatives(self.influence, s=1, typ='clusterHandle'):
         self._type =  'cluster'
         deformers = cmds.listConnections('%s.wm' % self.influence, d=1, s=0, t='cluster', et=1)
     else: cmds.error("%s is unsupported type!" % self.influence)
     
     try:
         infObjs = cmds.listConnections('%s.og' % deformers[0])
         cmds.select(infObjs)
     except TypeError:
         cmds.error("Can't find geometry deformed by %s" % self.influence)
     
     # Get into component select mode
     cmds.selectMode( object=True )
     cmds.selectMode( component=True )
     self.toggleButton()
 def bakeJoints(self, *args, **kwargs):
     #build joint list with children of Flat Jnt Grp        
     jnts=[]
     if mc.objExists(self.jntGrp):
         for i in mc.listRelatives(self.jntGrp, ad=1):
             if mc.objectType(i)=="joint":
                 jnts.append(i)
     else:
         mc.error("There is no 'FLAT_JNT_Grp' in this scene.")
     
     #make all joints keyable
     for j in jnts:
         attr=["t","r","s"]
         co=["x","y","z"]
         attrLs=[]
         for at in attr:
             for c in co:
                 attrLs.append("%s.%s%s"%(j,at,c))
         for x in attrLs:
             try:
                 mc.setAttr(x, k=1)
             except:
                 pass
Example #50
0
    def __init__(self, maya_light):
        '''
        initialize instance variables
        '''
        # gather basics across all light types and determine how to deal with
        #   specifics, whether related to type or even attributes
        if not mc.objectType(maya_light, isAType='light'):
            print '%s is not a light.' % maya_light
            return

        self.__shape = maya_light
        self.__use_shadows = mc.getAttr("%s.useDepthMapShadows" % self.__shape)
        self._name = ''
        self._path = ''
        self._position = {}  # x,y,z
        self._rotation = {}  # x,y,z
        self._scale = {}  # x,y,z
        self._type = ''
        self._color = {}  # r,g,b
        self._intensity = '0.0'
        self._shadows = 'No'

        self._get_light_details()
Example #51
0
def geometryType(geometry):
    """
    Return the geometry type of the first shape under the specified geometry object
    @param geometry: The geometry object to query
    @type geometry: str
    """
    # Check Geometry
    if not cmds.objExists(geometry):
        raise Exception('Geometry object "' + geometry + '" does not exist!!')

    # Get Shapes
    shapeList = glTools.utils.shape.getShapes(geometry, intermediates=False)
    if not shapeList:
        shapeList = glTools.utils.shape.getShapes(geometry, intermediates=True)
    if not shapeList:
        raise Exception('Geometry object "' + geometry +
                        '" has no shape children!!')

    # Get Geometry Type
    geometryType = cmds.objectType(shapeList[0])

    # Return Result
    return geometryType
Example #52
0
def getMaterialsFromSelectedObjects(*args):
    selected = mc.ls(sl=1)
    shapes = mc.ls(selected, dag=1, s=1)
    allInputNodes = []
    if shapes == []:
        pass
    else:
        for shape in shapes:

            sg = mc.listConnections(shape, type='shadingEngine')

            if sg is not None:
                inputNodes = mc.listConnections(sg, s=1, d=0)
                for inputNode in inputNodes:
                    allInputNodes.append(inputNode)

        materials = mc.ls(allInputNodes, materials=1)
        materials = [
            material for material in materials
            if mc.objectType(material) != 'displacementShader'
        ]
        materials = list(set(materials))
        return materials
Example #53
0
def DeleteLastFrame(self):
    #Delete second to last frame, keep the ghost frame leading.
    goodIndex = len(g_animationFrames) - 1
    res = cmds.confirmDialog( title='Delete Frame', message='About to delete frame: %d' % goodIndex, button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )

    if res == 'No':
        return
    #Removing the model data
    g_animationFrames.remove(g_animationFrames[goodIndex])
    newNumberOfFrames = len(g_animationFrames) - 1

    #Deleting the transform of the boxes
    allObjects = cmds.ls()
    lastFramesBoxes = []

    for obj in allObjects:
        if '_%d_' % (goodIndex) in obj and cmds.objectType(obj) == 'transform':
            lastFramesBoxes.append(obj)
    for box in lastFramesBoxes:
        cmds.delete(box)

    #Changing end number of the Animation GUI
    cmds.textField(g_endingAnimationFrameNumber, e = True, text = newNumberOfFrames)
Example #54
0
def shapeInputAttr(shape):
	'''
	Return the shape input attribute.
	@param shape: The shape node to find the shape input attribute for.
	@type shape: str
	'''
	# Check Shape
	if not isShape(shape):
		raise Exception('Object "'+shape+'" is not a valid shape node!')

	# Determine Shape Input Plug
	shapeInputAttr = ''
	shapeInputType = mc.objectType(shape)
	shapeInputDict = {	'mesh':'inMesh',
						'nurbsCurve':'create',
						'nurbsSurface':'create'	}
	if shapeInputDict.has_key(shapeInputType):
		shapeInputAttr = shapeInputDict[shapeInputType]
	else:
		raise Exception('Unsupported shape type! ('+shapeInputType+')')

	# Return Result
	return shapeInputAttr
 def doFindReplace( self, param ):
   if self.strToFind != '' :
     print ( ">> self.strToFind = %s self.strToReplace = %s" ) % (self.strToFind, self.strToReplace)
     
     for i in range( len( self.fileTextures ) ):  
       fileNodeName = self.fileTextures[ i ]
       fileNodeType = cmds.objectType( fileNodeName )
       
       if fileNodeType == 'file' or fileNodeType == 'mentalrayTexture' : attrName = "fileTextureName" 
       elif fileNodeType == 'imagePlane' : attrName = "imageName" 
       else: continue  
       
       fileTextureName = cmds.getAttr( fileNodeName + "." + attrName )
       
       if fileTextureName is None : fileName = ''
       else: fileName = str( fileTextureName )
       newName = str( fileName ).replace( str( self.strToFind ), str( self.strToReplace ), 1 )
       if newName != fileName :
         # print fileNodeName + "." + attrName
         # ??? It is strange, but folder renaming doesn't work wor ImagePlane's "imageName" attribute... 
         cmds.setAttr( fileNodeName + "." + attrName, newName, type="string" )
         print ">> fileName = %s new = %s" % ( fileName, newName )
     self.refreshUI( True )
Example #56
0
def findMeshWithBlendShapes(nameSpace):
    """
    Purpose:        return the meshes connected to blend_shape node
    Procedure:      get a list of blend_shape node,
                    follow those connections to the mesh shape node
                    traverse up the hierarchy to find parent transform node
    Presumption:    character has a valid namespace
    :param nameSpace: all the blendShapes nodes
    :return:        a list of all the meshes with blendShape
    """

    returnArray = []

    blendshapes = cmds.ls((nameSpace + ':*'), type='blendShape')

    for curBlendShape in blendshapes:
        downStreamNodes = cmds.listHistory(curBlendShape, future=1)
        for curNode in downStreamNodes:
            if cmds.objectType(curNode, isType='mesh'):
                parents = cmds.listRelatives(curNode, parent=1)
                returnArray.append(parents[0])

    return returnArray
Example #57
0
def findRelatedSkinCluster(geometry):
	'''
	Return the skinCluster attached to the specified geometry
	@param geometry: Geometry object/transform to query
	@type geometry: str
	'''
	# Check geometry
	if not mc.objExists(geometry):
		raise Exception('Object '+geometry+' does not exist!')
	# Check transform
	if mc.objectType(geometry) == 'transform':
		try: geometry = mc.listRelatives(geometry,s=True,ni=True,pa=True)[0]
		except: raise Exception('Object '+geometry+' has no deformable geometry!')
	
	# Determine skinCluster
	skin = mm.eval('findRelatedSkinCluster "'+geometry+'"')
	if not skin: 
		skin = mc.ls(mc.listHistory(geometry),type='skinCluster')
		if skin: skin = skin[0]
	if not skin: skin = ''
	
	# Return result
	return skin
Example #58
0
def isFollicle(follicle):
    """
    Test if node is a valid follicle
    @param follicle: Name of follicle to query
    @type follicle: str
    """
    # Check Object Exists
    if not cmds.objExists(follicle):
        return False

    # Check Shape
    if 'transform' in cmds.nodeType(follicle, i=True):
        follicleShape = cmds.ls(
            cmds.listRelatives(follicle, s=True, ni=True, pa=True) or [],
            type='follicle')
        if not follicleShape: return False
        follicle = follicleShape[0]

    # Check Follicle
    if cmds.objectType(follicle) != 'follicle': return False

    # Return Result
    return True
Example #59
0
 def deleteSkeleton(self):
     intermediateShapes = []
     attachedGeo = []
     for geo in self.geometryData:
         if not geo.skinnable():
             if geo.attached():
                 attachedGeo.append(geo)
             continue
         history = mc.listHistory(geo.shapeName())
         for node in history:
             if mc.objectType(node, isAType="shape"):
                 if mc.getAttr("%s.intermediateObject" % node):
                     intermediateShapes.append(node)
     mc.delete(self.skelGroup)
     mc.delete(intermediateShapes)
     self.skelGroup = ""
     self.rootJoint = None
     self.joints = {}
     self.primitiveData = []
     # Attached geometry has been deleted with the skeleton
     #
     for geo in attachedGeo:
         self.geometryData.remove(geo)
Example #60
0
def targetList(constraint):
    '''
	Return a list of targets (drivers) for the specified constraint node
	@param constraint: The constraint node whose targets will be returned
	@type constraint: str
	'''
    # Check Constraint
    if not isConstraint(constraint):
        raise Exception('Constraint "' + constraint + '" does not exist!!')

    # Get Target List
    targetList = []
    constraintType = mc.objectType(constraint)
    if constraintType == 'aimConstraint':
        targetList = mc.aimConstraint(constraint, q=True, tl=True)
    elif constraintType == 'geometryConstraint':
        targetList = mc.geometryConstraint(constraint, q=True, tl=True)
    elif constraintType == 'normalConstraint':
        targetList = mc.normalConstraint(constraint, q=True, tl=True)
    elif constraintType == 'orientConstraint':
        targetList = mc.orientConstraint(constraint, q=True, tl=True)
    elif constraintType == 'parentConstraint':
        targetList = mc.parentConstraint(constraint, q=True, tl=True)
    elif constraintType == 'pointConstraint':
        targetList = mc.pointConstraint(constraint, q=True, tl=True)
    elif constraintType == 'poleVectorConstraint':
        targetList = mc.poleVectorConstraint(constraint, q=True, tl=True)
    elif constraintType == 'scaleConstraint':
        targetList = mc.scaleConstraint(constraint, q=True, tl=True)
    elif constraintType == 'tangentConstraint':
        targetList = mc.tangentConstraint(constraint, q=True, tl=True)

    # Check Target List
    if not targetList: targetList = []

    # Return Result
    return targetList