def _do_maya_pre_publish(self, task, work_template, progress_cb):
        """
        Do Maya primary pre-publish/scene validation
        """
        import maya.cmds as cmds

        progress_cb(0.0, "Validating current scene", task)

        # get the current scene file:
        scene_file = cmds.file(query=True, sn=True)
        if scene_file:
            scene_file = os.path.abspath(scene_file)

        # validate it:
        scene_errors = self._validate_work_file(scene_file, work_template,
                                                task["output"], progress_cb)

        for ref in pm.ls(type='reference'):
            try:
                pm.referenceQuery(ref, filename=True)
            except:
                pm.lockNode(ref, l=False)
                pm.delete(ref)

        progress_cb(100)

        return scene_errors
 def _do_maya_pre_publish(self, task, work_template, progress_cb):
     """
     Do Maya primary pre-publish/scene validation
     """
     import maya.cmds as cmds
     
     progress_cb(0.0, "Validating current scene", task)
     
     # get the current scene file:
     scene_file = cmds.file(query=True, sn=True)
     if scene_file:
         scene_file = os.path.abspath(scene_file)
         
     # validate it:
     scene_errors = self._validate_work_file(scene_file, work_template, task["output"], progress_cb)
     
     for ref in pm.ls(type='reference'):  
         try:
             pm.referenceQuery(ref,filename=True)  
         except:  
             pm.lockNode(ref,l=False)
             pm.delete(ref)
     
     progress_cb(100)
       
     return scene_errors
    def getReferencePath(self, node):
        filepath = ''
        if isinstance(node, type('')):
            try:
                node = pm.PyNode(node)
            except:
                pm.warning('Can not figure out what '+str(node)+' is, ignored!')
                return filepath

        if pm.referenceQuery(node, isNodeReferenced=True):
            filepath = pm.referenceQuery(node,  filename=True, wcn=True).replace('\\', '/')
        elif node.nodeType() == 'assemblyReference':
            l_rep_names = pm.assembly(node, query = True, listRepresentations= True)
            if not l_rep_names:
                return ''
            rep_name = pm.assembly(node, query = True, active = True)
            if rep_name in l_rep_names:
                if not rep_name.endswith('.locator'):
                    i = l_rep_names.index(rep_name)
                    filepath = pm.getAttr(node.name() + '.rep['+str(i)+'].rda')
                else:
                    # Choose locator
                    filepath = node.getAttr('definition')
            else:
                # Choose None
                if self.checkLeveL(node):
                    filepath = node.getAttr('definition')
                
        return filepath
    def filterObjects(self, obj):
        # convert obj to master
        masters = []
        if not obj:  # if no obj in frustum, return an empty list
            return masters

        for o in obj:
            if pm.referenceQuery(o, inr=True):
                try:
                    ns = pm.referenceQuery(o, ns=True)
                except:
                    print 'can not find namespace for object: ' + o
                    continue
                if pm.objExists(ns + ':master') and pm.objExists(ns + ':poly'):
                    masters.append(ns + ':master')

            else:
                if pm.nodeType(o) == 'assemblyReference':
                    masters.append(o)
                else:
                    tokens = o.split(':')
                    master_name = ':'.join(tokens[:-1]) + ':master'
                    if pm.objExists(master_name):
                        m_parent = pm.listRelatives(master_name, parent=True)
                        if len(m_parent) > 0 and m_parent[0].nodeType(
                        ) == 'assemblyReference':
                            masters.append(m_parent[0].name())

        return [pm.PyNode(m) for m in list(set(masters))]
def delete(node):
	if pm.referenceQuery(node, inr = True):
		refFile = pm.referenceQuery(node, f = True)
		ref = pm.FileReference(refFile)
		ref.remove()
		return
	for child in node.listRelatives(c=True):
		delete(child)
	pm.delete(node)
Beispiel #6
0
def getReferenceInfo(objToQuery=None, info='path'):
	"""
	Get the reference path / node associated with the given  objToQuery
	@param info: path / node
	@type info: str
	"""
	if objToQuery == None: objToQuery = pm.selected()[0]
	if info == 'path': return pm.referenceQuery( objToQuery, filename=True )
	elif info == 'node': return pm.referenceQuery( objToQuery, referenceNode=True )
Beispiel #7
0
def func():
    remove_namespace()
    # 找出带有关键字的骨骼根节点
    key_world = "Root_M"
    all_nodes = cmds.ls(type="joint", l=True)
    for node in all_nodes:
        print node
        if str(node).endswith("Root_M") and "DeformationSystem" in str(node):
            pm.select(node)
            break
    print("hahahaha")
    current_select = pm.ls(sl=True)
    if not current_select:
        return
    # 判断是不是代理文件,并处理命名空间
    final = get_top(current_select)[0]
    # judge the selection is ref or not
    ref_jud = pm.referenceQuery("%s" % final, isNodeReferenced=True)
    if ref_jud:
        file_path = pm.referenceQuery("%s" % final, filename=True)
        print file_path
        pm.mel.eval('file -importReference "%s"' % file_path)
        # 导入之后重新选择节点
        all_nodes = cmds.ls(type="joint", l=True)
        for node in all_nodes:
            print node
            if str(node).endswith("Root_M") and "DeformationSystem" in str(
                    node):
                pm.select(node)
                break
        print("hahahaha")
    current_select = pm.ls(sl=True)
    # 将这套骨骼从组中提出
    cmds.parent(current_select, world=True)
    # 选择根骨骼层级下的所有骨骼
    pm.select(current_select, hierarchy=True)
    all_sk = pm.ls(sl=True)
    # 获取当前起止帧数
    start = pm.playbackOptions(q=True, minTime=True)
    end = pm.playbackOptions(q=True, maxTime=True)
    # 进行动画烘焙
    pm.bakeResults(all_sk, simulation=True, hierarchy="below", t=(start, end))
    # 导出所选骨骼,包含所有层级,为fbx文件
    # 先选中骨骼
    pm.select(current_select)
    # 反选并删除其余内容,因为工程没整理,批量导出会有残余
    pm.mel.eval("invertSelection")
    pm.delete(pm.ls(sl=True))
    # 再选择导出的骨骼
    pm.select(current_select, hierarchy=True)
    # 输出路径
    current_path = pm.mel.eval("file -q -sn")
    fbxpath = os.path.splitext(current_path)[0] + ".fbx"
    pm.mel.eval('file -force -options "v=1;" -typ "FBX export" -pr -es "%s"' %
                fbxpath)
Beispiel #8
0
    def list_ref_assets(self):
        '''
        comes from list_ani_assets.py, check traditional reference nodes
        '''
        l_assets = []
        asset_trans = pm.ls('master', recursive=True, referencedNodes=True)
        l_constrained = cf.constrainedAssets(asset_trans)

        for trans in asset_trans:
            l_sons = pm.listRelatives(trans, c=True, pa=True)
            for son in l_sons:
                if not son.name().endswith(':poly'):
                    continue

                #asset_name = trans.name().split(":")[-2]
                asset_name = '.'.join(trans.name().split(":")[:-1])
                #print asset_name
                if pm.referenceQuery(trans, isNodeReferenced=True):
                    ref_path = pm.referenceQuery(trans, filename=True)
                    tokens = ref_path.split('/')
                    if 'asset' in tokens:
                        i = tokens.index('asset')
                        asset_type = tokens[i + 1]
                        ref_asset_name = tokens[i + 2]
                        asset_src = tokens[i + 3]
                    else:
                        asset_type = '-'
                        ref_asset_name = '-'
                        asset_src = '-'
                        #self.d_asset[asset_name] = {'type':tokens[i+1], 'src':tokens[i+3]}
                else:
                    asset_type = '-'
                    ref_asset_name = '-'
                    asset_src = '-'
                    #AssetData(namespace='', type='',  name='',        step='',   transform=None)
                if trans.fullPath() in l_constrained or trans.fullPath(
                ).startswith("|assets|asb"):
                    status = 'constrained'
                elif cf.isAnimation(trans):
                    status = 'animated'
                else:
                    status = 'edited'

                asset_data = ad.AssetData(asset_name, asset_type,
                                          ref_asset_name, asset_src, trans,
                                          status)
                if status == 'constrained':
                    asset_data.constrained = True
                l_assets.append(asset_data)

        return l_assets
Beispiel #9
0
 def test_failed_ref_edits(self):
     # Animate the zombieAttrs
     for transform in [x.getParent() for x in pm.ls(type='mesh')]:
         try:
             zombie = transform.attr('zombieAttr')
         except pm.MayaAttributeError:
             continue
         zombie.setKey(t=1, v=1)
         zombie.setKey(t=2, v=2)
         zombie.setKey(t=3, v=4)
     self.masterFile = pm.saveAs( os.path.join( self.temp, 'master.ma' ), f=1 )
     
     pm.openFile(self.sphereFile, f=1)
     pm.SCENE.pSphere1.zombieAttr.delete()
     pm.saveFile(f=1)
     
     # deleting the attr should give some failed ref edits...
     pm.openFile(self.masterFile, f=1)
     
     sphereRefs = [x for x in pm.listReferences(recursive=True)
                   if x.path.endswith('sphere.ma')]
     for ref in sphereRefs:
         print "testing failed ref edits on: %s" % ref
         self.assertEqual(1, len(pm.referenceQuery(ref,successfulEdits=False,failedEdits=True,es=True)))
         self.assertEqual(1, len(cmds.referenceQuery(str(ref.refNode), successfulEdits=False,failedEdits=True,es=True)))
Beispiel #10
0
 def test_failed_ref_edits(self):
     # Animate the zombieAttrs
     for transform in [x.getParent() for x in pm.ls(type='mesh')]:
         try:
             zombie = transform.attr('zombieAttr')
         except pm.MayaAttributeError:
             continue
         zombie.setKey(t=1, v=1)
         zombie.setKey(t=2, v=2)
         zombie.setKey(t=3, v=4)
     self.masterFile = pm.saveAs( os.path.join( self.temp, 'master.ma' ), f=1 )
     
     pm.openFile(self.sphereFile, f=1)
     pm.SCENE.pSphere1.zombieAttr.delete()
     pm.saveFile(f=1)
     
     # deleting the attr should give some failed ref edits...
     pm.openFile(self.masterFile, f=1)
     
     sphereRefs = [x for x in pm.listReferences(recursive=True)
                   if x.path.endswith('sphere.ma')]
     for ref in sphereRefs:
         print "testing failed ref edits on: %s" % ref
         self.assertEqual(1, len(pm.referenceQuery(ref,successfulEdits=False,failedEdits=True,es=True)))
         self.assertEqual(1, len(cmds.referenceQuery(str(ref.refNode), successfulEdits=False,failedEdits=True,es=True)))
Beispiel #11
0
def main(*args):
    # get the top one
    if not cmds.ls(sl=True):
        cmds.select(all=True)
    objs = pm.ls(sl=True, references=True)
    if not objs:
        return pm.inViewMessage(smg="select object first",
                                pos="midCenterTop",
                                bkc=0x00FF1010,
                                fade=True)
    pm.select(clear=True)
    for obj in objs:
        parent_node = pm.listRelatives(obj,
                                       children=True,
                                       fullPath=True,
                                       allParents=True)
        if parent_node:
            final = get_top(obj)[0]
        else:
            final = obj

        file_path = pm.referenceQuery("%s" % final, filename=True)

        if file_path.startswith("T:"):
            new_version_file = file_path.replace("T:", "m:")

            cmds.file(new_version_file,
                      loadReference="%s" % final,
                      type="mayaAscii",
                      options="v=0")
            pm.inViewMessage(smg="Update Done",
                             pos="midCenterTop",
                             bkc=0x00FF1010,
                             fade=True)
Beispiel #12
0
def reset_skin(oColl):
    #TODO: Test and make sure oColl can be transforms or shapes.
    # first, check for shapes vs. transforms. Let the user pick any mix
    #gatherShapes = [x.getParent() for x in oColl if type(x) == pm.nodetypes.Mesh]
    #gatherTransforms = [x for x in oColl if type(x) == pm.nodetypes.Transform if x.getShape()]
    #firstFilter = gatherTransforms + gatherShapes
    #geoFilter = [x for x in firstFilter if type(x.getShape()) == pm.nodetypes.Mesh]

    oldSel = pm.selected()
    for eachGeo in oColl:
        skinInputs = eachGeo.getShape().listHistory(interestLevel=1,
                                                    type='skinCluster')
        # filters out the bug where if a geo has a lattice which is skinned,
        # you get the lattice influences back instead.
        correctSkins = [
            skin for skin in skinInputs if eachGeo.name() in
            [sk.getTransform().name() for sk in skin.getGeometry()]
        ]
        for oSkin in correctSkins:
            skinJointList = pm.listConnections(oSkin.matrix, t='joint')
            bindPose = pm.listConnections(skinJointList[0].name(),
                                          d=True,
                                          s=False,
                                          t='dagPose')
            if bindPose:
                if not (pm.referenceQuery(bindPose[0], inr=True)):
                    pm.delete(bindPose[0])
            sourceGeo = pm.skinCluster(oSkin, q=True, g=True)[0]
            pm.skinCluster(oSkin, e=True, ubk=True)
            pm.skinCluster(skinJointList, sourceGeo, ibp=True, tsb=True)
    pm.select(oldSel)
Beispiel #13
0
    def recursiveRefInfo(self, targetRef, parentDict):
        refInfo = {}

        assetName = targetRef.namespace().split(':')[-2]

        # if an object with that name exists multiple times only add the node
        if parentDict.has_key(assetName):
            parentDict[assetName]['nodes'].append(targetRef)
            return

        refInfo['name'] = assetName
        # get visibility
        refLoc = self.getReferenceLocator(targetRef)
        if refLoc:
            refInfo['visibility'] = refLoc.visibility.get()

            # get label visibility
            refInfo['annotation'] = self.findLabel(refLoc).visibility.get()

        refInfo['nodes'] = [targetRef]

        refInfo['children'] = {}
        childRefs = pm.referenceQuery(targetRef, rfn=True, ch=True)

        # if there are no child references return
        if childRefs:
            for childRef in childRefs:
                childRef = pm.PyNode(childRef)
                self.recursiveRefInfo(childRef, refInfo['children'])

        parentDict[assetName] = refInfo
Beispiel #14
0
 def set_model(self):
     model_data = list()
     assets = get_asset_names.get_asset_names()
     if not assets:
         return
     assets = [
         asset.name() for asset in assets if pm.referenceQuery(asset, inr=1)
     ]
     # {'assetName':'goushi','assetType':'asset','assetChildType':'character'}
     for asset in assets:
         asset_child_type, asset_name, temp = asset.split(":")[-1].split(
             "_")
         arg_dict = {
             'assetName': asset_name,
             'assetType': 'asset',
             'assetChildType': ASSET_DICT[asset_child_type]
         }
         shd_version = self.__db.getShadeVersion(arg_dict)
         model_data.append([asset, shd_version])
     self.model = AssetTableModel(model_data)
     self.proxy_model = QSortFilterProxyModel()
     self.proxy_model.setFilterKeyColumn(0)
     self.proxy_model.setDynamicSortFilter(True)
     self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
     self.proxy_model.setSourceModel(self.model)
     self.filter_le.textChanged.connect(self.set_filter)
     self.table_view.setModel(self.proxy_model)
     # delegate
     self.set_item_delegate()
     self.table_view.resizeColumnToContents(0)
Beispiel #15
0
    def copy(self):
        '''
        Description            
            Function for store(copy) the maya objects attributes value.
                        
            :Type - class function                  
            :param  None            
            :return dataList    <dict>    example {'mObect': {'attributes': {'rx': 0.0, 'ry': 0.0}, 'namespace': 'Clifan:'}}                   
            :example to execute            
                from smartCopy import mayaPose
                reload(mayaPose)
                objects = pymel.ls(sl=1)
                mp= mayaPose.MayaPose(objects=objects)
                poseData = mp.copy()
        '''

        if not self._mObjects:
            warnings.warn(
                'function set \"copy\" _mObjects attribute value is none, update the _mObjects attribute value'
            )
            return None

        dataList = {}

        for eachObject in self._mObjects:
            currentNamespace = 'None'
            currentObject = eachObject.name()

            if pymel.referenceQuery(eachObject, inr=True):
                currentNamespace = eachObject.namespace()
                currentObject = eachObject.name().replace(currentNamespace, '')

            attriList = eachObject.listAttr(r=True,
                                            w=True,
                                            k=True,
                                            u=True,
                                            v=True,
                                            m=True,
                                            s=True)

            if not attriList:
                print 'attributes are does not exists', eachObject.name()
                continue

            attributeData = {}
            for eachAttri in attriList:
                currentValue = eachAttri.get()
                attributeData.setdefault(eachAttri.attrName().encode(),
                                         currentValue)

            controlDatas = {
                'namespace': currentNamespace.encode(),
                'attributes': attributeData
            }

            dataList.setdefault(currentObject, controlDatas)

        pprint.pprint(dataList)

        return dataList
Beispiel #16
0
def listCharacterReferences():
    namespaces = []
    for ref in core.ls(type="reference"):
        try:
            isLoaded = core.referenceQuery(ref, isLoaded=True)
        except:
            continue

        if not isLoaded:
            continue

        ns = core.referenceQuery(ref, shn=True, namespace=True)
        if core.objExists(ns+":M_spine_fk_1_control"):
            namespaces.append(ns)

    return namespaces
Beispiel #17
0
    def getReferenceXform(self, node):
        xform = None
        wform = None
        if isinstance(node, type('')):
            try:
                node = pm.PyNode(node)
            except:
                pm.warning('Can not figure out what ' + str(node) +
                           ' is, ignored!')
                return xfrom

        if pm.referenceQuery(node, isNodeReferenced=True):
            g_ctrl = self.getGlobalCtrl(node)
            if g_ctrl:
                xform = pm.xform(g_ctrl,
                                 query=True,
                                 matrix=True,
                                 objectSpace=True)
                wform = pm.xform(g_ctrl,
                                 query=True,
                                 matrix=True,
                                 worldSpace=True)
        elif node.nodeType() == 'assemblyReference':
            xform = pm.xform(node, query=True, matrix=True, objectSpace=True)
            wform = pm.xform(node, query=True, matrix=True, worldSpace=True)

        return xform, wform
Beispiel #18
0
def duplicateReference():
	'''
	Duplicate Reference and snap it to position of original
	'''
	item = pm.selected()[0]
	if pm.referenceQuery(item, inr=True)
		ref_node = pm.referenceQuery(item, rfn=True)
		ref_path = pm.FileReference(ref_node).path

		ref_ns = pm.referenceQuery(item, ns=True)
		ref_dup = pm.createReference(ref_path, ns=ref_ns + '1')
		# get root node
		ref_dup.selectAll()
		root_node = pm.selected()[0].root()
		# snap
		pm.delete(pm.parentConstraint(item, root_node, mo=0))
Beispiel #19
0
def move_selected_attr(down):
    """
    Move all selected attributes in the channel box down (or up if down is false).
    """
    attrs = [pm.PyNode(n) for n in pm.mel.eval('selectedChannelBoxPlugs')]
    if not attrs:
        log.info('Select one or more attributes in the channel box')
        return

    # Attributes might be selected on more than one node.  Group them by node and process
    # them separately.
    nodes = {attr.node() for attr in attrs}
    for node in nodes:
        if pm.referenceQuery(node, isNodeReferenced=True):
            log.error('Can\'t reorder attributes on referenced node: %s', node)
            continue

        # listAttrs returns long names, so be sure to use longName here too.
        selected_attrs = [
            attr.longName() for attr in attrs if attr.node() == node
        ]
        all_attrs = pm.listAttr(node, userDefined=True)

        # Group attributes into three groups: attributes before the selection, the selected
        # attributes, and attributes after the selection.
        #
        # If more than one attribute is being moved and they're not contiguous, we'll lump
        # them together then move the entire group.
        grouped_selected_attrs = []
        added_selected_attrs = False
        group1 = []
        group2 = selected_attrs
        group3 = []
        for attr in all_attrs:
            if attr in selected_attrs:
                added_selected_attrs = True
                continue
            if added_selected_attrs:
                group3.append(attr)
            else:
                group1.append(attr)

        new_list = group1 + group2 + group3

        # If we're moving attributes down, take the first attribute in group3 and put it at the
        # end of group1.  Otherwise, take the last attribute in group1 and put it at the beginning
        # of group3.
        #
        # If there are no elements to move (there's nowhere to move the selection), run the operation
        # anyway so attribute grouping still happens.
        if down and group3:
            group1.append(group3[0])
            group3[:1] = []
        elif not down and group1:
            group3[0:0] = [group1[-1]]
            group1[-1:] = []

        new_attr_list = group1 + group2 + group3
        set_attribute_order(node, new_attr_list)
Beispiel #20
0
def get_namespace(node):
    if is_reference.is_reference(node):
        namespace = pm.referenceQuery(node, namespace=1)
        if namespace == ":":
            namespace = ":".join(node.split(":")[:-1])
    else:
        namespace = ":".join(node.split(":")[:-1])
    return namespace.strip(":")
 def import_references(self, item):
     # import all references in the file
     self.parent.logger.info(
         "Importing references in the current session...")
     references = pm.ls(references=1)
     for reference in references:
         cmds.file(pm.referenceQuery(reference, f=True),
                   importReference=True)
Beispiel #22
0
 def test_live_edits_returning_an_empty_list(self):
     """testing if the le=True or liveEdits=True with no reference edit will
     return an empty list
     """
     # create a new reference with no edits
     ref = pm.createReference(self.sphereFile, namespace='sphere')
     edits = pm.referenceQuery(ref, es=1, le=1)
     self.assertEqual(edits, [])
    def getReferencePass(self, node):
        look_pass = ''
        if pm.referenceQuery(node, isNodeReferenced=True):
            g_ctrl = self.getGlobalCtrl(node)
            if g_ctrl and g_ctrl.hasAttr('lookPass'):
                look_pass = g_ctrl.getAttr('lookPass', asString=True)

        return look_pass
Beispiel #24
0
 def test_live_edits_returning_an_empty_list(self):
     """testing if the le=True or liveEdits=True with no reference edit will
     return an empty list
     """
     # create a new reference with no edits
     ref = pm.createReference(self.sphereFile, namespace='sphere')
     edits = pm.referenceQuery(ref, es=1, le=1)
     self.assertEqual(edits, [])
Beispiel #25
0
    def test_failed_ref_edits(self):
        self.createFailedEdits()

        sphereRefs = [x for x in pm.listReferences(recursive=True)
                      if x.path.endswith('sphere.ma')]
        for ref in sphereRefs:
            print "testing failed ref edits on: %s" % ref
            self.assertEqual(1, len(pm.referenceQuery(ref,successfulEdits=False,failedEdits=True,es=True)))
            self.assertEqual(1, len(cmds.referenceQuery(str(ref.refNode), successfulEdits=False,failedEdits=True,es=True)))
Beispiel #26
0
    def test_failed_ref_edits(self):
        self.createFailedEdits()

        sphereRefs = [x for x in pm.listReferences(recursive=True)
                      if x.path.endswith('sphere.ma')]
        for ref in sphereRefs:
            print "testing failed ref edits on: %s" % ref
            self.assertEqual(1, len(pm.referenceQuery(ref,successfulEdits=False,failedEdits=True,es=True)))
            self.assertEqual(1, len(cmds.referenceQuery(str(ref.refNode), successfulEdits=False,failedEdits=True,es=True)))
def change_path(node_type, attr_name, mapping, rep_path, dicts):

    maya_proj_paht = cmds.workspace(q=True, fullName=True)
    source_path = "%s/sourceimages" % (maya_proj_paht)
    scenes_path = "%s/scenes" % (maya_proj_paht)
    data_path = "%s/data" % (maya_proj_paht)
    register_node_types = pm.ls(nodeTypes=1)
    if node_type in register_node_types:
        all_node = pm.ls(type=node_type)
        if len(all_node) != 0:
            print "the  node type  is %s" % (node_type)
            for node in all_node:
                if node.hasAttr(attr_name):
                    #file_path = cmds.getAttr(node + "."+attr_name)
                    refcheck = pm.referenceQuery(node, inr=True)
                    #print "refcheck %s " % (refcheck)
                    if (refcheck == False):
                        try:
                            node.attr(attr_name).set(l=0)
                        except Exception, error:
                            print Exception, ":", error
                            pass
                    file_path = node.attr(attr_name).get()
                    if file_path != None and file_path.strip() != "":
                        file_path = file_path.replace('\\', '/')
                        file_path = file_path.replace('<udim>', '1001')
                        file_path = file_path.replace('<UDIM>', '1001')
                        if os.path.exists(file_path) == 0:
                            asset_name = os.path.split(file_path)[1]
                            file_path_new = file_path
                            if rep_path:
                                file_path_new = "%s/%s" % (rep_path,
                                                           asset_name)
                            if os.path.exists(file_path_new) == 0 and mapping:
                                for repath in mapping:
                                    if mapping[repath] != repath:
                                        if file_path.find(repath) >= 0:
                                            file_path_new = file_path.replace(
                                                repath, mapping[repath])

                            if os.path.exists(file_path_new) == 0:
                                file_path_new = "%s/%s" % (source_path,
                                                           asset_name)
                            if os.path.exists(file_path_new) == 0:
                                file_path_new = "%s/%s" % (scenes_path,
                                                           asset_name)
                            if os.path.exists(file_path_new) == 0 and dicts:
                                if asset_name in dicts:
                                    file_path_new = dicts[asset_name]

                            if os.path.exists(file_path_new) == 0:
                                print "the %s node %s  %s is not find ::: %s " % (
                                    node_type, node, attr_name, file_path)
                            else:
                                cmds.setAttr((node + "." + attr_name),
                                             file_path_new,
                                             type="string")
Beispiel #28
0
def exportReferences(destination,
                     tag=None,
                     selectionMode=False,
                     startFrame=1,
                     endFrame=1):
    if selectionMode:
        selection = reference_selection.getSelectedReferences()
    else:
        selection = reference_selection.getLoadedReferences()

    if selection is None:
        return

    abcFiles = []

    for ref in selection:
        # refNodes = cmds.referenceQuery(unicode(ref), nodes=True)
        refPath = pm.referenceQuery(unicode(ref), filename=True)
        print 'the refpath', refPath
        refNodes = pm.referenceQuery(unicode(refPath), nodes=True)
        print 'the refNode', refNodes
        rootNode = pm.ls(refNodes[0])[0]
        print 'rootNode', rootNode
        refAbcFilePath = os.path.join(destination,
                                      getFilenameForReference(rootNode))
        print refAbcFilePath
        try:
            if tag is None:
                command = buildAlembicCommand(refAbcFilePath,
                                              startFrame,
                                              endFrame,
                                              geoList=[rootNode])
            else:
                command = buildTaggedAlembicCommand(rootNode, refAbcFilePath,
                                                    tag, startFrame, endFrame)
            print 'Command:', command
        except NoTaggedGeo, e:
            message_gui.error('Unable to locate Alembic Export tag for ' +
                              str(ref),
                              title='No Alembic Tag Found')
            return
        print 'Export Alembic command: ', command
        pm.Mel.eval(command)
        abcFiles.append(refAbcFilePath)
Beispiel #29
0
def isTopLevelReference(ref):
    """
    Return True if the given file reference's parent is the scene

    Args:
        ref: A reference node
    """
    if ref is None:
        return False
    return pm.referenceQuery(ref, rfn=True, tr=True) == ref.refNode
def nameRef():
    all_ref = pm.listReferences()
    print all_ref[0]

    refNode = pm.referenceQuery(all_ref[0], rfn=True)
    refPath = pm.referenceQuery(all_ref[0], f=True, un=True)

    if refPath != '$AVATARS_V3_PERFORCE_DEPOT/rig/Avatar_Rig.ma':
        print 'FIX PATH'
        pm.system.cmds.file('$AVATARS_V3_PERFORCE_DEPOT/rig/Avatar_Rig.ma',
                            loadReference=refNode,
                            type="mayaAscii",
                            options="v=0")

    for ref in all_ref:
        if ref.namespace == 'Avatar_Rig':
            print 'already good'
        else:
            ref.namespace = 'Avatar_Rig'
 def isOverrideAR(self, m):
     if not pm.referenceQuery(m,isNodeReferenced=1):return False
     ref = m.referenceFile()
     if not ref:return False
     refNode = ref.refNode
     if not refNode:return False
     if pm.hasAttr(refNode,'AROrign'):
         print pm.getAttr(refNode.name()+'.AROrign')
         return True
     return False
Beispiel #32
0
    def getReferenceNodeFromObject(self, obj):
        refNodeName = None
        refNode = None
        try:
            refNodeName = pm.referenceQuery(obj, rfn=True, tr=True)
        except:
            if obj: refNodeName = obj.namespace()[:-1] + 'RN'

        if refNodeName: refNode = pm.ls(refNodeName)[0]

        return refNode
Beispiel #33
0
def swapReferenceWithImport( obj=None, *a ):
    """ Based on the namespace of the current (referenced) selection, this 
        command does the following:
        - Removes the referenced scene completely
        - Imports the same scene into the default namespace """
    
    confirm = pm.confirmDialog(title='You sure?',
                 message="""This script will remove the selected reference
and its edits, then import it back in.  This cannot be undone so make sure
that you've saved your working file.""",
                 button=['OK','Cancel'],
                 defaultButton='OK',
                 dismissString='Cancel'
                 )
    if confirm == 'Cancel':
        return False
    
    if not obj:
        obj = select.single()
        if not obj:
            return False
    
    if not obj.nodeType() == 'transform':
        return False
    
    if not pm.referenceQuery(obj, rfn=True):
        pm.warning('Select a referenced asset!')
        return False
    
    asset_path = pm.referenceQuery(obj, f=True)
    
    try:
        ref_node = str(obj.split(':')[0]+'RN')
        cmds.file(removeReference=True, referenceNode=ref_node)
    except:
        pm.warning('Could not find RN node.  You may have to remove this one manually.')
        return False
    
    imp = pm.importFile(asset_path, defaultNamespace=True)
    
    return imp
Beispiel #34
0
def create_reference(path,
                     namespace_name=":",
                     allow_repeat=False,
                     get_group=False):
    result = None
    path = path.replace("\\", "/")
    if path.endswith(".abc"):
        load_plugin.load_plugin("AbcImport.mll")
    file_type = get_file_type(path)
    if allow_repeat:
        result = pm.system.createReference(path,
                                           loadReferenceDepth="all",
                                           mergeNamespacesOnClash=False,
                                           namespace=namespace_name,
                                           type=file_type)
    else:
        references = pm.listReferences()
        if not references:
            print "*" * 100
            result = pm.system.createReference(path,
                                               loadReferenceDepth="all",
                                               ignoreVersion=1,
                                               gl=1,
                                               options="v=0",
                                               mergeNamespacesOnClash=True,
                                               namespace=namespace_name,
                                               type=file_type)
        else:
            reference_paths = [ref.path for ref in references]
            if path not in reference_paths:
                result = pm.system.createReference(path,
                                                   loadReferenceDepth="all",
                                                   mergeNamespacesOnClash=True,
                                                   namespace=namespace_name,
                                                   type=file_type)
            else:
                ref_node = pm.referenceQuery(path, referenceNode=1)
                if not pm.referenceQuery(ref_node, isLoaded=1):
                    pm.system.loadReference(path)
    if get_group:
        return pm.referenceQuery(result.refNode, dagPath=1, nodes=1)[0]
Beispiel #35
0
def getReferenceNode( *nodes ):
    if nodes:
        pm.select(nodes)    
    nodes = pm.ls(sl=True)
    if not nodes:
        raise
        
    refNodes = []    
    # 알아오기
    for node in nodes:

        # 레퍼런스가 아니면 제낌
        if not pm.referenceQuery( node, isNodeReferenced=True ):
            continue

        refNode = pm.referenceQuery( node, referenceNode=True )
        refNode = pm.PyNode( refNode )
        refNodes.append( refNode )
    
    # 중복 파일 제거
    refNodes = list(set(refNodes))

    return refNodes
    def is_reference(self, node):
        """
        Check if mobject that the pynode refers to is referenced.
        Return False or True.
        """

        #reference check
        if (pm.referenceQuery(node, isNodeReferenced = True)):

            #log
            self.logger.debug('Node {0} is referenced.'.format(node.name()))
            return True

        #return
        return False
Beispiel #37
0
def getReferenceFilepath( *nodes ):
    if nodes:
        pm.select(nodes)    
    nodes = pm.ls(sl=True)
    if not nodes:
        raise
    
    refNodes = getReferenceNode( nodes )
    
    # 알아오기
    filePaths = []
    for refNode in refNodes:
        filePath = pm.referenceQuery( refNode, filename=True )
        filePaths.append( filePath )
    
    return filePaths
    def _action_execute(self):
        """
        Manage the different action that can happen on the tool. Will change depending on the selection
        """
        if (self.action == "#create"):

            if pymel.referenceQuery(self.nSelDriven, isNodeReferenced=True):
                bCreateParent = False
            else:
                bCreateParent = not self.ui.chkUseParent.isChecked()
            pNewSp = SpaceSwitcherLogic()
            with pymel.UndoChunk():
                if self.aSelDrivers:
                    pNewSp.setup_space_switch(self.nSelDriven, self.aSelDrivers, bCreateWolrdNode=False, bCreateParent=bCreateParent)
                else: #There is no drivers, so the user want the world to be one of them
                    pNewSp.setup_space_switch(self.nSelDriven, self.aSelDrivers, bCreateWolrdNode=True, bCreateParent=bCreateParent)
            self._update_parentList(pNewSp)
            pNewSp.pNetwork = libSerialization.export_network(pNewSp)
            self.aSceneSpaceSwitch.append(pNewSp)
            pymel.select(self.nSelDriven)

        elif (self.action == "#add"):
            self.pSelSpSys.add_target(self.aSelDrivers)
            self._update_parentList(self.pSelSpSys)
            #Delete the old network before updating a new one
            if (self.pSelSpSys.pNetwork):
                pymel.delete(self.pSelSpSys.pNetwork)
                self.pSelSpSys.pNetwork = None
            self.pSelSpSys.pNetwork = libSerialization.export_network(self.pSelSpSys)
            pymel.select(self.nSelDriven)

        elif (self.action == "#switch"):
            pCurParent = self.ui.lstParent.selectedIndexes()[0]
            #Remove one to the index since the original parent doesn't really exist in the list of parent in the system
            self.pSelSpSys.do_switch(pCurParent.row() - 1)

        elif (self.action == "#remove"):
            for iIdx in self.toRemove:
                self.pSelSpSys.remove_target(iIdx - 1)

            #Check if it worth it to keep the system, if not, delete the network and parent constraint
            if not self.pSelSpSys.aDrivers:
                self.aSceneSpaceSwitch.remove(self.pSelSpSys)
                if (self.pSelSpSys.nSwConst):
                    pymel.delete(self.pSelSpSys.nSwConst)
                if (self.pSelSpSys.pNetwork):
                    pymel.delete(self.pSelSpSys.pNetwork)

                #Return to the create state action since the node is still selected, but everything is deleted
                self.action = "#create"
                self.ui.lblStatus.setText("Driven Node --> " + str(self.nSelDriven) + "")
                self.ui.lblStatus.setText(self.ui.lblStatus.text() + " " + self.colorTemplate.format("yellow", "(First Setup)"))
                self.ui.btnAction.setEnabled(True)
                self.ui.btnAction.setText("Setup Space Switch System for [" + self.nSelDriven.name() + "]")
            else:
                if (self.pSelSpSys.pNetwork):
                    pymel.delete(self.pSelSpSys.pNetwork)
                    self.pSelSpSys.pNetwork = None
                self.pSelSpSys.pNetwork = libSerialization.export_network(self.pSelSpSys)
                pymel.select(self.nSelDriven)

            self._update_parentList(self.pSelSpSys)
    def _selectionChange(self, *args):
        """
        Manage the selection change to know which action the user want to do. The remove action
        need to be implemented another way
        """
        aCurSel = pymel.selected()

        if (len(aCurSel) == 0):
            self.nSelDriven = None
            self.aSelDrivers = []
        elif (len(aCurSel) == 1):
            self.nSelDriven = aCurSel[0]
            self.aSelDrivers = []
        else:
            self.nSelDriven = aCurSel[-1]
            self.aSelDrivers = aCurSel[0:-1]

        self.ui.lblStatus.setText("Driven Node --> " + str(self.nSelDriven) + "")

        if (self.nSelDriven != None):
            if pymel.referenceQuery(self.nSelDriven, isNodeReferenced=True):
                self.ui.chkUseParent.setEnabled(False)
            else:
                self.ui.chkUseParent.setEnabled(True)
            #Look for existing space switcher system
            self.pSelSpSys = None
            for pSp in self.aSceneSpaceSwitch:
                if (pSp.nDriven == self.nSelDriven):
                    self.pSelSpSys = pSp
                    break;
            self._update_parentList(self.pSelSpSys)
            if self.pSelSpSys == None:
                self.action = "#create"
                self.ui.lblStatus.setText(self.ui.lblStatus.text() + " " + self.colorTemplate.format("yellow", "(First Setup)"))
                self.ui.btnAction.setEnabled(True)
                self.ui.btnAction.setText("Setup Space Switch System for [" + self.nSelDriven.name() + "]")
            else:
                if (self.aSelDrivers):
                    self.action = "#add"
                    self.ui.lblStatus.setText(self.ui.lblStatus.text() + " " + self.colorTemplate.format("green", "(Add Parent)"))
                    if not self.pSelSpSys.isParentExist(self.aSelDrivers):
                        self.ui.btnAction.setEnabled(True)
                        sParentList = "("
                        for pParent in self.aSelDrivers:
                            sParentList += "[" + pParent.name() + "]"
                        sParentList += ")"
                        self.ui.btnAction.setText("Add " + sParentList +" as new parent")
                    else:
                        self.ui.btnAction.setEnabled(False)
                        self.ui.btnAction.setText("Remove the node that is already a Driver node of the current system")
                else:
                    #If a parent is selected in the list, active the button to do the switch
                    pSel = self.ui.lstParent.selectedIndexes()
                    self.action = "#switch"
                    self.ui.lblStatus.setText(self.ui.lblStatus.text() + " " + self.colorTemplate.format("green", "(Switch Parent)"))
                    self.ui.btnAction.setEnabled(False)
                    self.ui.btnAction.setText("Select a parent in the list to switch the parent")
                    if (pSel):
                        pSel = pSel[0]
                        self.ui.btnAction.setEnabled(True)
                        self.ui.btnAction.setText("Switch " + self.nSelDriven.name() + " to follow -->" + pSel.data())
        else:
            self.ui.btnAction.setEnabled(False)
            self.ui.chkUseParent.setEnabled(True)
            self.ui.btnAction.setText("Choose a node")
            self._update_parentList(None)
Beispiel #40
0
    def btnCmd(self, *args):    
        if   args[0]=='create':        
            # startPath        = 'X:/2012_CounterStrike2_V2/3D_project/Share/scenes/character'               # 시작 디렉토리
            fileFilter = "Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)"    # 선택 가능한 확장자

            result = pm.fileDialog2( 
                fileFilter        = fileFilter,                   # 선택 가능한 확장자
                dialogStyle       = 1,                                 # 1: 윈도우 스타일, 2: 마야 스타일
                startingDirectory = self.startPath.get(),                   # 시작 디렉토리
                fileMode          = 1                                     # 파일 하나만 선택 하는 모드
                )
                
            if result:    
                self.startPath.set( os.path.dirname(result[0]) )

                res = pm.promptDialog( m='namespace : ', text= Ref.getBasename( result[0] )  )
                
                if res == 'Confirm':
                    print 
                    ns = pm.promptDialog( q=True, text=True)    
                    Ref.refCreate( result[0], namespace=ns )                       # 레퍼런스 생성
                           
        elif args[0]=='reload':
            sel = cmds.ls(sl=True)
            if sel:
                RNs=[]
                for obj in sel:
                    RN = Ref.getReferenceNode( obj )
                    if RN:
                        RNs.append( RN )             # 레퍼런스 노드 이름 알아옴.

                RNs = list(set(RNs))

                if RNs and pm.confirmDialog( m=u' %s\n\n위 레퍼런스(들)를 갱신하겠습니까?'%RNs) == "Confirm":
                    Ref.refReload( RNs  )                                             # 레퍼런스 제거
    
        elif args[0]=='import':
            sel = cmds.ls(sl=True)
            if sel:
                RNs=[]
                for obj in sel:
                    RN = Ref.getReferenceNode( obj )
                    if RN:
                        RNs.append( RN )             # 레퍼런스 노드 이름 알아옴.

                RNs = list(set(RNs))

                if RNs and pm.confirmDialog( m=u' %s\n\n위 레퍼런스(들)를 import 하겠습니까?'%RNs) == "Confirm":
                    Ref.refImport( RNs  )                                             # 레퍼런스 제거
    
        elif args[0]=='replace':         
            # 선택한 오브젝트관련 레퍼런스 파일을, 지정한 파일로 교체
            #
            #
            #startPath        = 'X:/2012_CounterStrike2_V2/3D_project/Share/scenes/character'                       # 시작 디렉토리
            fileFilter = "Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)"    # 선택 가능한 확장자
            sel = cmds.ls(sl=True)
            if sel:
                RNs=[]
                for obj in sel:
                    RN = Ref.getReferenceNode( obj )
                    if RN:
                        RNs.append( RN )             # 레퍼런스 노드 이름 알아옴.

                RNs = list(set(RNs))

                result = pm.fileDialog2( 
                    fileFilter        = fileFilter,                   # 선택 가능한 확장자
                    dialogStyle       = 1,                                 # 1: 윈도우 스타일, 2: 마야 스타일
                    startingDirectory = self.startPath.get(),                   # 시작 디렉토리
                    fileMode          = 1                                     # 파일 하나만 선택 하는 모드
                    )
                    
                if result: 
                    self.startPath.set( os.path.dirname(result[0]).replace('/','\\') )

                    Ref.refReplace( RNs, result[0] )                     # 레퍼런스 교체
                    pm.refresh()
                    pm.confirmDialog( message=u'완료 되었습니다.' )
                else:
                    pm.confirmDialog( message=u'중지 되었습니다.' )
    
        elif args[0]=='remove':         
            RNs = Ref.getReferenceNode( cmds.ls(sl=True) )                    # 선택한 물체에서 레퍼런스 노드 알아옴
            if RNs and pm.confirmDialog( m=u' %s\n\n위 레퍼런스(들)를 삭제하시겠습니까?' % RNs) == "Confirm":
                Ref.refRemove( RNs  )                                         # 레퍼런스 제거
        
        elif args[0]=='browse':
            result = pm.fileDialog2(                            # 디렉토리 선택 모드
                # fileFilter= "Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)", # 선택 가능한 확장자
                dialogStyle       = 1,                                  # 1: 윈도우 스타일, 2: 마야 스타일
                startingDirectory = self.startPath.get(),                       # 시작 디렉토리
                fileMode          = 3                                     # 0: 존재하거나 존재하지 않든 상관 없음 1: 한개의 존재하는 파일, 2: 디렉토리 명( 디렉토리와 파일 둘다 보임), 3: 디렉토리 명( 디렉토리만 보임), 4: 하나 이상의 존재하는 파일
                )
            
            if result:
                self.startPath.set(result[0])
    
        elif args[0]=='state':          
            sel  = cmds.ls(sl=True)
            if sel:
                RNs=[]
                for obj in sel:
                    RN = Ref.getReferenceNode( obj )
                    if RN:
                        RNs.append( RN )             # 레퍼런스 노드 이름 알아옴.

                RNs = list(set(RNs))

                if not RNs:
                    print '# -----------------------------------------------------------------------------------------------'
                    print '# '
                    print u'# 레퍼런스가 아닙니다.'
                    print '# '
                    print '# -----------------------------------------------------------------------------------------------'
                    return

                for RN in RNs:
                    _File = Ref.getFile( RN )                          # 레퍼런스 노드 관련된 이름 알아옴
                    _ns   = pm.referenceQuery( RN, namespace=True )                          # 레퍼런스 노드 관련된 이름 알아옴

                    print '# -----------------------------------------------------------------------------------------------'
                    print '# refNode   : %s'%RN                                    # 해당 파일 오픈 스크립트 출력
                    print '# namespace : %s'%_ns                                    # 해당 파일 오픈 스크립트 출력
                    print '# command   : pm.openFile( "%s", f=True )'%_File      # 해당 파일 오픈 스크립트 출력
                    print '# filePath  : %s'%_File.replace('/','\\')                  # 해당 파일 오픈 스크립트 출력
                    print '# -----------------------------------------------------------------------------------------------'
Beispiel #41
0
def isTopLevelReference(ref):
    """ Return True if the given file reference's parent is the scene """
    if ref is None:
        return False
    return pm.referenceQuery(ref, rfn=True, tr=True) == ref.refNode