예제 #1
0
def rmvGeoLayer(*args):
    '''
    Remove selected geometry or geometries from 'geo_layer'.
    '''

    selList = cmds.ls(sl=True)
    cmds.editDisplayLayerMembers('defaultLayer', selList)
예제 #2
0
def intoDfltDisLyr(*args):
    '''
    Move selected geometry into 'defaultDisplayLayer'.
    '''

    selList = cmds.ls(sl = True)
    cmds.editDisplayLayerMembers('defaultLayer', selList)
예제 #3
0
def addGeoLayer(*args):
    '''
    Add selected geometry or geometries to the geo_layer.
    '''

    selList = cmds.ls(sl=True)

    if not cmds.objExists('geo_layer'):
        geoLayer = cmds.createNode('displayLayer', n='geo_layer')

    if selList:
        cmds.editDisplayLayerMembers('geo_layer', selList)
    else:
        cmds.select(cl=True)
        if cmds.objExists('lod01_GRP'):
            cmds.select('lod01_GRP', add=True, hi=True)
        if cmds.objExists('lod02_GRP'):
            cmds.select('lod02_GRP', add=True, hi=True)
        if cmds.objExists('lod03_GRP'):
            cmds.select('lod03_GRP', add=True, hi=True)
        if cmds.objExists('floorContactCheck_geo'):
            cmds.select('floorContactCheck_geo', add=True)

        selList = cmds.ls(sl=True)
        cmds.editDisplayLayerMembers('geo_layer', selList)
def tf_makeSphere(width, subdivs, parent, child, prefix, suffix ):       
    
    dummyBase = '%s' % (parent + child+ '_joint')
    dummyName = tf_dummyString(dummyBase, prefix, suffix)
    
    # create the cube
    
    createSphere = cmds.polySphere( r=width, ch=False, sx= 20, sy= 20, n= dummyName )
    
    
    cmds.editDisplayLayerMembers ( 'DummyLayer', createSphere)  
    
    # move cube to parent
    pointCon = cmds.pointConstraint( parent, createSphere[0] )
    
    # delete constraint once cube is in position
    cmds.delete( pointCon )
    
    # create the aim constraint
    #aimCon = cmds.aimConstraint( child, createSphere[0], aim=[0,0,1], u=[0,0,1] )
    
    # delete constraint once cube is aimed at child
    #cmds.delete( aimCon )
    
    #parent cube under the parent joint
    cmds.parent( createSphere[0], parent )
    
    # freeze transforms
    cmds.makeIdentity( createSphere[0], apply=True )
예제 #5
0
def referenceCreateDisplayLayer(referenceList): 
    #根据参考创建对应的显示层
    for reference in referenceList:
        referenceRelativesNodes = cmds.referenceQuery(reference,nodes=True)
        referenceNamespace = cmds.referenceQuery(reference,namespace=True,showNamespace=True)
        transformNodes = referenceNodeTypeFilter(referenceRelativesNodes,'transform')
        referenceDisplayLayer = cmds.createDisplayLayer(e=True,n=referenceNamespace+'_View')
        cmds.editDisplayLayerMembers(referenceDisplayLayer,transformNodes)
예제 #6
0
def main():
    """docstring for main"""

    my_sel = cmds.ls(sl=True)
    layer_sel = cmds.ls(type='displayLayer')
    for i in layer_sel:
        print i
    cmds.editDisplayLayerMembers('displayLayer1', my_sel)
예제 #7
0
 def makePairs(self):
     sel = cmds.ls(os=1)
     garments = cmds.listRelatives(sel[0])  # len(garments)
     patterns = cmds.listRelatives(sel[1])  # len(patterns)
     retopos = cmds.listRelatives(sel[2])  # len(retopos)
     retopos_BB_width = {}
     retopos_BB_length = {}
     retopos_BB_center = {}
     patterns_BB_width = {}
     patterns_BB_length = {}
     patterns_BB_center = {}
     # In case that uv doesn't exists.
     cmds.select(retopos, r=1)
     mel.eval("performPolyAutoProj 0;")
     cmds.select(sel, r=1)
     # In case wrong bb
     for i in retopos:
         cmds.polyMergeVertex(i, d=0.001)
     # Matching
     for i in retopos:
         BB = cmds.polyEvaluate(i, b=1)
         retopos_BB_width[i] = BB[0][1] - BB[0][0]
         retopos_BB_length[i] = BB[1][1] - BB[1][0]
         retopos_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                 (BB[1][1] + BB[1][0]) / 2]
     for i in patterns:
         BB = cmds.polyEvaluate(i, b=1)
         patterns_BB_width[i] = BB[0][1] - BB[0][0]
         patterns_BB_length[i] = BB[1][1] - BB[1][0]
         patterns_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                  (BB[1][1] + BB[1][0]) / 2]
     pair_pattern_retopo = {}  # len(pair_pattern_retopo)
     for i in patterns:
         for j in retopos:
             if      abs(patterns_BB_width[i] - retopos_BB_width[j])         < 1 \
                 and abs(patterns_BB_length[i] - retopos_BB_length[j])       < 1 \
                 and abs(patterns_BB_center[i][0] - retopos_BB_center[j][0]) < 1 \
                 and abs(patterns_BB_center[i][1] - retopos_BB_center[j][1]) < 1:
                 pair_pattern_retopo[i] = j
     for i in pair_pattern_retopo:
         cmds.transferAttributes(i, pair_pattern_retopo[i], transferUVs=1)
     for i in pair_pattern_retopo:
         cmds.select(pair_pattern_retopo[i], i, r=1)
         cmds.CreateWrap()
     for i in pair_pattern_retopo:
         pairGarment = i[:-8]
         pattern = i
         blendObjs = [pairGarment, pattern]  # 0: target 1: origin
         blendName = cmds.blendShape(blendObjs,
                                     o='world',
                                     n='clothTransfer#')
         cmds.hide(sel[1])
         cmds.displaySurface(sel[0], x=1)
     cmds.hide(sel[1])
     cmds.displaySurface(sel[0], x=1)
     layerName = cmds.createDisplayLayer(n="garment#", e=1)
     cmds.editDisplayLayerMembers(layerName, sel[0])
     cmds.setAttr(layerName + '.displayType', 2)
예제 #8
0
 def clear(self):
     # type: () -> NoReturn
     nodes = _cmds.editDisplayLayerMembers(self.mel_object,
                                           query=True,
                                           fullNames=True)
     if nodes is not None:
         _cmds.editDisplayLayerMembers('defaultLayer',
                                       nodes,
                                       noRecurse=True)
def createLayer(objs=[], layerName=''):
    if layerName:
        if cmds.objExists(layerName) and cmds.nodeType(
                layerName) == 'displayLayer':
            ly = cmds.editDisplayLayerMembers(
                layerName, objs)  # store my selection into the display layer
        else:
            cmds.createDisplayLayer(name=layerName, number=1, empty=True)
            ly = cmds.editDisplayLayerMembers(layerName, objs)
        return ly
예제 #10
0
def addToLayer(_data, _layer, _objects):
    assert isinstance(_data, sd.SceneData), "_data must be SceneData object"
    assert type(_layer) == type("") or type(_objects) == type(u''), "_layer must be a string"
    if type(_objects) == type([]):
        for obj in _objects:
            assert type(obj) == type("")  or type(obj) == type(u''), "All objects must be strings"
            cmds.editDisplayLayerMembers(_data.getLayer(_layer), obj)
    else:
        assert type(_objects) == type("") or type(_objects) == type(u''), "_objects must be a string"
        cmds.editDisplayLayerMembers(_data.getLayer(_layer), _objects)
예제 #11
0
 def addtolow(self):
     Name = cmds.ls(sl=1, o=1)
     cmds.editDisplayLayerMembers('Low_Poly', Name, noRecurse=True)
     Name = cmds.ls(sl=1, o=1)
     Selected = Name[0]
     if Selected in List_Low:
         om.MGlobal.displayInfo("Already in List")
     else:
         List_Low.append(Selected)
         om.MGlobal.displayInfo("Added to List.")
예제 #12
0
	def extractWithDeltaConnection(self, shape, delta, value, live=True, offset=10.0):
		""" Extract a shape with a live partial delta added in.
			Useful for updating progressive shapes
		"""
		with disconnected(self.shapeNode):
			for attr in cmds.listAttr("{0}.weight[*]".format(self.shapeNode)):
				cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)

			# Pull out the rest shape. we will blend this guy to the extraction
			extracted = cmds.duplicate(self.mesh, name="{0}_Extract".format(shape.name))[0]
			cmds.editDisplayLayerMembers("defaultLayer", extracted, noRecurse=True)

			cmds.setAttr(shape.thing, 1.0)
			# Store the initial shape
			init = cmds.duplicate(self.mesh, name="{0}_Init".format(shape.name))[0]

		# clear old orig objects
		for item in [init, extracted]:
			self._clearShapes(item, doOrig=True)

		deltaPar = cmds.listRelatives(delta, parent=True)[0]
		idx = 1

		# build the restObj system
		cmds.select(clear=True) # 'cause maya
		bs = cmds.blendShape(extracted, name="{0}_DeltaBS".format(shape.name))[0]
		cmds.blendShape(bs, edit=True, target=(extracted, 0, init, 1.0))
		cmds.blendShape(bs, edit=True, target=(extracted, 1, deltaPar, 1.0))

		cmds.setAttr("{0}.{1}".format(bs, init), 1.0)
		cmds.setAttr("{0}.{1}".format(bs, deltaPar), value)

		outCnx = '{0}.worldMesh[0]'.format(delta)
		inCnx = '{0}.inputTarget[0].inputTargetGroup[{1}].inputTargetItem[6000].inputGeomTarget'.format(bs, 1)
		cmds.connectAttr(outCnx, inCnx, force=True)
		cmds.aliasAttr(delta, '{0}.{1}'.format(bs, deltaPar))

		# Cleanup
		nodeDict = dict(Init=init)
		repDict = self._reparentDeltaShapes(extracted, nodeDict, bs)

		# Remove the tweak node, otherwise editing the input progressives
		# *inverts* the shape
		exShape = cmds.listRelatives(extracted, noIntermediate=1, shapes=1)[0]
		tweak = cmds.listConnections(exShape+'.tweakLocation', source=1, destination=0)
		if tweak:
			cmds.delete(tweak)

		# Shift the extracted shape to the side
		cmds.xform(extracted, relative=True, translation=[offset, 0, 0])

		if live:
			self.connectShape(shape, extracted, live, delete=False)

		return extracted
예제 #13
0
def createRigDisplayLayer(rig):
    """
    Creates a Display Layer and adds $rig to this layer
    [attr] $rig - current rig which we pass in to this function
    """

    layerName = rig + "_DL"

    cmds.createDisplayLayer(name=layerName) #create a layer

    cmds.editDisplayLayerMembers(layerName, rig) #add a rig to it
예제 #14
0
def createLayerFromSmoothSets(*arg):
    smoothSetLs = smoothSetList()
    smoothSetLs.sort(reverse=True)
    for smoothSet in smoothSetLs:
        memberLs = mc.sets(smoothSet, q=True)
        if memberLs:
            value = smoothSet[len(smoothSetBodyName):]
            createDisplayer(value)
            mc.editDisplayLayerMembers(dispLayerName(value),
                                       memberLs,
                                       noRecurse=True)
 def UpdateDisplayLayer():
     cmds.select(cmds.listRelatives(cmds.ls(cameras = True, lights = True),parent = True))
     try:
         cmds.select("UserLights", add = True)
     except:
         pass
     try:
         cmds.select("CMLightRig", add = True)
     except:
         pass
     cmds.editDisplayLayerMembers( 'CM_Lights_and_Cameras', cmds.ls(selection = True) )
예제 #16
0
def rmvCustomRigNodesFromSets(*args):
    cmds.select('extra*_grp', 'misc*_grp', r=True, hi=True)
    if cmds.objExists('facial*_grp'):
        cmds.select('facial*_grp', add=True, hi=True)

    customRigNodes = cmds.ls(sl=True)

    cmds.sets(customRigNodes, rm='ControlSet')
    cmds.sets(customRigNodes, rm='AllSet')
    cmds.sets(customRigNodes, rm='DeformSet')

    cmds.editDisplayLayerMembers('defaultLayer', customRigNodes)
예제 #17
0
def addBlend():
    cards = cmds.ls('card*', transforms=True)
    for card in cards:
        bend = cmds.nonLinear(card, type='bend')[1]
        if not cmds.ls('bendHandleLayer'):
            cmds.createDisplayLayer(nr=True, name='bendHandleLayer')
        else:
            cmds.editDisplayLayerMembers('bendHandleLayer', bend)
        cmds.parent(bend, card)
        cmds.setAttr(bend + '.rx', 90)
        cmds.setAttr(bend + '.ry', 0)
        cmds.setAttr(bend + '.rz', 90)
예제 #18
0
def run(params, rig):
    for num, element in enumerate(params['layers']):
        nodes = [x.name() for x in element['objects']]
        if not cmds.objExists(element['name']):
            display_layer = cmds.createDisplayLayer(nodes, n=element['name'])
        else:
            cmds.editDisplayLayerMembers(element['name'], nodes)
            display_layer = element['name']

        cmds.setAttr('{}.visibility'.format(display_layer), element['visible'])
        for attr in ('displayType', 'shading', 'texturing', 'playback'):
            attr_name = '{}.{}'.format(display_layer, attr)
            cmds.setAttr(attr_name, element[attr])
예제 #19
0
	def createRawShape(self, shapeName, shape):
		newShape = cmds.duplicate(self.mesh, name=shapeName)[0]
		cmds.delete(newShape, constructionHistory=True)
		cmds.editDisplayLayerMembers("defaultLayer", newShape, noRecurse=True)
		index = self._firstAvailableIndex()
		cmds.blendShape(self.shapeNode, edit=True, target=(self.mesh, index, newShape, 1.0))
		weightAttr = "{0}.weight[{1}]".format(self.shapeNode, index)
		thing = cmds.ls(weightAttr)[0]
		shape.thing = thing
		shapeIdx = self.simplex.shapes.index(shape)
		cmds.connectAttr("{0}.weights[{1}]".format(self.op, shapeIdx), thing)

		return newShape
예제 #20
0
def drawCurve( target,start,end,colour,samples ):
	# print target,start,end,samples,colour
	# make locator, constrain to target
	cmds.spaceLocator( name="myLocator" )
	cmds.select( target )
	cmds.select( "myLocator", add=True )
	cmds.pointConstraint()

	# make a new render layer with locator, and change display colour
	cmds.select( "myLocator" )
	exists = cmds.objExists( "AnimationCurves" )
	if ( exists==False ):
		cmds.createDisplayLayer( name="AnimationCurves", number=1, nr=True )
		cmds.createDisplayLayer( name="Spheres", number=1, nr=True )
		cmds.setAttr( "AnimationCurves.color", colour )
		cmds.setAttr( "Spheres.color", 16 )		

	# make a list of all the frames where points for the curve will be created
	frameList = []
	frameList.append( start )
	length = end - start
	samples = cmds.intField( samplesField, q=1, v=1 )
	interval = int( length / (samples-1) ) # using int() to ensure integer frame numbers
	for i in range( 1,samples ):
		frameList.append( start+interval*i )
	frameList.append( end )

	# make a list of tuples containing the locations of the target/locator for every frame needed
	xFormList = []
	n = 0
	for frame in ( frameList ):
		x = cmds.getAttr( "myLocator.tx",time=frame )
		y = cmds.getAttr( "myLocator.ty",time=frame )
		z = cmds.getAttr( "myLocator.tz",time=frame )
		currentXForm = ( x,y,z )
		xFormList.append( currentXForm )
		cmds.sphere( n="sphere"+str(n), r=0.2 )
		cmds.move( x,y,z, "sphere"+str(n), a=True )
		n+=1
		# print frame, "= ", x,y,z
	cmds.editDisplayLayerMembers( "Spheres", "sphere*", nr=True )

	# create curve using list of tuples
	cmds.curve( p=xFormList, d=1, ws=True )
	cmds.rename( target+"_animation_curve" )
	cmds.group( target+"_animation_curve", "sphere*", n="curve" )
	# add curve to animation curves layer
	cmds.editDisplayLayerMembers( "AnimationCurves", "curve", nr=True )
	cmds.delete("myLocator")
	cmds.button( ccButton, e=1, en=0 )
	cmds.frameLayout( buttonGroup, e=1, l="Delete curve before creating another" )
예제 #21
0
파일: rcMaya.py 프로젝트: RobRuckus/rcTools
	def imageCard(self):
		selImage=mc.fileDialog()
		material=mc.shadingNode('lambert',asShader=1)
		fileNode=mc.shadingNode('file',asTexture=1)
		mc.setAttr(fileNode+'.fileTextureName',selImage,typ='string')
		mc.connectAttr(fileNode+'.outColor', material+'.color')
		sizeFactor=0.01
		imageSize=mc.getAttr(fileNode+'.outSize')
		modelPlane=mc.polyPlane(w=imageSize[0][0]*sizeFactor,h=imageSize[0][1]*sizeFactor,sx=1,sy=1,n='modelPlane',ax=[0,1,0],ch=0)
		mc.hyperShade(modelPlane,assign=material)
		if not mc.objExists('layer_ModelTemplate'): 
			mc.createDisplayLayer(name='layer_ModelTemplate')
			mc.setAttr('layer_ModelTemplate.displayType',2)
		mc.editDisplayLayerMembers('layer_ModelTemplate',modelPlane)
예제 #22
0
def add_to_dlayer(obj, layer, verbose=0):
    """Add the specified object to a display layer, creating it if needed.

    Args:
        obj (str): object to add
        layer (str): layer to add to
        verbose (int): print process data
    """
    if not cmds.objExists(layer):
        set_namespace(":")
        dprint("Creating displaylayer", layer, verbose=verbose)
        cmds.createDisplayLayer(name=layer, number=True, empty=True)

    cmds.editDisplayLayerMembers(layer, obj, noRecurse=1)
예제 #23
0
def combine():
    '''
		Combines the selected objects cleanly
	'''

    # grab your selection using the ls command
    selection = cmds.ls(sl=True)

    # the object that is your "source" is going to be the first one you selected
    target_object = selection[0]

    # if you want your source object to be the last one selected, comment the line above
    # and uncomment the following line

    # target_object = selection[-1] # the -1 array lookup means the last item of the array

    # let's give the user some feedback onto what's happening
    print "The Target Object is ", target_object

    # store the pivot information, so we can restore it in the future
    pivot = cmds.xform(target_object,
                       query=True,
                       worldSpace=True,
                       rotatePivot=True)

    # store the displayLayer for the same reason
    displayLayers = cmds.listConnections(target_object, type="displayLayer")

    # combine the meshes, with disabled construction history
    # this will get rid of the empty nodes that get left behind
    # and store the resulting new mesh name as a variable, so we can mess with it
    new_mesh = cmds.polyUnite(ch=False)

    # move the pivot back into place
    cmds.xform(new_mesh, rotatePivot=pivot)

    # if the object was a part of any display layers
    #  add the new object back to that layer
    if displayLayers:

        # the listConnections command will give us an array back of all of the different
        # connections, but since we can only be in one layer at a time, we know
        # that our layer is going to be the first one.
        # that's why we put the [0] after displayLayers
        cmds.editDisplayLayerMembers(displayLayers[0], new_mesh)

    # rename the new mesh to it's original name
    cmds.rename(new_mesh, target_object)

    print "Done!"
예제 #24
0
 def prepareOrginialGeo(self,*args):
     sel = cmds.ls(sl=True)[0]
     if '_org' in sel:
         blendshape_base_geo = cmds.duplicate(sel,n="{0}_blendshape".format(sel.split('_org')[0]))
         layers = cmds.ls(type='displayLayer')
         if "org_geo_layer" not in layers:
             org_layer = cmds.createDisplayLayer(n="org_geo_layer",e=True)
             cmds.editDisplayLayerMembers(org_layer,sel,blendshape_base_geo,noRecurse=True)
             cmds.setAttr("{0}.displayType".format(org_layer),2)
         elif "org_geo_layer" in layers:
             cmds.editDisplayLayerMembers(org_layer,sel,noRecurse=True)
             cmds.setAttr("{0}.displayType".format(org_layer),2)
     else:
         cmds.confirmDialog(m="Please Select The Orginial Geo!")
     cmds.select(sel,blendshape_base_geo,r=True)
예제 #25
0
 def members(self):
     # type: () -> List[DagNode]
     tmp_mfn = _om2.MFnDependencyNode()
     members = _cmds.editDisplayLayerMembers(self.mel_object,
                                             query=True,
                                             fullNames=True)
     return [_graphs.eval_node(node, tmp_mfn) for node in members or []]
예제 #26
0
    def keyPressEvent(self, event):
        pm.undoInfo(openChunk=True)
        if event.key() == Qt.Key_Space:
            if self.selectedItems():
                for item in self.selectedItems():
                    print item.text()
                    # new_state = Qt.Unchecked if item.checkState() else Qt.Checked
                    # if item.flags() & Qt.ItemIsUserCheckable:
                    #     item.setCheckState(new_state)
            self.reset()
        # 删除功能

        elif event.key() == Qt.Key_Delete:
            for item in self.selectedItems():
                layer_name = item.text()
                layer_name = unicode(layer_name)
                objs_in_layer = cmds.editDisplayLayerMembers(layer_name, query=True)
                if objs_in_layer is not None:
                    print '1'
                    self.takeItem(self.row(item))
                    for i in objs_in_layer:
                        print i
                        pm.delete(i)
                    self.takeItem(self.row(item))
                    pm.delete(layer_name)
                else:
                    self.takeItem(self.row(item))
                    pm.delete(layer_name)
        pm.undoInfo(closeChunk = True)
예제 #27
0
def doRemoveFromLayers(node):
    """Disconnect layers from nodes.
    """
    topGrpLayer = None
    cnxList = [
        x
        for x in (cmds.listConnections(node, source=True, destination=False) or [])
        if cmds.nodeType(x) == "displayLayer"
    ]
    if cnxList:
        topGrpLayer = cnxList[0]
    nodeList = cmds.listRelatives(node, path=True, allDescendents=True) or []
    nodeList.append(node)
    if nodeList:
        cmds.editDisplayLayerMembers("defaultLayer", nodeList, noRecurse=True)
    return topGrpLayer
예제 #28
0
def queryLayer(lyr_name):
    '''Return all objects within the display layer'''
    items_in_lyr = cmds.editDisplayLayerMembers(lyr_name, q=True)
    if items_in_lyr is None:
        items_in_lyr = []

    return items_in_lyr
예제 #29
0
def _getPolygonFromDisplayLayers():
    visible_displaylayers = [ d for d in mc.ls(type='displayLayer')
        if mc.getAttr(d+'.visibility') and d not in ['defaultLayer']]
    if not visible_displaylayers:
        return {}
    polygonCollections = {}
    for dl in visible_displaylayers:
        itemsInLayer = mc.editDisplayLayerMembers(dl, q=True, fn=True)
        if not itemsInLayer:
            continue
        items = [o for o in itemsInLayer if mc.nodeType(o) in
            ['mesh', 'transform']]
        if not items:
            continue
        collections = []
        for item in items:
            if mc.nodeType(item) == 'mesh':
                collections.append(item)
            elif mc.nodeType(item) == 'transform':
                relatives = mc.listRelatives(item, ad=True,
                    type='mesh', ni=True, f=True)
                collections.extend(relatives)
        if collections:
            polygonCollections[dl] = collections
    return polygonCollections
예제 #30
0
 def inLayer( self , layerData ):
     for ln in layerData:
         if cmds.ls( ln[0] ) != []:
             cmds.delete( ln[0] )
         cmds.createDisplayLayer( name=ln[0] )
         print ln[0]
         map ( lambda item : cmds.editDisplayLayerMembers( ln[0] , item )  , ln[1] )
    def _run(self):
        self.import_eyes_aim_asset()
        self.create_lookat_placement_guides()
        self.place_lookat_rig()
        self.create_eye_control_heirarchy()
        self.connect_sightlines()
        self.connect_lookat_rig()
        self.delete_lookat_placement_guides()
        self.place_au_eyes_controls()
        self.orient_au_eyes_controls()
        self.constrain_au_eyes_controls()
        self.constrain_plot_to_lookat()
        self.setup_scaling()
        self.disable_lookat_by_default()

        # Add LookAt to "Controls" display layer.
        cmds.editDisplayLayerMembers('Controls', 'grp_controls_lookat_AITrajectory_world', 'lookat_sightlines')
    def DrawJointMotionPaths( self, roots ):
        """ Gathers points for each joint of each root and build motion paths (optimized to only cycle thru timeline once) """
        # prep the data structure
        keypoints = {}
        for root in roots:
            keypoints[root] = {}
            #.split(':')[-1]
            joints = [j for j in mc.listRelatives( root, allDescendents=True ) if j in self.traceableObjs]  # TODO: just get the nearby joints by projecting them all onto the viewing plane and finding the distance
            for j in joints:
                keypoints[root][j] = []
        # cycle through the timeline and record data
        for t in range(int(mc.playbackOptions(q=True,minTime=True)), int(mc.playbackOptions(q=True,maxTime=True))+1):
            mc.currentTime(t)
            for root in roots:
                #.split(':')[-1]
                joints = [j for j in mc.listRelatives( root, allDescendents=True ) if j in self.traceableObjs]
                for j in joints:
                    keypoints[root][j].append( mc.xform( j, q=True, ws=True, translation=True ) )
        # use the data to build motion curves
        cols = [9,12,13,14,15,17,18,23,29,31]   # color indices for the display layers
        for root in roots:
            joints = [j for j in mc.listRelatives( root, allDescendents=True ) if j in self.traceableObjs]
            if len(joints) > 0:
                traceGroup = mc.group(n="%s_MotionTraces"%root,empty=True)
                curves = []
                for num, j in enumerate(joints):
                    curve = bmt.CurveMotionTrace( j, keys=keypoints[root][j] )
                    curveGeom = curve.construct("%s_trace"%j)
                    curves.append( curveGeom )   # add the motion paths to the trace's search list and set up the DTWs

                    displayLayerName = "%s_MotionPaths"%j#.split(':')[-1]
                    if not mc.objExists(displayLayerName):
                        mc.createDisplayLayer(name=displayLayerName)
                        mc.setAttr("%s.color"%displayLayerName, cols[num])  
                        mc.editDisplayLayerMembers( displayLayerName, curveGeom )
                    else:
                        objs = mc.editDisplayLayerMembers(displayLayerName, query=True )
                        if objs:
                            objs.append( curveGeom )
                        else:
                            objs = [curveGeom]
                        mc.editDisplayLayerMembers( displayLayerName, objs )
                mc.parent(curves, traceGroup)
                mc.parent(traceGroup, root)
                mc.select(cl=True)
예제 #33
0
	def extractShape(self, shape, live=True, offset=10.0):
		""" Make a mesh representing a shape. Can be live or not.
			Can also store its starting shape and delta data
		"""
		with disconnected(self.shapeNode):
			for attr in cmds.listAttr("{0}.weight[*]".format(self.shapeNode)):
				cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)

			cmds.setAttr(shape.thing, 1.0)
			extracted = cmds.duplicate(self.mesh, name="{0}_Extract".format(shape.name))[0]
			cmds.editDisplayLayerMembers("defaultLayer", extracted, noRecurse=True)

		# Shift the extracted shape to the side
		cmds.xform(extracted, relative=True, translation=[offset, 0, 0])

		if live:
			self.connectShape(shape, extracted, live, delete=False)
		return extracted
예제 #34
0
    def deleteEmptyLayers(self):
        dispLayers = cmds.ls(type='displayLayer')

        for i in dispLayers:
            layerItems = cmds.editDisplayLayerMembers(i, query=True)
            if layerItems == None:
                cmds.delete(i)
            else:
                print layerItems
예제 #35
0
	def extractWithDeltaShape(self, shape, live=True, offset=10.0):
		""" Make a mesh representing a shape. Can be live or not.
			Also, make a shapenode that is the delta of the change being made
		"""
		with disconnected(self.shapeNode) as cnx:
			shapeCnx = cnx[self.shapeNode]
			for v in shapeCnx.itervalues():
				cmds.setAttr(v, 0.0)

			# store the delta shape
			delta = cmds.duplicate(self.mesh, name="{0}_Delta".format(shape.name))[0]

			# Extract the shape
			cmds.setAttr(shape.thing, 1.0)
			extracted = cmds.duplicate(self.mesh, name="{0}_Extract".format(shape.name))[0]
			cmds.editDisplayLayerMembers("defaultLayer", extracted, noRecurse=True)

			# Store the initial shape
			init = cmds.duplicate(extracted, name="{0}_Init".format(shape.name))[0]

		# clear old orig objects
		for item in [delta, extracted, init]:
			self._clearShapes(item, doOrig=True)

		# build the deltaObj system
		bs = cmds.blendShape(delta, name="{0}_DeltaBS".format(shape.name))[0]

		cmds.blendShape(bs, edit=True, target=(delta, 0, init, 1.0))
		cmds.blendShape(bs, edit=True, target=(delta, 1, extracted, 1.0))

		cmds.setAttr("{0}.{1}".format(bs, init), -1.0)
		cmds.setAttr("{0}.{1}".format(bs, extracted), 1.0)

		# Cleanup
		nodeDict = dict(Delta=delta, Init=init)
		repDict = self._reparentDeltaShapes(extracted, nodeDict, bs)

		# Shift the extracted shape to the side
		cmds.xform(extracted, relative=True, translation=[offset, 0, 0])

		if live:
			self.connectShape(shape, extracted, live, delete=False)

		return extracted, repDict['Delta']
예제 #36
0
 def setupDisplayLayers(self):
     if self.rootJoint:
         mc.editDisplayLayerMembers(getSkeletonLayer(), self.rootJoint.name)
     for geometry in self.geometryData:
         chunks = geometry.chunkNames()
         if chunks:
             mc.editDisplayLayerMembers(getGeometryLayer(), chunks)
         else:
             mc.editDisplayLayerMembers(getGeometryLayer(), geometry.name())
     for primitive in self.primitiveData:
         mc.editDisplayLayerMembers(getPrimitiveLayer(), primitive.name)
예제 #37
0
    def update_listWidgetB(self, layer_name):
        self.tar_model.clear()
        objs_in_layer = cmds.editDisplayLayerMembers(layer_name, query=True)
        if objs_in_layer == None:
            print 'empty layer'
            return
        print str(len(objs_in_layer)) + ' objs in ' + layer_name
        for obj in objs_in_layer:

            self.tar_model.appendRow(QtGui.QStandardItem(obj))
예제 #38
0
def addToSmoothSet(*arg):
    selection = filterSelection(mc.ls(sl=True, l=True), 'scene')
    #value = mc.intSliderGrp(smstUI_smoothLvl_intSG, q=True, value=True)
    value = getSmoothLvl()
    if selection:

        # --- set
        remFromAll()
        createSmoothSet(value)
        inSet = mc.sets(smoothSetName(value), q=True) or []
        mc.sets(selection, add=smoothSetName(value))
        result = list(
            set([sel.rpartition('|')[-1] for sel in selection]) - set(inSet))
        print '# %s added to %s' % (result, smoothSetName(value))
        """
        # --- partition
        createPartition()
        addToPartition(smoothSetName(value))
        """
        # --- options
        options = optWhichNeedLoop()
        if options['loopInObj']:
            for obj in result:
                if mc.menuItem(smstUI_optSmView_mI, q=True, cb=True):
                    mc.displaySmoothness(obj, polygonObject=3)
                if options['loopInShape']:
                    for shape in mc.listRelatives(obj, s=True, f=True):
                        if mc.menuItem(smstUI_optSmPw_mI, q=True, cb=True):
                            mc.setAttr(shape + '.smoothLevel', value)
                        if mc.menuItem(smstUI_optSmRnd_mI, q=True, cb=True):
                            mc.setAttr(shape + '.renderSmoothLevel', value)

        # --- layer
        if mc.menuItem(smstUI_optDispLay_mI, q=True, cb=True):
            createDisplayer(value)
            mc.editDisplayLayerMembers(dispLayerName(value),
                                       result,
                                       noRecurse=True)

    else:
        mc.error(
            'Wrong node type in selection ! Please select geometry transforms only'
        )
예제 #39
0
    def makeMeshCtrl(self):
        newMesh = cmds.duplicate(self.initialMesh, n=self.newCtrlName)[0]
        newMeshParts = [item.replace(self.initialMesh, newMesh) for item in self.selectedFaces]
        print(newMesh)
        print(newMeshParts)
        cmds.setAttr(newMesh+'.tx', lock=False)
        cmds.setAttr(newMesh+'.ty', lock=False)
        cmds.setAttr(newMesh+'.tz', lock=False)
        cmds.setAttr(newMesh+'.rx', lock=False)
        cmds.setAttr(newMesh+'.ry', lock=False)
        cmds.setAttr(newMesh+'.rz', lock=False)
        cmds.setAttr(newMesh+'.sx', lock=False)
        cmds.setAttr(newMesh+'.sy', lock=False)
        cmds.setAttr(newMesh+'.sz', lock=False)
        cmds.editDisplayLayerMembers('defaultLayer', newMesh, noRecurse=True)

        newMeshShape = cmds.listRelatives(newMesh, shapes=True)[0]
        oldMeshShape = cmds.listRelatives(self.initialMesh, shapes=True)[0]
        ctrlShape = cmds.listRelatives(self.selectedCtrl, shapes=True)[0]

        cmds.connectAttr(oldMeshShape+'.outMesh', newMeshShape+'.inMesh')

        cmds.parent(newMesh, self.selectedCtrl)
        cmds.makeIdentity(newMesh, apply=True, r=True, t=True, s=True)
        cmds.select(newMesh+'.f[*]', r=True)
        cmds.select(newMeshParts, tgl=True)
        cmds.delete()

        cmds.select(cl=True)

        cmds.parent(newMeshShape, self.selectedCtrl, shape=True, relative=True)

        newMeshHistory = cmds.listHistory(newMeshShape)
        for item in newMeshHistory:
            if cmds.nodeType(item) == 'transformGeometry':
                transGeoNode = item

        cmds.setAttr(transGeoNode+'.invertTransform', 1)
        cmds.connectAttr(self.selectedCtrl+'.worldMatrix', transGeoNode+'.transform')
        cmds.delete(newMesh)

        cmds.hide(ctrlShape)
        cmds.select(cl=True)
예제 #40
0
    def _find(self):
        """
        :return: Empty display layers
        :rtype: generator
        """
        layers = self.ls(type="displayLayer")
        layers = reference.removeReferenced(layers)

        for layer in layers:
            if (not cmds.editDisplayLayerMembers(layer, query=True)
                    and not layer.endswith("defaultLayer")):
                yield layer
예제 #41
0
def createMayaBox(jointName, parentJointName, amIRoot):
    #print 'Trying to create controlBox, jointName: %s\n   parentJointName: %s\n amIRoot: %s' % (jointName, parentJointName, amIRoot)
    cmds.select(jointName)
    parentJnt = cmds.listRelatives(jointName, p = True)
    jntTrans = cmds.xform(q = True, translation = True, ws = True)
    jntRot = cmds.xform(q = True, rotation = True, ws = True)
    cmds.makeIdentity(apply = True, jo = True)
    controlName = 'Control_%s' % jointName
    if jointName.lower() == 'root':
        #special shape for the root
        newCurve = cmds.circle(n = controlName, nr = (0,1,0), r = 30)[0]
    else:
        #default shape is the cube
        edge = 20
        newCurve = cmds.curve(n = controlName, d = 1, p=[(-edge, edge, edge),
        (edge, edge, edge),
        (edge,-edge,edge),
        (-edge,-edge,edge),
        (-edge,edge,edge),
        (-edge,edge,-edge),
        (-edge,-edge,-edge),
        (-edge, -edge, edge),
        (-edge, edge, edge),
        (edge,edge,edge),
        (edge,edge,-edge),
        (-edge, edge, -edge),
        (-edge, -edge, -edge),
        (edge, -edge, -edge),
        (edge, edge, -edge),
        (edge,edge,edge),
        (edge, -edge, edge) ,
        (edge, -edge, -edge)], k = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])
    cmds.editDisplayLayerMembers('Controls', newCurve)
    cmds.move(jntTrans[0],jntTrans[1],jntTrans[2])
    cmds.makeIdentity(apply = True, t= 1, r= 1, s= 1, n= 0)
    cmds.connectAttr('%s.r' % newCurve, '%s.r' % jointName)
    if not amIRoot:
        cmds.parent(controlName, 'Control_%s' % parentJointName)
        #adding to a display layer is recursive by default, so only do on root
        cmds.editDisplayLayerMembers('Joints', cmds.ls(sl = True)[0])
    def _get_empty_layers(self):

        layers = cmds.ls(type='displayLayer')
        empty = []

        for layer in layers:
            if layer in self.__skip_layers:
                continue

            members = cmds.editDisplayLayerMembers(layer, q=1)
            if not members:
                empty.append(layer)

        return empty
예제 #43
0
	def init_export_layers(self):
		export_layer_names = None
		if cmds.objExists('export_layers'):
			export_layer_names = cmds.listRelatives('export_layers')

		self._exportLayers.clear()
		if export_layer_names is not None:
			# Load items from settings
			for export_layer_name in export_layer_names:
				name_value = self._settings.load('name', '', export_layer_name, 'export_layers')
				objects_value = self._settings.load('objects', '', export_layer_name, 'export_layers', as_list = True)
				active_value = self._settings.load('active', True, export_layer_name, 'export_layers')

				self._exportLayers.add(name_value, objects_value, active_value)

		# Add export objects from the scene
		fbx_export_layer = self._util.to_node_name('FBX_Export')
		character_name = self._settings.get_ref_name()
		objects = []

		if character_name == '':
			# Set default character name
			character_name = 'Character'

		# Check if it hasn't been added before
		is_new_export_layer = True
		for exportLayer in self._exportLayers.get_list():
			if character_name == exportLayer.get_name():
				is_new_export_layer = False
				break

		# Check that FBX export layer exists
		is_fbx_export_layer_exists = cmds.objExists(fbx_export_layer)

		if is_new_export_layer and is_fbx_export_layer_exists:
			# Get export objects from the scene
			export_objects = cmds.editDisplayLayerMembers(fbx_export_layer, query=True)
			if export_objects is not None and len(export_objects) > 0:
				objects = export_objects

			self._exportLayers.add(character_name, objects, True)

		# Update UI
		self._update_export_layers_ui()
    def _get_empty_layers(self):

        layers = cmds.ls(type='displayLayer')
        empty = []

        for layer in layers:
            if layer in self.__skip_layers:
                continue

            # Skip those that are referenced
            # TODO: Do we really want to skip those that are referened?
            if cmds.referenceQuery(layer, isNodeReferenced=True):
                continue

            members = cmds.editDisplayLayerMembers(layer, q=1)
            if not members:
                empty.append(layer)

        return empty
예제 #45
0
def doSwapForReference(node, startingDirectory=ddConstants.ASSETLIBRARY, filename=None):
    '''
    Swaps selected group or reference for another reference.
    @param node: Node or GRP node to be swapped out.
    @param startingDirectory: Base asset library directory (optional).
    @param filename: Can pass filename directly to bypass file browser dialog (optional).
    '''
    # Get the node's parent. 
    nodeParent = cmds.listRelatives(node, parent=True, path=True)
    
    # Get the node's layer.
    topGrpLayer = None
    cnxList = [x for x in (cmds.listConnections(node, source=True, destination=False) or []) if cmds.nodeType(x) == "displayLayer"]
    if cnxList:
        topGrpLayer = cnxList[0]
    
    # Get the node's transformations.
    pos = cmds.xform(node, query=True, worldSpace=True, absolute=True, rotatePivot=True)
    rot = cmds.getAttr("%s.r" % node)[0]
    scl = cmds.getAttr("%s.s" % node)[0]
    
    # Select the node for the user to see.
    cmds.select(node, replace=True)
    cmds.refresh()
    cmds.namespace(setNamespace=":")
    
    # Get new reference file using file browser dialog.
    if not filename:
        filename = cmds.fileDialog2(
                fileMode=1, caption="Swap For Reference", 
                startingDirectory=startingDirectory, okCaption="Reference"
                )
        if not filename: 
            return None, startingDirectory, None
        filename = filename[0]
    
    # Check if file exists.
    if not os.path.isfile(filename):
        sys.stdout.write("File %s not found.\n" % filename)
        confirm = cmds.confirmDialog(
                title="Warning", messageAlign="center", 
                message='File not found "%s".' % filename, 
                button=["Cancel"], 
                defaultButton="Cancel", cancelButton="Cancel", dismissString="Cancel")
        return None, startingDirectory, None
    
    # Create the namespace.
    namespace = filename.rpartition("/")[2].rpartition("\\")[2].rpartition(".")[0]
    
    # Update the startingDirectory for the next pass.
    startingDirectory = filename.rpartition("/")[0]
    
    # Remove old reference or just delete the node.
    if cmds.referenceQuery(node, isNodeReferenced=True):
        referencedPath = cmds.referenceQuery(node, filename=True)
        cmds.file(referencedPath, removeReference=True, mergeNamespaceWithRoot=True)
    else:
        cmds.delete(node)
        
    # Load new reference under the new namespace.
    newReferencedNodes = cmds.file(filename, reference=True, namespace=namespace, returnNewNodes=True)
    
    # Find the top group of the referenced file.
    referencedTopGrp = ""
    refTransforms = [x for x in newReferencedNodes if cmds.nodeType(x) == "transform"]
    for refTransform in refTransforms:
        refParent = cmds.listRelatives(refTransform, parent=True, fullPath=True)
        if not refParent or not refParent[0] in refTransforms:
            referencedTopGrp = refTransform
            
    # Position new top group using node's transformations. 
    try:
        cmds.xform(referencedTopGrp, worldSpace=True, absolute=True, translation=pos)
        cmds.setAttr("%s.r" % referencedTopGrp, rot[0], rot[1], rot[2])
        cmds.setAttr("%s.s" % referencedTopGrp, scl[0], scl[1], scl[2])
    except:
        sys.stdout.write("Unable to reposition new node %s due to locked channels.\n" % referencedTopGrp)
        
    # Parent new top group to node's parent and node's layer.
    if topGrpLayer:
        cmds.editDisplayLayerMembers(topGrpLayer, referencedTopGrp, noRecurse=True)
    if nodeParent:
        try:
            referencedTopGrp = cmds.parent(referencedTopGrp, nodeParent[0])[0]
        except:
            sys.stdout.write("Unable to reparent new node %s.\n" % referencedTopGrp)
    
    # Return new top group and updated starting directory.
    return referencedTopGrp, startingDirectory, filename
예제 #46
0
def do(nodes=None):
    '''
    Duplicate referenced objects as referenced objects.
    @param nodes: One or more GEO or GRP nodes (optional).
    '''
    topGrp = "RefGrp"
    if not nodes:
        nodes = cmds.ls(selection=True, long=True) or []
        
    newSelection = list()
    referencedFiles = list()
    cmds.namespace(setNamespace=":")
    
    for node in nodes:
        if not cmds.referenceQuery(node, isNodeReferenced=True):
            sys.stdout.write("--> Not a referenced object: %s. Skipping...\n" % node)
            continue
        
        # Get the referenced node data.
        namespace = cmds.referenceQuery(node, namespace=True)
        namespaceChildren = [x for x in (cmds.ls("%s:*" % namespace, long=True) or []) if cmds.nodeType(x) == "transform"]
        
        # Get the top node.
        currentNode = node
        for child in namespaceChildren:
            parent = cmds.listRelatives(child, parent=True, path=True)
            if parent and not parent in namespaceChildren:
                currentNode = parent
        
        # Find the original reference information.
        filename = cmds.referenceQuery(currentNode, filename=True)
        nodeParent = cmds.listRelatives(currentNode, parent=True, path=True)
        topGrpLayer = None
        cnxList = [x for x in (cmds.listConnections(currentNode, source=True, destination=False) or []) if cmds.nodeType(x) == "displayLayer"]
        if cnxList:
            topGrpLayer = cnxList[0]
            
        # Check if new reference has already been created for this object.
        if filename in referencedFiles:
            continue
            
        # Reference nodes under topGrp.
        namespace = cmds.file(filename, query=True, namespace=True)
        cmds.file(filename, reference=True, namespace=namespace, groupReference=True, groupName=topGrp)
        referencedFiles.append(filename)
        
        # Transform the new nodes.
        newObjects = [x for x in cmds.listRelatives(topGrp, path=True) if cmds.nodeType(x) == "transform"] or None
        if newObjects:
            newNamespace = newObjects[0].rpartition(":")[0]
            for newObject in newObjects:
                # Find the matching original object.
                matchingObject = newObject.replace(newNamespace, namespace)
                if cmds.objExists(matchingObject):
                    # Get the transforms of the original object.
                    pos = cmds.getAttr("%s.t" % matchingObject)[0]
                    rot = cmds.getAttr("%s.r" % matchingObject)[0]
                    scl = cmds.getAttr("%s.s" % matchingObject)[0]
                    
                    # Transform the new object.
                    cmds.setAttr("%s.t" % newObject, pos[0], pos[1], pos[2])
                    cmds.setAttr("%s.r" % newObject, rot[0], rot[1], rot[2])
                    cmds.setAttr("%s.s" % newObject, scl[0], scl[1], scl[2])
                    
        # Clean out the topGrp.
        topGrpObjects = cmds.listRelatives(topGrp, path=True) or None
        if topGrpObjects:
            newSelection.extend(topGrpObjects)
            if nodeParent:
                cmds.parent(topGrpObjects, nodeParent)
            else:
                cmds.parent(topGrpObjects, world=True)
                
            if topGrpLayer:
                cmds.editDisplayLayerMembers(topGrpLayer, topGrpObjects, noRecurse=True)
                
        if cmds.objExists(topGrp):
            cmds.delete(topGrp)
    
    if newSelection:
        cmds.select(newSelection, replace=True)
import sys
import maya.standalone
maya.standalone.initialize( name='python' )
import maya.cmds as mc

file_path = sys.argv[-2]
export_path = sys.argv[-1]

mc.loadPlugin("objExport")

mc.file(file_path, o=True)

try:
    objects_to_select = mc.editDisplayLayerMembers("output", query=True)
    mc.select(objects_to_select)
except:
    mc.select(all=True)
mc.delete(constructionHistory=True)

mc.file(export_path, force=True, options="groups=1;ptgroups=1;materials=0;smoothing=1;normals=1", typ="OBJexport", es=True)

def tf_makeCubeBasic(width, depth, parent, child, prefix, suffix ):       
    # create the cube
    createCube = cmds.polyCube( w=width, h=depth, d=depth, ch=False, n='%s' % (parent + child + "_" + suffix) )
    #w = width of dummy (z relative to joint)
    #h = depth of dummy (y relative to joint)
    #d = height of dummy (meaningless, as we move the height to size of parent to child joints)
    
    cmds.editDisplayLayerMembers ( 'DummyLayer', createCube)   
    
    # move cube to parent
    pointCon = cmds.pointConstraint( parent, createCube[0] )
    
    # delete constraint once cube is in position
    cmds.delete( pointCon )
    
    # create the aim constraint
    aimCon = cmds.aimConstraint( child, createCube[0], aim=[0,0,1], u=[0,0,1] )
    
    # delete constraint once cube is aimed at child
    cmds.delete( aimCon )
    
    #parent cube under the parent joint
    cmds.parent( createCube[0], parent )
    
    # freeze transforms
    cmds.makeIdentity( createCube[0], apply=True )
    
    
    #
    # ajdust the shape of the reference cube
    # create clusters on verts
    
    #create top cluster
    topCluster = cmds.cluster( '%s.vtx[4:7]' % createCube[0] )
    cmds.hide( topCluster )
    
    topClusterConstraint = cmds.pointConstraint( parent, topCluster[1] )
    
    #create middle cluster
    #cmds.select( '%s.vtx[9:11]' % createCube[0], r=True )
    #cmds.select( '%s.vtx[21:25]' % createCube[0], add=True )
    
    #cluster = 'newCluster  "-envelope 1"'
    #midCluster = mel.eval(cluster)
    
    #cmds.hide( midCluster )
    
    #middleClusterConstraint = cmds.pointConstraint( parent, child, midCluster[1] )
    
    #cmds.setAttr( '%s.%sW0' % ( middleClusterConstraint[0], child), 0.5 )
    #cmds.setAttr( '%s.%sW1' % ( middleClusterConstraint[0], parent), 0.5 )
    
    
    bottomCluster = cmds.cluster( '%s.vtx[0:3]' % createCube[0] )
    cmds.hide( bottomCluster )
    
    bottomClusterConstraint = cmds.pointConstraint( child, bottomCluster[1] )
    
    cmds.delete( createCube[0], ch=True )
    # delete the constraints    
    get_trans = cmds.listRelatives( topClusterConstraint[0], p=True )
    #need to do an if statement
    cmds.delete( get_trans )
    
    #get_trans = cmds.listRelatives( middleClusterConstraint[0], p=True )
    #need to do an if statement
    #cmds.delete( get_trans )
    
    get_trans = cmds.listRelatives( bottomClusterConstraint[0], p=True )
    #need to do an if statement
    cmds.delete( get_trans )
예제 #49
0
def do(nodes=None, replaceWithReference=True, export=True, currentAssetCategory="environments", notify=True):
    # double check if necessary environment variables exist before continuing
    print "should we notify? %s" % str(notify)
    vpe.VP_Environment().test()

    currentAssetLibrary = ddConstants.ASSET_DIRECTORIES[currentAssetCategory]

    # Check if assetLibrary folder exists
    if not os.path.isdir(currentAssetLibrary):
        confirm = cmds.confirmDialog(
            title="Warning",
            messageAlign="center",
            message="AssetLibrary path does not exist: %s" % currentAssetLibrary,
            button=["Ok"],
            defaultButton="Ok",
            cancelButton="Ok",
            dismissString="Ok",
        )
        return

    # Get selection
    if not nodes:
        nodes = cmds.ls(selection=True, objectsOnly=True, long=True)
        if len(nodes) == 0:
            confirm = cmds.confirmDialog(
                title="Warning",
                messageAlign="center",
                message="Select at least one group object.",
                button=["Ok"],
                defaultButton="Ok",
                cancelButton="Ok",
                dismissString="Ok",
            )
            return

    if not isinstance(nodes, list):
        nodes = [nodes]

    invalidNodes = list()
    invalid_textured_nodes = list()
    override = False
    resultTopNodes = list()

    # Clean and export
    for sel in nodes:
        sys.stdout.write("\n--> %s\n" % sel.rpartition("|")[2])

        currentNode = sel
        nodeParent = cmds.listRelatives(sel, parent=True, path=True)
        if cmds.referenceQuery(currentNode, isNodeReferenced=True):
            currentNode = ddImportFromReference.do(currentNode)[0]

        invalidNode = ddCheckNames.do(nodes=currentNode, currentAssetCategory=currentAssetCategory)
        valid_textures = ddCheckTextures.do(node=currentNode)[0]
        if not invalidNode and valid_textures:
            publish_details = {}
            # no need to grab notes from user if not sending email
            if notify:
                publish_details["Notes"] = publish_notes.PublishNotes().notes

            validNode = ddRemoveNamespaces.doRemoveNamespaces(node=currentNode)
            topGrpLayer = ddRemoveFromLayers.do(nodes=validNode)[0]

            pos = cmds.xform(validNode, query=True, worldSpace=True, absolute=True, rotatePivot=True)
            rot = cmds.getAttr("%s.r" % validNode)[0]
            scl = cmds.getAttr("%s.s" % validNode)[0]

            ddUnlockGeoTransforms.do(nodes=validNode)
            returnedNodes = ddRemovePivotOffsets.do(
                nodes=validNode, returnToPos=False, currentAssetCategory=currentAssetCategory
            )
            if returnedNodes:
                validNode = returnedNodes[0]

            ddAddGeoMetadata.do(nodes=validNode)
            ddLockGeoTransforms.do(nodes=validNode)
            advancedAssets = cmds.ls(type="container", long=True)
            if advancedAssets:
                sys.stdout.write("Deleting advanced assets...\n")
                cmds.delete(advancedAssets)

            unknownNodes = cmds.ls(type="unknown", long=True)
            if unknownNodes:
                try:
                    sys.stdout.write("Deleting unknown nodes...\n")
                    cmds.delete(unknownNodes)
                except:
                    cmds.warning("Unable to delete unknown nodes.")

            if not export:
                continue

            if currentAssetLibrary == ddConstants.CHAR_ASSETLIBRARY:
                exportedNode, exportedPath = exportCharacterAsset(sel)
                # attempt to collect publish details for character piece
                charType = {"hero": "hero", "bg": "background", "sec": "secondary"}
                scene_patt = re.compile("char_(%s)_[A-Z]{3}_[a-z]+" % "|".join(charType.values()))
                char_patt = re.compile("[A-Z]{3}_[a-zA-Z]+")

                if scene_patt.search(exportedNode):
                    publish_details["Character"] = char_patt.search(exportedNode).group()
                publish_details["Template_Category"] = "vad_chesspiece"
            else:
                exportedNode, exportedPath, override = exportAsset(
                    node=validNode, override=False, currentAssetCategory=currentAssetCategory
                )
                env_patt = re.compile("[a-z]{3,4}(_[a-z]{3})*(_[a-z]+)*_([a-zA-Z]+[0-9]*[A-Z]v[A-Z])_*")
                if env_patt.search(exportedNode):
                    publish_details["Enviro_Asset"] = env_patt.search(exportedNode).groups()[-1]
                publish_details["Template_Category"] = "vad_enviro_asset"

            if exportedPath:
                ddScreenBoardGrab.do_boards(
                    nodes=exportedNode.rpartition("|")[2], current_asset_category=currentAssetCategory
                )
                # ddScreenGrab.do(nodes=exportedNode.rpartition("|")[2], currentAssetCategory=currentAssetCategory)
            else:
                if currentNode != sel:
                    cmds.delete(currentNode)
                sys.stdout.write("Export of %s was Canceled..." % exportedNode)
                return

            # update publish details with version, file
            #   and file path information
            version_patt = re.compile("_v([0-9]{2,4})_*")
            if version_patt.search(exportedNode):
                publish_details["Version"] = version_patt.search(exportedNode).groups()[0]
            publish_details["FILEPATH"] = "%s.ma" % exportedPath
            publish_details["FILE"] = os.path.basename(publish_details["FILEPATH"])

            if replaceWithReference and exportedPath:
                currentSceneFile = cmds.file(query=True, sceneName=True).replace("/", os.sep)
                exportedFile = "%s.ma" % exportedPath
                if currentSceneFile == exportedFile:
                    confirm = cmds.confirmDialog(
                        title="Warning",
                        messageAlign="center",
                        message="Scene file is already open. Cannot reference a file into itself.",
                        button=["Ok"],
                        defaultButton="Ok",
                        cancelButton="Ok",
                        dismissString="Ok",
                    )
                    if confirm == "Ok":
                        continue

                # Delete original GRP
                confirm = cmds.confirmDialog(
                    title="Warning",
                    messageAlign="center",
                    message="Delete original GRP?",
                    button=["Ok", "Keep Original"],
                    defaultButton="Ok",
                    cancelButton="Keep Original",
                    dismissString="Keep Original",
                )
                if confirm == "Ok":
                    cmds.delete(exportedNode)
                else:
                    # Move group back.
                    cmds.xform(exportedNode, worldSpace=True, absolute=True, translation=pos)
                    cmds.setAttr("%s.r" % exportedNode, rot[0], rot[1], rot[2])
                    cmds.setAttr("%s.s" % exportedNode, scl[0], scl[1], scl[2])

                # Reference a copy of the exported file
                namespace = os.path.split(exportedPath)[1].partition(".")[0]

                newReferencedNodes = cmds.file(
                    "%s.ma" % exportedPath, reference=True, namespace=namespace, returnNewNodes=True
                )
                referencedTopGrp = ""
                refTransforms = [x for x in newReferencedNodes if cmds.nodeType(x) == "transform"]
                for refTransform in refTransforms:
                    refParent = cmds.listRelatives(refTransform, parent=True, fullPath=True)
                    if not refParent or not refParent[0] in refTransforms:
                        referencedTopGrp = refTransform
                cmds.xform(referencedTopGrp, worldSpace=True, absolute=True, translation=pos)
                cmds.setAttr("%s.r" % referencedTopGrp, rot[0], rot[1], rot[2])
                cmds.setAttr("%s.s" % referencedTopGrp, scl[0], scl[1], scl[2])

                if topGrpLayer:
                    cmds.editDisplayLayerMembers(topGrpLayer, referencedTopGrp, noRecurse=True)
                if nodeParent:
                    referencedTopGrp = cmds.parent(referencedTopGrp, nodeParent[0])[0]

                resultTopNodes.append(referencedTopGrp.rpartition("|")[2])
            else:
                # Move group back.
                cmds.xform(exportedNode, worldSpace=True, absolute=True, translation=pos)
                cmds.setAttr("%s.r" % exportedNode, rot[0], rot[1], rot[2])
                cmds.setAttr("%s.s" % exportedNode, scl[0], scl[1], scl[2])
                resultTopNodes.append(exportedNode.rpartition("|")[2])
                if topGrpLayer:
                    cmds.editDisplayLayerMembers(topGrpLayer, exportedNode, noRecurse=True)
                if nodeParent:
                    exportedNode = cmds.parent(exportedNode, nodeParent[0])[0]

            # prep and send publish email
            publish_details["SHOW"] = os.getenv("SHOW")
            publish_details["ARTIST"] = os.getenv("ARTIST") if os.getenv("ARTIST") else "Some Artist"

            # send publish email if user specified notification
            if notify:
                sys.stdout.write("Sending email. \n")
                set_email = pub_mail.PublishEmail(publish_details["Template_Category"])
                set_email.publish_details = publish_details
                set_email.build_email()
                set_email.send_mail()
            else:
                sys.stdout.write("Holding off on sending publish email by request. \n")

        else:
            if invalidNode:
                sys.stdout.write("Invalid name %s. Skipping...\n" % invalidNode[0].rpartition("|")[2])
                invalidNodes.append(sel)
            elif not valid_textures:
                sys.stdout.write("Invalid texture found on node %s. Skipping...\n" % sel.rpartition("|")[2])
                invalid_textured_nodes.append(sel)

    if invalidNodes:
        nodeString = ""
        for invalidNode in invalidNodes:
            nodeString += "%s, " % invalidNode.rpartition("|")[2]

        confirm = cmds.confirmDialog(
            title="Warning",
            messageAlign="center",
            message="Please legalize the %s names of the following groups and re-export:\n\n%s"
            % (currentAssetCategory[:-1], nodeString[:-2]),
            button=["Ok"],
            defaultButton="Ok",
            cancelButton="Ok",
            dismissString="Ok",
        )
        cmds.select(invalidNodes, replace=True)

    # report back any nodes found with invalid textures
    if invalid_textured_nodes:
        node_string = ", ".join(invalid_textured_nodes)

        confirm = cmds.confirmDialog(
            title="Warning",
            messageAlign="center",
            message="Please fix the textures of the following groups and re-export:\n\n%s" % (node_string),
            button=["Ok"],
            defaultButton="Ok",
            cancelButton="Ok",
            dismissString="Ok",
        )
        if invalidNodes:
            # add to selection of other invalid nodes
            cmds.select(invalid_textured_nodes, add=True)
        else:
            # select only these invalid nodes
            cmds.select(invalid_textured_nodes, replace=True)

    if resultTopNodes:
        try:
            cmds.select(resultTopNodes, r=1)
        except:
            pass
예제 #50
0
 def CreateArchive(*args):
     cmds.confirmDialog(m = "This action will create a copy of the scene in the temp dir")
         
     ExportTypes = cmds.textScrollList("ExportTextScrollList", query = True, si = True)
     
     for Type in ExportTypes:
         if Type == "ma" or Type == "mb":
             #Save the file copy in the new path
             if Type == "ma":
                 cmds.file( save = True, type='mayaAscii' )
             else:
                 cmds.file( save = True, type='mayaBinary' )
             
             cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer")
             
             ShadersFile.ShaderClass.DeleteWireframeShader()
             ShadersFile.ShaderClass.DeleteUVMat()
             if not cmds.objExists("ShadowPlane"):
                 ShadersFile.ShaderClass.DeleteVrayShadowMat()
                 ShadersFile.ShaderClass.DeleteMRShadowMat()
                 
             ModelName = cmds.getAttr("CMSettings.ModelName")
             
             ProjectPath = cmds.getAttr("CMSettings.ProjectPath")
             
             try:cmds.delete("CMSettings")
             except:pass
             
             if cmds.objExists("RWSPlane"):
                 cmds.delete("RWSPlane")
             if cmds.objExists("RWSTexture"):
                 cmds.delete("RWSTexture")
             if cmds.objExists("RWSTexturePlacer"):
                 cmds.delete("RWSTexturePlacer")
             if cmds.objExists("RWSShader"):
                 cmds.delete("RWSShader")
             if cmds.objExists("RWSShaderSG"):
                 cmds.delete("RWSShaderSG")
             
             try:cmds.delete("CMBackground")
             except:pass
             
             SceneParts = ["ShadowPlane", "CMLightRig", "UserLights", "CMBackground"]
             for i in SceneParts:
                 if (not cmds.checkBox( i + "CheckBox", query = True, value = True)) and cmds.objExists(i):
                     if i == "ShadowPlane": 
                         ShadersFile.ShaderClass.DeleteVrayShadowMat()
                         ShadersFile.ShaderClass.DeleteMRShadowMat()
                     if i == "CMLightRig":
                         try: cmds.delete("EnvironmentGamma")
                         except:pass
                     try:cmds.delete(i)
                     except:pass
                 
             #Delete all animations
             try:cmds.cutKey(ModelName)
             except:pass
             
             for mesh in cmds.listRelatives(ModelName, children = True):
                 try:cmds.setAttr(mesh + "Smooth.divisions", 0)
                 except:pass
                 try:cmds.delete(mesh + "Smooth")
                 except:pass
         
             
             #Move the persp to the signatures place
             for i in range(0,len(SnapShotFile.SnapShotClass.SnapShots)):
                 if cmds.getAttr(SnapShotFile.SnapShotClass.SnapShots[i].Camera+'.CMSignature') == True:
                         SnapShotFile.SnapShotClass.SnapShots[i].CopyCameraInfo()
             
             cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer")
             
             try:cmds.delete("Signature")
             except:pass
             
             try:cmds.delete("SQRSignature")
             except:pass
             
             try:cmds.delete("ContextSig")
             except:pass
             
             try:cmds.delete("Product")
             except:pass
             
             for i in TurntableFile.TurntableClass.Turntables:
                 try:cmds.delete(i.RenderLayer)
                 except:pass
             
             try:cmds.delete("Wireframe")
             except:pass
             
             try:cmds.delete("Subdivision_0")
             except:pass
             
             try:cmds.delete("Subdivision_1")
             except:pass
             
             try:cmds.delete("UVs")
             except:pass
             
             mel.eval("BakeAllNonDefHistory;")
             #cmds.delete(all = True, constructionHistory = True)
             
             #Delete all cameras
             for i in SnapShotFile.SnapShotClass.SnapShots:
                 cmds.camera(i.Camera, edit = True, startupCamera = False)
             
             for i in TurntableFile.TurntableClass.Turntables:
                     cmds.camera(i.Camera, edit = True, startupCamera = False)
             
             CameraList = SnapShotFile.SnapShotClass.SnapShots
             for i in CameraList:
                 if cmds.getAttr(i.Camera + ".CMSignature"):
                     cmds.setAttr(i.Camera + ".backgroundColor", 0.968627, 0.968627, 0.968627, type = "double3")
                     cmds.rename(i.Camera, ModelName + "Camera")
                     try:cmds.delete(i.Camera + "_ImagePlane")
                     except:pass
                 else:
                     cmds.delete(i.Camera)
             
             CameraList = TurntableFile.TurntableClass.Turntables
             for i in TurntableFile.TurntableClass.Turntables:
                 cmds.delete(i.Camera)
             
             try:cmds.delete("CMForegroundPlane")
             except:pass
             try:cmds.delete("CMBackgroundPlane")
             except:pass
                 
             cmds.select(all = True)
             cmds.editDisplayLayerMembers(ModelName + "_layer", cmds.ls(selection = True), noRecurse = True  )
             cmds.displaySmoothness(divisionsU = 1,divisionsV = 1, pointsWire = 8, pointsShaded = 2, polygonObject = 2)
             for mesh in cmds.ls(sl = True):
                     try: 
                         cmds.setAttr(mesh + ".renderSmoothLevel", 1)
                     except:
                         pass
             
             #Save the file
             if Type == "ma":
                 cmds.file( rename = ProjectPath + "/temp/" + "/CM_" + ModelName + ".ma" )
                 cmds.file( save = True, type='mayaAscii' )
             else:
                 cmds.file( rename = ProjectPath + "/temp/" + "/CM_" + ModelName + ".mb" )
                 cmds.file( save = True, type='mayaBinary' )
             
             #Create the zip file
             if Type == "ma":
                 zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_ma.zip', 'w')
             else:
                 zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_mb.zip', 'w')
                 
             
             #write to the zip file
             if Type == "ma":
                 zipf.write(ProjectPath + "/temp/" + "CM_" + ModelName + ".ma", os.path.basename(ProjectPath + "/temp/" + "CM_" + ModelName + ".ma"))                
             else:
                 zipf.write(ProjectPath + "/temp/" + "CM_" + ModelName + ".mb", os.path.basename(ProjectPath + "/temp/" + "CM_" + ModelName + ".mb"))                
             
                 
             
             ##### Get textures ####
             def GetTextures():
                 Textures = []
                 
                 for i in cmds.ls(textures = True):
                     try:
                         Textures.append(cmds.getAttr(i + ".fileTextureName"))
                     except:
                         pass
                 #Remove duplicates    
                 return list(set(Textures))
             
             for i in GetTextures():
                 try:
                     zipf.write(i, os.path.basename(i))
                 except:
                     print "Could not write file ", i , " to zip"
             zipf.close()
             
         else:            
             #Create the export file
             try:
                 fileName = cmds.file(ProjectPath+ "/Temp/" + "CM_" + ModelName, exportAll = True, type = Type )
             except:
                 print "Failed to export scene in format :" , Type
                 continue
             
             #Create the zip file
             zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_' + Type +'.zip', 'w')
             
             #Iges format returns a wrong path fix it 
             if not os.path.exists(fileName):
                 Name, fileExtension = os.path.splitext(fileName)
                 if fileExtension == ".iges":
                     fileName = Name + ".igs"
             
             #Write the file into the zip
             try:
                 zipf.write(fileName, os.path.basename(fileName))
             except:
                 print "Could not write the format:", Type, " to zip file"
             
             #Write the textures in the zip
             for i in GetTextures():
                 try:
                     zipf.write(i, os.path.basename(i))
                 except:
                     pass
             zipf.close()
     
     cmds.displaySmoothness(divisionsU = 0,divisionsV = 0, pointsWire = 4, pointsShaded = 1, polygonObject = 1)
     
     #Save the file
     fileName = cmds.file(l = True, q = True)
     fileName = fileName[0]
     Extension = os.path.splitext(fileName)[1]
     if Extension == '.ma':            
         cmds.file( save = True, type='mayaAscii' )
     elif Extension == '.mb':
         cmds.file( save = True, type='mayaBinary' )
     elif Extension == "":
         cmds.file( save = True, type='mayaAscii' )
     
     cmds.confirmDialog(m = "The orginal file has been saved in the project folder")
     
     #Check to see if the window exists if it does delete it
     if cmds.dockControl("CMMainDock", exists = True):
         try:
             cmds.deleteUI("CMMainDock")
         except:
             print "Could not delete Main Dock"
     elif cmds.window("CMMainWindow", exists = True):
         try:
             cmds.deleteUI("CMMainWindow")
         except:
             print "Could not delete Main Window"
     
     if cmds.headsUpDisplay('SnapButton', exists = True):
         cmds.headsUpDisplay('SnapButton', rem = True)
     
     cmds.select(cmds.listRelatives(cmds.ls(cameras = True, lights = True),parent = True))
     try:
         cmds.select("UserLights", add = True)
     except:
         pass
     try:
         cmds.select("CMLightRig", add = True)
     except:
         pass
     try:
         cmds.editDisplayLayerMembers( 'CM_Lights_and_Cameras', cmds.ls(selection = True) )
     except:
         pass
예제 #51
0
def do(nodes=None, currentAssetLibrary=ddConstants.ASSETLIBRARY):
    '''
    Replaces selected nodes with references.
    @param nodes: One or moer GEO or GRP nodes (optional).
    @param currentAssetLibrary: Base asset library (optional).
    '''
    # Divider tokens: environment assets: GRP; character chessPieces: CPF, CPO, CPD.
    dividerTypes = ["CPF", "CPO", "CPD", "CPS"]
    
    # Character token abbreviations and equivalent asset directories.
    charType = { "hero": "hero", "bg": "background", "sec": "secondary" }
    
    if not nodes:
        nodes = cmds.ls(selection=True, long=True)
    if not isinstance(nodes, list):
        nodes = [nodes]
        
    cmds.namespace(setNamespace=":")
    
    for node in nodes:
        if not node:
            sys.stdout.write("--> %s does not exist. Skipping...\n" % node)
            continue
            
        if cmds.referenceQuery(node, isNodeReferenced=True):
            sys.stdout.write("--> Unable to replace referenced node %s with reference. Skipping... \n" % node.rpartition("|")[2])
            continue
            
        if ":" in node:
            sys.stdout.write("--> Unable to find original file for %s. Try removing namespaces first. Skipping... \n" % node.rpartition("|")[2])
            continue
        
        # Find the correct divider token used by the node.
        divider = "GRP"
        nodeParts = node.rpartition("|")[2].split("_")
        for nodePart in nodeParts:
            if nodePart in dividerTypes:
                divider = "%s_GRP" % nodePart

        # There should be at least 6 tokens to find the file.
        #   unless it's in the prop structure
        if not nodeParts[0].startswith('prop') and len(nodeParts) < 6:
            cmds.warning("--> Published asset file not found for %s. Skipping..." % node.rpartition("|")[2])
            continue
        
        currentPath = node
        found = False
        nodeName = ""
        # Find the full path to the top node containing the correct divider token.
        while not(currentPath == "") and not found:
            firstPart, pipeChr, lastPart = currentPath.rpartition("|")
            if divider in lastPart:
                found = True
                nodeName = lastPart
            else:
                currentPath = firstPart
        
        # Get the top node's parent.
        nodeParent = cmds.listRelatives(currentPath, parent=True, path=True)
        
        # Get the top node's layer.
        topGrpLayer = None
        cnxList = [x for x in (cmds.listConnections(currentPath, source=True, destination=False) or []) if cmds.nodeType(x) == "displayLayer"]
        if cnxList:
            topGrpLayer = cnxList[0]
            
        # Get the top node's transformations.
        pos = cmds.xform(currentPath, query=True, worldSpace=True, absolute=True, rotatePivot=True)
        rot = cmds.getAttr("%s.r" % currentPath)[0]
        scl = cmds.getAttr("%s.s" % currentPath)[0]
        
        nodePath, grp, version = nodeName.partition('_%s_' % divider)
        version = version.partition("_")[0]
        dirs, underscore, asset = nodePath.rpartition("_")
        nodePathParts = nodePath.split("_")
        
        # Build the path to the asset.
        assetPath = currentAssetLibrary
        for i in range(len(nodePathParts)):
            if currentAssetLibrary==ddConstants.CHAR_ASSETLIBRARY:
                if nodePathParts[i] == "char" or i > 2:
                    continue
                elif nodePathParts[i] in charType.keys():
                    assetPath = os.path.join(assetPath, charType[nodePathParts[i]])
                else:
                    assetPath = os.path.join(assetPath, nodePathParts[i])
                
            else:
                assetPath = os.path.join(assetPath, nodePathParts[i])
        
        # Build the asset filename and full path.
        assetFileName = "%s_%s.ma" % (asset, version)
        if currentAssetLibrary==ddConstants.CHAR_ASSETLIBRARY:
            assetPath = os.path.join(assetPath, "chesspiece", "published")
            asset = nodePath.replace("%s_%s_" % (nodePathParts[0], nodePathParts[1]), "")
            assetFileName = "%s_%s_%s.ma" % (asset, divider.replace("_GRP", ""), version)
        assetPath = os.path.join(assetPath, assetFileName)
        if not os.path.isfile(assetPath):
            cmds.warning("--> Published asset file not found for %s. Skipping..." % node.rpartition("|")[2])
            continue
        
        # Check if trying to reference the current scene file.
        currentSceneFile = cmds.file(query=True, sceneName=True).replace("/", os.sep)
        if currentSceneFile == assetPath:
            confirm = cmds.confirmDialog(
                    title="Warning", messageAlign="center", 
                    message="Scene file is already open. Cannot reference a file into itself.", 
                    button=["Ok"], 
                    defaultButton="Ok", cancelButton="Ok", dismissString="Ok"
                    )
            if confirm == "Ok":
                continue
                
        # Delete the original node.
        cmds.delete(node)
        
        # Create the namespace.
        namespace = os.path.split(assetFileName)[1].partition(".")[0]
        # Reference a copy of the asset into the namespace.
        newReferencedNodes = cmds.file(assetPath, reference=True, namespace=namespace, returnNewNodes=True)
        # Find the new referenced top node.
        referencedTopGrp = ""
        refTransforms = [x for x in newReferencedNodes if cmds.nodeType(x) == "transform"]
        for refTransform in refTransforms:
            refParent = cmds.listRelatives(refTransform, parent=True, fullPath=True)
            if not refParent or not refParent[0] in refTransforms:
                referencedTopGrp = refTransform
        
        # Set the referenced top node's transformations to match the original node.
        cmds.xform(referencedTopGrp, worldSpace=True, absolute=True, translation=pos)
        cmds.setAttr("%s.r" % referencedTopGrp, rot[0], rot[1], rot[2])
        cmds.setAttr("%s.s" % referencedTopGrp, scl[0], scl[1], scl[2])
        
        # Parent the referenced top node to the original node's parent and layer.
        if topGrpLayer:
            cmds.editDisplayLayerMembers(topGrpLayer, referencedTopGrp, noRecurse=True)
        if nodeParent:
            cmds.parent(referencedTopGrp, nodeParent[0])
            
    return True
예제 #52
0
def build ( char=None, cleanUp=False ):
    '''
    Builds the specified character
    
    '''
    #Build root structure
    rootSys = root.build()
    
    if not char:
        char = 'defaultChar'

    # import geo
    geoList = geo.importGeo(char)
    for g in geoList:
        cmds.parent( g, rootSys['geoGrp'] )
    
    # Import joints
    joints.importSkel(char)
    
    # Parent joints to root defJnts group
    jnts = cmds.ls(type='joint')
    for j in jnts:
        p = cmds.listRelatives(j, p=1)
        if not p:
            cmds.parent(j, rootSys['defJntsGrp'])

    # Build spine
    spineSys = spine.build( hips='cn_spine_01_defJnt', chest='cn_spine_06_defJnt', head='cn_spine_11_defJnt',numSpineJoints=6, numHeadJoints=6, twistAxis='x', bendAxis='y', cleanUp=cleanUp )
    cmds.parent(spineSys['xformGrp'], rootSys['systemsGrp'])
    spineTarg = cmds.group(empty=True)
    spineTarg = cmds.rename(spineTarg, common.getName(side='cn', rigPart='spine', function='const', nodeType='grp'))
    common.align(spineTarg, spineSys['xformGrp'])
    cmds.parent(spineTarg, rootSys['constGrp'])
    cmds.parentConstraint( spineTarg, spineSys['xformGrp'] )

    # Build limbs
    lf_arm = anom.systems.limb.build( startJoint='lf_shoulder_1_defJnt', middleJoint='lf_arm_1_defJnt', endJoint='lf_hand_defJnt', extraJoint='lf_hand_end_defJnt', side='lf', name='arm', twistJointCount=6 )
    cmds.parent( lf_arm['limbSystem_grp'], rootSys['systemsGrp'] )
    
    rt_arm = anom.systems.limb.build( startJoint='rt_shoulder_1_defJnt', middleJoint='rt_arm_1_defJnt', endJoint='rt_hand_defJnt', extraJoint='rt_hand_end_defJnt', side='rt', name='arm', twistJointCount=6 )
    cmds.parent( rt_arm['limbSystem_grp'], rootSys['systemsGrp'] )
    
    lf_leg = anom.systems.limb.build( startJoint='lf_leg_1_defJnt', middleJoint='lf_knee_1_defJnt', endJoint='lf_foot_defJnt', extraJoint='lf_foot_end_defJnt', side='lf', name='leg', twistJointCount=5, isLeg=True )
    cmds.parent( lf_leg['limbSystem_grp'], rootSys['systemsGrp'] )
    
    rt_leg = anom.systems.limb.build( startJoint='rt_leg_1_defJnt', middleJoint='rt_knee_1_defJnt', endJoint='rt_foot_defJnt', extraJoint='rt_foot_end_defJnt', side='rt', name='leg', twistJointCount=5, isLeg=True )
    cmds.parent( rt_leg['limbSystem_grp'], rootSys['systemsGrp'] )


    
    # Build hands
    lf_hand = anom.systems.hand.build( side='lf', root='lf_hand_root_defJnt',
                                       fingerDict={'thumb':'lf_hand_thumb1_defJnt',
                                                   'index':'lf_hand_index1_defJnt',
                                                   'mid':'lf_hand_mid1_defJnt',
                                                   'pinky':'lf_hand_pinky1_defJnt'},
                                      cleanUp=cleanUp )
    cmds.parent (lf_hand['systemGrp'], rootSys['systemsGrp'])
    cmds.parentConstraint( lf_arm['jointList'][2], lf_hand['systemGrp'], mo=1 ) # Sorry - I know it's horrible but time's running out!! (Bad, bad Duncan... :p)
    
    rt_hand = anom.systems.hand.build( side='rt', root='rt_hand_root_defJnt',
                                       fingerDict={'thumb':'rt_hand_thumb1_defJnt',
                                                   'index':'rt_hand_index1_defJnt',
                                                   'mid':'rt_hand_mid1_defJnt',
                                                   'pinky':'rt_hand_pinky1_defJnt'},
                                      cleanUp=cleanUp )
    cmds.parent (rt_hand['systemGrp'], rootSys['systemsGrp'])
    cmds.parentConstraint( rt_arm['jointList'][2], rt_hand['systemGrp'], mo=1 )
    
    # Build feet
    lf_foot = reverseFoot.build( side = 'lf', jntFoot = lf_leg['jointList'][-1],
                                 ctrlFoot = lf_leg['end_ctrl'],
                                 ikHandleLeg = lf_leg['ikHandle'],
                                 mesh = 'cn_body_render_mesh',
                                 stretchLoc = lf_leg['stretch_positions'][1],
                                 cleanUp = cleanUp
                                 )
    cmds.parent( lf_foot['systemsGrp'], rootSys['systemsGrp'])
    
    rt_foot = reverseFoot.build( side = 'rt',
                                 jntFoot = rt_leg['jointList'][-1],
                                 ctrlFoot = rt_leg['end_ctrl'],
                                 ikHandleLeg = rt_leg['ikHandle'],
                                 mesh = 'cn_body_render_mesh',
                                 stretchLoc = rt_leg['stretch_positions'][1],
                                 cleanUp = cleanUp
                                 )
    cmds.parent( rt_foot['systemsGrp'], rootSys['systemsGrp'])
    
    # Build AutoHips
    lf_autoHip = autoHip.createAutoHip(lf_leg['start_ctrl'], spineSys['hipCtrl'][0], lf_leg['end_ctrl'])
    rt_autoHip = autoHip.createAutoHip(rt_leg['start_ctrl'], spineSys['hipCtrl'][0], rt_leg['end_ctrl'])
    cmds.parent( lf_autoHip['autoHipSystem_grp'], rt_autoHip['autoHipSystem_grp'], rootSys['systemsGrp'])

    # Build Rivets
    lf_shoulder_rivet = rivet.build( targ=lf_arm['start_ctrl'], mesh='cn_body_render_mesh', side='lf', rigPart='arm', cleanUp=cleanUp )
    cmds.parent( lf_shoulder_rivet['follicle'], rootSys['constGrp'] )
    cmds.pointConstraint( lf_shoulder_rivet['constGrp'], cmds.listRelatives(lf_arm['start_ctrl'], p=1)[0] )
    
    rt_shoulder_rivet = rivet.build( targ=rt_arm['start_ctrl'], mesh='cn_body_render_mesh', side='rt', rigPart='arm', cleanUp=cleanUp )
    cmds.parent( rt_shoulder_rivet['follicle'], rootSys['constGrp'] )
    cmds.pointConstraint( rt_shoulder_rivet['constGrp'], cmds.listRelatives(rt_arm['start_ctrl'], p=1)[0] )
    
    lf_eye_rivet = rivet.build( targ='lf_head_eye_defJnt', mesh='cn_body_render_mesh', side='lf', rigPart='eye', cleanUp=cleanUp )
    cmds.parent( lf_eye_rivet['follicle'], rootSys['constGrp'] )
    
    rt_eye_rivet = rivet.build( targ='rt_head_eye_defJnt', mesh='cn_body_render_mesh', side='rt', rigPart='eye', cleanUp=cleanUp )
    cmds.parent( rt_eye_rivet['follicle'], rootSys['constGrp'] )
    
    connectToPuppet()

    # Bind skin
    cmds.select( cmds.listRelatives(rootSys['geoGrp']) )
    anom.core.skinWeights.rebindSkinClusters( char )
    anom.core.skinWeights.setSkinWeights( char )
    cmds.reorderDeformers( 'lf_foot_contact_ffd', 'skincluster_cn_body_render_mesh', 'cn_body_render_mesh' )

    # Make everything follow root the evil way | global scale
    cmds.parentConstraint( rootSys['constGrp'][0], rootSys['systemsGrp'][0], mo=1 )
    cmds.scaleConstraint ( rootSys['constGrp'][0], rootSys['systemsGrp'][0], mo=1 )
    cmds.connectAttr( rootSys['systemsGrp'][0] + '.scale', rootSys['defJntsGrp'][0] + '.scale' )

    invScale = cmds.shadingNode( 'multiplyDivide', asUtility = True, name = 'root_systems_invScale_md' )
    cmds.setAttr( invScale + '.operation', 2 )
    cmds.setAttr( invScale + '.input1', 1, 1, 1, type='double3' )
    cmds.connectAttr( rootSys['systemsGrp'][0] + '.scale', invScale + '.input2' )

    #connect autoHip to inverse world scale
    cmds.connectAttr( invScale + '.output', lf_autoHip['placer'][0] + '.scale' )
    cmds.connectAttr( invScale + '.output', rt_autoHip['placer'][0] + '.scale' )

    #connect follicles to systemGrp scale this fixes errors from the offset at extreme scaling values
    for fol in [ lf_shoulder_rivet['follicle'], rt_shoulder_rivet['follicle'], lf_eye_rivet['follicle'], rt_eye_rivet['follicle'] ]:
        cmds.connectAttr( rootSys['systemsGrp'][0] + '.scale', fol+'.scale' )
        cmds.setAttr( fol+'.v', 0 )

    # finally hide defJnts
    if cleanUp:
        cmds.setAttr( rootSys['offsetCtrl'][0].control +'.jointsVisibility', 0 )

    # create a Layer for the meshes
    cmds.createDisplayLayer( name='MESH_layer', empty=True )
    cmds.editDisplayLayerMembers( 'MESH_layer', rootSys['geoGrp'], noRecurse=True )
    cmds.setAttr( 'MESH_layer.displayType', 2 ) # unselectable

    cmds.select( clear=True )
예제 #53
0
 def outLayer(self):
     layers = [ x for x in cmds.ls(type="displayLayer" ) if x!= 'defaultLayer' ]
     layerData = []
     for x in layers:
         layerData.append( [ x , cmds.editDisplayLayerMembers( x , q=1) ] )
     return layerData