コード例 #1
0
    def set_fps(self, fps=25):
        """sets the fps of the environment
        """

        # get the current time, current playback min and max (because maya
        # changes them, try to restore the limits)

        current_time = pm.currentTime(q=1)
        pMin = pm.playbackOptions(q=1, min=1)
        pMax = pm.playbackOptions(q=1, max=1)
        pAst = pm.playbackOptions(q=1, ast=1)
        pAet = pm.playbackOptions(q=1, aet=1)

        # set the time unit, do not change the keyframe times
        # use the timeUnit as it is
        time_unit = u"pal"

        # try to find a timeUnit for the given fps
        # TODO: set it to the closest one
        for key in self.time_to_fps:
            if self.time_to_fps[key] == fps:
                time_unit = key
                break

        pm.currentUnit(t=time_unit, ua=0)
        # to be sure
        pm.optionVar['workingUnitTime'] = time_unit

        # update the playback ranges
        pm.currentTime(current_time)
        pm.playbackOptions(ast=pAst, aet=pAet)
        pm.playbackOptions(min=pMin, max=pMax)
コード例 #2
0
    def importMixamoFbx(self):
        print 'importMixamoFbx'
        pm.newFile(f=1)
        if self.fbxFile:
            if os.path.isfile(self.fbxFile):

                # import the FBX file
                pm.mel.eval('FBXImport -f "' + (self.fbxFile) + '"')
                # clean its namespace
                removeNamespace()
                # self.logger.info('Imported file %s',self.fbxFile)
                hips = pm.ls("Hips", type='joint')

                # add root joint for scale
                rootJnt = pm.joint(n='Root')
                pm.parent(hips[0], rootJnt)
                # self.logger.info('Added root joint %s',rootJnt)

                # clean up textures
                self.cleanUpTextures()
                pm.currentUnit(t='ntsc')
                # add shadow plane

                return 1
            else:
                pm.error('Fbx file %s doesn\'t exist' % self.fbxFile)
                return 0
        else:
            pm.error('No file was given')
            return 0
コード例 #3
0
    def set_pref(project_file_path):
        """
        读取JSON文件,并应用到maya
        Args:
            project_file_path:被读取的JSON的文件的路径

        Returns:
            无
        """
        # 提取项目的配置文件
        with open(project_file_path, "r") as read_conf_file:
            current_conf_file_read = read_conf_file.read()
            current_conf_read = json.loads(current_conf_file_read)

        set_time_unit = current_conf_read["time_unit"]
        set_res_w = current_conf_read["res_width"]
        set_res_h = current_conf_read["res_height"]
        set_device_ratio = current_conf_read["res_device_ratio"]
        set_pixel_ratio = current_conf_read["res_pixel_ratio"]

        # 以配置文件设置maya
        pm.currentUnit(time=set_time_unit)
        pm.PyNode("defaultResolution").deviceAspectRatio.set(set_device_ratio)
        pm.PyNode("defaultResolution").pixelAspect.set(set_pixel_ratio)
        pm.PyNode("defaultResolution").width.set(set_res_w)
        pm.PyNode("defaultResolution").height.set(set_res_h)
コード例 #4
0
ファイル: mayaEnv.py プロジェクト: dshlai/oyprojectmanager
    def set_fps(self, fps=25):
        """sets the fps of the environment
        """

        # get the current time, current playback min and max (because maya
        # changes them, try to restore the limits)

        current_time = pm.currentTime(q=1)
        pMin = pm.playbackOptions(q=1, min=1)
        pMax = pm.playbackOptions(q=1, max=1)
        pAst = pm.playbackOptions(q=1, ast=1)
        pAet = pm.playbackOptions(q=1, aet=1)

        # set the time unit, do not change the keyframe times
        # use the timeUnit as it is
        time_unit = u"pal"

        # try to find a timeUnit for the given fps
        # TODO: set it to the closest one
        for key in self.time_to_fps:
            if self.time_to_fps[key] == fps:
                time_unit = key
                break

        pm.currentUnit(t=time_unit, ua=0)
        # to be sure
        pm.optionVar['workingUnitTime'] = time_unit

        # update the playback ranges
        pm.currentTime(current_time)
        pm.playbackOptions(ast=pAst, aet=pAet)
        pm.playbackOptions(min=pMin, max=pMax)
コード例 #5
0
    def importMixamoFbx(self):
        print "importMixamoFbx"
        pm.newFile(f=1)
        if self.fbxFile:
            if os.path.isfile(self.fbxFile):

                # import the FBX file
                pm.mel.eval('FBXImport -f "' + (self.fbxFile) + '"')
                # clean its namespace
                removeNamespace()
                # self.logger.info('Imported file %s',self.fbxFile)
                hips = pm.ls("Hips", type="joint")

                # add root joint for scale
                rootJnt = pm.joint(n="Root")
                pm.parent(hips[0], rootJnt)
                # self.logger.info('Added root joint %s',rootJnt)

                # clean up textures
                self.cleanUpTextures()
                pm.currentUnit(t="ntsc")
                # add shadow plane

                return 1
            else:
                pm.error("Fbx file %s doesn't exist" % self.fbxFile)
                return 0
        else:
            pm.error("No file was given")
            return 0
コード例 #6
0
    def importMixamoFbx(self) :
        print 'importMixamoFbx'
        pm.newFile(f=1)
        if self.fbxFile:
            if os.path.isfile(self.fbxFile):

                #import the FBX file
                pm.mel.eval( 'FBXImport -f "' + (self.fbxFile) + '"')
                #check for a default mesh in T-Pose. If found, replace geometry
                self.replaceGeometry()

                #clean its namespace
                removeNamespace()
                hips = pm.ls("Hips",type='joint')

                #add root joint for scale
                rootJnt = pm.joint(n='Root')
                pm.parent(hips[0],rootJnt)

                #clean up textures
                self.cleanUpTextures()
                pm.currentUnit(t='ntsc')

                return 1
            else:
                pm.error('Fbx file %s doesn\'t exist'%self.fbxFile)
                return 0
        else:
            pm.error('No file was given')
            return 0
コード例 #7
0
def makeDynamic(pickedBone):
    if sceneUnit!='cm':
        pm.currentUnit(l='cm')
    if pm.nodeType(pickedBone)=='joint':
        boneChain = getBoneChain(pickedBone)
    else:
        boneObs = createBone(pickedBone)
        boneChain=getBoneChain(boneObs[0][0])
        print pickedBone,boneObs,boneChain
    if not boneChain:
        return
    pm.select([boneChain[0],boneChain[len(boneChain)-1]],r=True)
    driveJointsWithHair(detailValue,falloffValue)
    hairHandle=pm.ls('hairHandle1')[0]
    hairHandle.setAttr("hairDamping",dampValue)
    hairHandle.setAttr("hairStiffness",stiffValue)
    if pm.nodeType(pickedBone)=='joint':
        pm.bakeResults(pickedBone,at=['rotate'],hi='below',sm=True,t=getTimeRange())
        pm.delete('dynJoint*','nucleus*','follicle*')
    else:
        for o in boneObs:
            if o[1]:
                pm.bakeResults(o[1],at=['rotate'],t=getTimeRange(),sm=True)
        pm.delete(boneChain,'dynJoint*','nucleus*','follicle*',hi='below')
    pm.currentUnit(l=sceneUnit)
コード例 #8
0
ファイル: common.py プロジェクト: jzboylxj/XDLibs
def set_time_unit(unit='ntsc'):
    current_unit = pm.currentUnit(q=True, time=True)
    if current_unit == unit:
        return
    else:
        current_unit = pm.currentUnit(time=unit)
        pm.playbackOptions(min=0)
        return
コード例 #9
0
ファイル: bs_shot.py プロジェクト: amolrupnar/bsPipe
def bs_shotBuild(epi, seq, shot, startTime, endTime, assetPaths):
    """
    @
    Args:
        epi (str): episode name like "ep001"
        seq (str): sequence name like "sq001"
        shot (str): shot name like "sh001"
        startTime (int): animation start time.
        endTime (int): animation end time.
        assetPaths (list): all assets path in list.

    Returns:
            None.
    """
    # set current time and unit.
    pm.currentUnit(time='pal')
    pm.playbackOptions(ast=startTime,
                       aet=endTime,
                       maxTime=endTime,
                       minTime=startTime)
    pm.currentTime(startTime)
    # create Hierarchy.
    shotGroup = pm.createNode('transform', n='shot_grp', ss=True)
    charGroup = pm.createNode('transform', n='char_grp', ss=True)
    propGroup = pm.createNode('transform', n='prop_grp', ss=True)
    setGroup = pm.createNode('transform', n='set_grp', ss=True)
    vehicleGroup = pm.createNode('transform', n='vehicle_grp', ss=True)
    fxGroup = pm.createNode('transform', n='fx_grp', ss=True)
    pm.parent(charGroup, propGroup, setGroup, vehicleGroup, fxGroup, shotGroup)
    # import camera.
    camFilePath = bs_pathGenerator.bs_getConfigPaths(
    ) + 'mayaFiles/shot_cam.ma'
    bs_mayaFile.bs_importFile(camFilePath)
    pm.parent('cam_grp', shotGroup)
    # add attributes.
    pm.addAttr(shotGroup, ln='bsw_episode', dt='string', k=True)
    pm.addAttr(shotGroup, ln='bsw_sequence', dt='string', k=True)
    pm.addAttr(shotGroup, ln='bsw_shot', dt='string', k=True)
    pm.addAttr(shotGroup, ln='bsw_stage', dt='string', k=True)
    # set Values.
    pm.setAttr(shotGroup + '.bsw_episode', epi)
    pm.setAttr(shotGroup + '.bsw_episode', l=True)
    pm.setAttr(shotGroup + '.bsw_sequence', seq)
    pm.setAttr(shotGroup + '.bsw_sequence', l=True)
    pm.setAttr(shotGroup + '.bsw_shot', shot)
    pm.setAttr(shotGroup + '.bsw_shot', l=True)
    pm.setAttr(shotGroup + '.bsw_stage', 'lay')
    pm.setAttr(shotGroup + '.bsw_stage', l=True)
    # add assets sets in one categorized set.
    pm.select(cl=True)
    mainSet = pm.sets(n='Assets_Set')
    charSet = pm.sets(n='Char_Set')
    propSet = pm.sets(n='Prop_Set')
    setSets = pm.sets(n='Set_Sets')
    vehicleSets = pm.sets(n='Vehicle_Sets')
    mainSet.addMembers([charSet, propSet, setSets, vehicleSets])
    bs_referenceAssetsInCurrentShot(assetPaths)
コード例 #10
0
def loadDefaults():
    """
    Loads the settings to use in Maya
    """
    # change grid, time, units, and playback options
    pm.currentUnit(time=pcfg.maya_default_time)
    pm.grid(size=1200, spacing=500, divisions=5)
    pm.playbackOptions(min=0, max=30)
    pm.currentTime(0)
    pm.currentUnit(linear=pcfg.maya_default_length)
コード例 #11
0
 def wrapper(*args, **kwargs):
     scene_unit = pm.currentUnit(query=True, linear=True)
     if scene_unit != 'cm':
         pm.currentUnit(linear='cm')
     try:
         result = func(*args, **kwargs)
     finally:
         if scene_unit != 'cm':
             pm.currentUnit(linear=scene_unit)
     return result
コード例 #12
0
    def saveRenderFile(self, forAnim, cacheFolder, log):
        lightingFolder = pm.optionVar.get('lightingFolderString', '')
        lightingString = pm.optionVar.get('lightingString', '')
        animString = pm.optionVar.get('animString', '')

        timeUnit = pm.currentUnit(q=1, time=True)
        startTime = pm.playbackOptions(query=True, minTime=True)
        endTime = pm.playbackOptions(query=True, maxTime=True)

        print 'Saving render file asfasfasfsfasf'
        pm.newFile(force=True)
        pm.currentUnit(time=timeUnit)
        pm.currentTime(startTime, edit=True)

        pm.playbackOptions(ast=startTime)
        pm.playbackOptions(aet=endTime)
        pm.playbackOptions(minTime=startTime)
        pm.playbackOptions(maxTime=endTime)

        workspace = pm.workspace.path
        print workspace
        print forAnim

        animRoot = forAnim.replace('\\', '/').replace(workspace, '')
        lightingFile = animRoot.split('/')[-1].replace(animString,
                                                       lightingString)

        foldersToFile = animRoot.split('/')[2:-1]

        for folder in foldersToFile:
            if not os.path.isdir(os.path.join(lightingFolder, folder)):
                os.mkdir(os.path.join(lightingFolder, folder))
                lightingFolder = os.path.join(lightingFolder, folder)
            else:
                lightingFolder = os.path.join(lightingFolder, folder)

        fullPath = os.path.join(lightingFolder, lightingFile)

        f, ext = os.path.splitext(lightingFile)
        print ext
        filetype = 'mayaAscii'
        if ext == '.mb':
            filetype = 'mayaBinary'

        pm.saveAs(fullPath, f=1, type=filetype)
        for reference in self.exportReferences:
            self.importAlembic(reference[1], reference[2], cacheFolder)

        for cam in self.userCameras:
            self.importAlembicCamera(cam, cacheFolder)

        pm.saveFile()
コード例 #13
0
ファイル: startupCmd.py プロジェクト: amolrupnar/bsPipe
def runInitialStartup():
    """
    @ run this function on maya start.
    Returns:
            None.
    """
    # load plugings.
    # pm.loadPlugin('mtoa')
    # set fps.
    pm.currentUnit(time='pal')
    print('SUCCESS MAYA OPEN WITH PRE LOADED SETTING...............'),
    bs_qui.bs_displayMessage(
        'success', 'SUCCESS MAYA OPEN WITH PRE LOADED SETTING...............')
コード例 #14
0
ファイル: lcGeometry.py プロジェクト: leocov-dev/lct-legacy
    def shrinkWrap(cls, verts, mesh, progBarList=None, *args, **kwargs):
        ''' '''
        # print'mesh: {}'.format(mesh)
        currentUnit = pm.currentUnit(query=True, linear=True)

        for bar in progBarList:
            pm.progressBar(bar, edit=True, endProgress=True)
            pm.progressBar(bar, edit=True, beginProgress=True, isInterruptable=True, maxValue=len(verts), en=True,
                           status='Running . . .')

        if mesh:
            # closestNode = pm.createNode('closestPointOnMesh')
            # pm.connectAttr(mesh.worldMesh[0], closestNode.inMesh)
            # pm.connectAttr(mesh.worldMatrix[0], closestNode.inputMatrix)

            pm.currentUnit(linear='cm')
            for vert in verts:
                vert = pm.PyNode(vert)

                if pm.progressBar(progBarList[0], query=True, isCancelled=True):
                    for bar in progBarList:
                        pm.progressBar(bar, edit=True, en=False)
                    break
                else:
                    # print 'vert: {}'.format(vert)
                    # vertPos = pm.pointPosition(vert, w=True)
                    vertPos = vert.getPosition(space='world')
                    # print 'vertPos: {}'.format(vertPos)
                    # closestNode.inPosition.set(vertPos)
                    # meshPos = closestNode.position.get()
                    meshPos = mesh.getClosestPoint(vertPos, space='world')[0]
                    # print 'meshPos: {}'.format(meshPos)

                    vert.setPosition(meshPos, space='world')
                    # pm.move(vert, meshPos, ws=True)
                    # vertPos2 = pm.pointPosition(vert, w=True)
                    # print 'vertPos2: {}'.format(vertPos2)

                    for bar in progBarList:
                        pm.progressBar(bar, edit=True, step=1)

            pm.currentUnit(linear=currentUnit)
            # pm.delete(closestNode)
            for bar in progBarList:
                pm.progressBar(bar, edit=True, en=False)
                pm.progressBar(bar, edit=True, endProgress=True)
        else:
            pm.warning('No verts selected')
コード例 #15
0
 def setCurrentLinearUnit(unit=("StringPin", "cm", {
     "ValueList": [
         "mm", "millimeter", "cm", "centimeter", "m", "meter", "km",
         "kilometer", "in", "inch", "ft", "foot", "yd", "yard", "mi", "mile"
     ]
 })):
     return pm.currentUnit(linear=unit)
コード例 #16
0
    def save_pref(project_file_path):
        """
        读取当前maya文件的配置,并保存JSON文件
        Args:
            project_file_path: 被保存JSON的文件的路径

        Returns:
            无

        """
        # 读取当前文件配置
        current_time_unit = pm.currentUnit(query=True, time=True)
        current_res_width = pm.PyNode("defaultResolution").width.get()
        current_res_height = pm.PyNode("defaultResolution").height.get()
        current_device_ratio = pm.PyNode(
            "defaultResolution").deviceAspectRatio.get()
        current_pixel_ratio = pm.PyNode("defaultResolution").pixelAspect.get()
        current_pref = {
            "time_unit": current_time_unit,
            "res_width": current_res_width,
            "res_height": current_res_height,
            "res_device_ratio": current_device_ratio,
            "res_pixel_ratio": current_pixel_ratio
        }

        current_conf = json.dumps(current_pref, sort_keys=True, indent=4)

        # 写入当前配置到文件
        with open(project_file_path, "w") as current_pref_file:
            current_pref_file.write(current_conf)
コード例 #17
0
def get_scene_fps():
    '''
    Gets the FPS that the scene is set to

    Returns:
        float. FPS value
    '''
    time = pm.currentUnit(q=True, t=True)
    
    if(time == 'game'):
        return 15.0
    elif(time == 'film'):
        return 24.0
    elif(time == 'pal'):
        return 25.0
    elif(time == 'ntsc'):
        return 30.0
    elif(time == 'show'):
        return 48.0
    elif(time == 'palf'):
        return 50.0
    elif(time == 'ntscf'):
        return 60.0
    else:
        print time
コード例 #18
0
ファイル: display.py プロジェクト: kinetifex/maya-kinetifex
def _getCurrentTime():
    #currentFrame = str( currentTime(query=True) )

    currentFrame = pm.currentTime( query=True )

    rate = __time_values[pm.currentUnit( q=1, time=1 )]

    return currentFrame / rate
コード例 #19
0
    def bdExportAll(self):
        timeUnit = pm.currentUnit(q=1, time=True)
        startTime = pm.playbackOptions(query=True, minTime=True)
        endTime = pm.playbackOptions(query=True, maxTime=True)

        animFileFullPath = pm.sceneName()
        animFileRelative = pm.sceneName().replace(projectPath, '')

        self.cachePath = self.bdGetCachePath(animFileRelative)

        loadedReferences = {}

        for i in range(self.referencesTableWidget.rowCount()):
            if self.referencesTableWidget.item(i, 0).text() == 'True':
                ns = self.referencesTableWidget.item(i, 1).text()
                nsPath = self.referencesTableWidget.item(i, 2).text()
                loadedReferences[ns] = nsPath

        for ns in loadedReferences.keys():
            self.bdExportAlambic(ns, self.cachePath)

        for i in range(self.camerasTableWidget.rowCount()):
            if self.camerasTableWidget.item(i, 0).text() == 'True':
                self.bdExportCameras(self.camerasTableWidget.item(i, 1).text())

        if self.saveRenderCheckBox.isChecked():

            pm.newFile(force=True)
            pm.currentUnit(time=timeUnit)
            pm.currentTime(startTime, edit=True)

            pm.playbackOptions(ast=startTime)
            pm.playbackOptions(aet=endTime)
            pm.playbackOptions(minTime=startTime)
            pm.playbackOptions(maxTime=endTime)

            for ns in loadedReferences:
                fileName = loadedReferences[ns]
                self.bdImportAlambic(ns, fileName, self.cachePath)

            for cam in self.cameras:
                self.bdImportCamera(cam)

            self.animFile = animFileRelative
            self.bdSaveRenderFile()
コード例 #20
0
def convert_scene_units(value):
    '''
    Default scene units for the toolset are 'cm'.  Convert any scene unit use to scale appropriately to this assumption
    '''
    return_value = value
    scene_units = pm.currentUnit(q=True, l=True)
    if scene_units == 'm':
        return_value /= 100.0
    return return_value
コード例 #21
0
 def __exit__(self, *_):
     if self.oldlin is not None:
         pmc.currentUnit(linear=self.oldlin)
     if self.oldang is not None:
         pmc.currentUnit(angle=self.oldang)
     if self.oldtim is not None:
         pmc.currentUnit(time=self.oldtim)
コード例 #22
0
 def __exit__(self, *_):
     if self.oldlin is not None:
         pmc.currentUnit(linear=self.oldlin)
     if self.oldang is not None:
         pmc.currentUnit(angle=self.oldang)
     if self.oldtim is not None:
         pmc.currentUnit(time=self.oldtim)
コード例 #23
0
    def createExportJob(self):
        timeUnit = pm.currentUnit(q=1, time=True)
        startTime = pm.playbackOptions(query=True, minTime=True)
        endTime = pm.playbackOptions(query=True, maxTime=True)

        animFileFullPath = pm.sceneName()
        animFileRelative = pm.sceneName().replace(pm.workspace.name, '')

        self.getCachePath(animFileRelative)

        for i in range(self.referencesTableWidget.rowCount()):
            if self.referencesTableWidget.item(i, 0).text() == 'True':
                ns = self.referencesTableWidget.item(i, 1).text()
                nsPath = self.referencesTableWidget.item(i, 2).text()
                self.loadedReferences[ns] = nsPath

        print self.loadedReferences
        '''
コード例 #24
0
def Get_currentUnit():
    result = 0

    currentUnit = pc.currentUnit(q=True, time=True)
    if currentUnit == "game":
        result = 15
    elif currentUnit == "film":
        result = 24
    elif currentUnit == "pal":
        result = 25
    elif currentUnit == "ntsc":
        result = 30
    elif currentUnit == "show":
        result = 48
    elif currentUnit == "palf":
        result = 50
    elif currentUnit == "ntscf":
        result = 60

    return result
コード例 #25
0
 def testWithUnit(self):
     def assertUnit(kw, ideal):
         self.assertEqual(pmc.currentUnit(q=True, **{kw: True}), ideal)
     pmc.currentUnit(angle='rad')
     pmc.currentUnit(linear='cm')
     pmc.currentUnit(time='sec')
     with with_unit(angle='deg'):
         with with_unit(linear='m'):
             with with_unit(time='min'):
                 assertUnit('angle', 'deg')
                 assertUnit('linear', 'm')
                 assertUnit('time', 'min')
     assertUnit('angle', 'rad')
     assertUnit('linear', 'cm')
     assertUnit('time', 'sec')
コード例 #26
0
    def testWithUnit(self):
        def assertUnit(kw, ideal):
            self.assertEqual(pmc.currentUnit(q=True, **{kw: True}), ideal)

        pmc.currentUnit(angle='rad')
        pmc.currentUnit(linear='cm')
        pmc.currentUnit(time='sec')
        with with_unit(angle='deg'):
            with with_unit(linear='m'):
                with with_unit(time='min'):
                    assertUnit('angle', 'deg')
                    assertUnit('linear', 'm')
                    assertUnit('time', 'min')
        assertUnit('angle', 'rad')
        assertUnit('linear', 'cm')
        assertUnit('time', 'sec')
コード例 #27
0
def get_scene_fps():
    """Get current scene fps as float.

    :rtype: float
    """
    fps_dict = {
        'game': 15.0,
        'film': 24.0,
        'pal': 25.0,
        'ntsc': 30.0,
        'show': 48.0,
        'palf': 50.0,
        'ntscf': 60.0
    }
    non_fps_list = ['hour', 'min', 'sec', 'millisec']

    fps_unicode = pm.currentUnit(q=True, time=True)
    fps_float = fps_dict.get(fps_unicode, None)

    if fps_unicode in non_fps_list:
        return 0.0
    if fps_float is None:
        return float(fps_unicode.replace('fps', ''))
    return fps_float
コード例 #28
0
def main(unit_linear, unit_time, log=None):
    if not log:
        import logging
        log = logging.getLogger()

    # use ' ' as a fill char and center aligned
    log.debug('{0:-<40}'.format('check_unit'))

    # What is the current linear unit?
    #if pm.currentUnit( query=True, linear=True ) != u'cm' :
    if pm.currentUnit(query=True, linear=True) != unit_linear:
        pm.currentUnit(linear=unit_linear)
        log.warning('current linear unit not match:%s' % unit_linear)
    else:
        log.debug('current linear unit match:%s' % unit_linear)

    #if pm.currentUnit( query=True, time=True ) != u'film' :
    if pm.currentUnit(query=True, time=True) != unit_time:
        pm.currentUnit(linear=unit_time)
        log.warning('current time unit not match:%s' % unit_time)
    else:
        log.debug('current time unit match:%s' % unit_time)
コード例 #29
0
ファイル: check_unit.py プロジェクト: hongloull/digital37
def main(unit_linear,unit_time,log=None):
    if not log:
        import logging
        log = logging.getLogger()
    
    # use ' ' as a fill char and center aligned
    log.debug('{0:-<40}'.format('check_unit'))
    
    # What is the current linear unit?
    #if pm.currentUnit( query=True, linear=True ) != u'cm' :
    if pm.currentUnit( query=True, linear=True ) != unit_linear :
        pm.currentUnit(linear=unit_linear)
        log.warning('current linear unit not match:%s' % unit_linear)
    else:
        log.debug('current linear unit match:%s' % unit_linear)
        
    #if pm.currentUnit( query=True, time=True ) != u'film' :
    if pm.currentUnit( query=True, time=True ) != unit_time :
        pm.currentUnit(linear=unit_time)
        log.warning('current time unit not match:%s' % unit_time)
    else:
        log.debug('current time unit match:%s' % unit_time)
コード例 #30
0
def springApply(pickedBone, pickedBones,springLoop=False,springRotateRate=0.3,springTwist=0.3):
    '''
    Get idea from max scripts 'SpringMagic' made by Sichuang Yuan, but make it more friendly with Maya
    '''

    # since maya 2016, there is a new animation evaluation mode called "Parallel" which supose to improve
    # the runtime performance of maya, but the new function seems cause some problem when calculate spring magic.
    # so I'll revert evaluation mode back to old way during calculation and set it back after
    # store evaluationManager mode for 2016 or newer
    if pm.versions.current() > 201600:
        currentMode = pm.evaluationManager( q=1, mode = 1 )[0]
        pm.evaluationManager( mode = 'off' )
    # Check Unit
    if sceneUnit!='cm':
        pm.currentUnit(l='cm')
    # get pickedBone chain, only get one stream, will not process branches
    if pm.nodeType(pickedBone)=='joint':
        boneChain = getBoneChain(pickedBone)
    else:
        boneObs = createBone(pickedBone)
        boneChain=[b[0] for b in boneObs]
        pm.hide(boneChain)
    if not boneChain:
        return
    print pickedBone
    boneRoot = boneChain[0].getParent()
    # get frame range
    pm.currentTime( startFrame, edit=True )

    # get pickedBone chain start pose and key it
    boneStartRotation = {}
    # boneStartMatirx = {}
    for bone in boneChain:
        # reset bone rotate axis as 0
        bone.setRotation = bone.getAttr('rotateAxis')
        pm.xform(bone, ra = [0,0,0])
        # get bone start rotation pose
        boneStartRotation[bone] = bone.getRotation()
        # boneStartMatirx[bone] = bone.getAttr('matrix')

        if not springLoop:
            pm.setKeyframe(bone, attribute = 'rotate')
        # delete key not at start frame
        pm.cutKey( bone, time=(startFrame + 1,endFrame) )

    # get bone start world translation
    boneWorldTranlation = {}
    previousBoneWorldTranlation = {}
    previousBoneWorldRotation = {}
    previousBoneRotateAxis = None

    loopCount = float(springLoop)
    pickedBoneCount = float(len(pickedBones))
    boneChainCount = float(len(boneChain))
    frameCount = float(endFrame-startFrame)
    # caculate part
    for loop in range( int(loopCount+1) ):

        for frame in range( startFrame, endFrame+1 ):

            pm.currentTime( frame, edit=True )

            for bone in boneChain:

                # get bone world translation & matrix
                boneWorldTranlation[bone] = dt.Vector( pm.xform(bone, worldSpace = 1, translation = 1, query = 1) )
                # skip caculate at first frame
                if previousBoneWorldTranlation:
                    # skip end bone
                    if not bone == boneChain[-1]:
                        # get child bone name for caculate
                        childBone = boneChain[boneChain.index(bone) + 1]

                        # get the vector from current position to previous child position
                        boneAimVector = (boneWorldTranlation[bone] - previousBoneWorldTranlation[childBone]).normal()

                        # restore current bone rotation
                        boneCurrentRotation = bone.getRotation()

                        # reset bone to start pose
                        bone.setAttr('rotate', boneStartRotation[bone])

                        childBoneHight = pm.xform( childBone, worldSpace = 1, translation = 1, query = 1 )
                        
                        # get the vector of stance pose
                        stanceTranslation = ( childBone.getAttr('matrix') * childBone.getAttr('parentMatrix') ).translate
                        
                        boneStanceVetor = (boneWorldTranlation[bone] - stanceTranslation).normal()

                        # get rotation axis and degrees bewteen two vectors
                        boneRotateDegrees = math.degrees( boneStanceVetor.angle( boneAimVector ) )
                        boneRotateAxis = boneStanceVetor.axis( boneAimVector )

                        # if the rotate axis fliped
                        if previousBoneRotateAxis:
                            if abs(math.degrees( previousBoneRotateAxis.angle( boneRotateAxis ))) > 90: 
                                # then flip it back
                                boneRotateAxis = -boneRotateAxis
                                boneRotateDegrees = -boneRotateDegrees

                        previousBoneRotateAxis = boneRotateAxis

                        # set rotate rate
                        rotateRate = 1-float(springRotateRate)

                        upVector = dt.Vector(0,1,0)
                        rotateValue = upVector * (boneRotateDegrees*rotateRate)
                        # skip rotate bone if very close to start pose
                        if abs(boneRotateDegrees) > 0.001:

                            # match up bone and stance vector with aim constraint
                            lct = pm.spaceLocator()
                            lct.setTranslation( stanceTranslation )
                            cns = pm.aimConstraint( lct, bone, aimVector = [1,0,0], upVector = upVector, worldUpVector = boneRotateAxis )
                            # keep aim result before remove constraint
                            pm.setKeyframe(bone, attribute = 'rotate')
                            pm.delete( cns, lct )
                            # do rotate bone
                            pm.rotate(bone, rotateValue, objectSpace = 1, relative = 1)

                        else:
                            # use previous frame rotation
                            bone.setAttr('rotate', boneCurrentRotation)
                            pm.setKeyframe(bone, attribute = 'rotate')






                        # apply twist
                        twist = float(springTwist)
                        if 1 > twist:
                            # reset rotat x
                            bone.setAttr('rotateX', boneStartRotation[bone][0] )
                            # creat locator with stance rotation, slow step setMatrix, need optmaize
                            lct = pm.spaceLocator()
                            lct.setRotation(pm.xform(bone,q=1,worldSpace=1,rotation=1))
                            lct_p = pm.spaceLocator()
                            lct_p.setRotation(previousBoneWorldRotation[bone])
                            # get twist delay value
                            # creat orient constraint
                            cns_X = pm.orientConstraint( lct, lct_p, bone, skip = ['y','z'] )

                            # apply twist value to constraint
                            cns_X.setAttr(lct+'W0', twist)
                            cns_X.setAttr(lct_p+'W1', 1-twist)
                            # set rotate interp as shortest
                            cns_X.setAttr('interpType', 2)

                            # get caculated x
                            boneRotateX = bone.getAttr('rotateX')
                            # apply new rotate x
                            bone.setAttr('rotateX', boneRotateX)
                            pm.setKeyframe(bone, attribute = 'rotate')

                            pm.delete( cns_X, lct, lct_p )

                # save for next frame use
                previousBoneWorldRotation[bone] = pm.xform(bone,q=1,worldSpace=1,rotation=1)
                # print previousBoneWorldRotation[bone]
                #runProgressBar( main_progressBar, 1/(loopCount+1)*(1/pickedBoneCount)*(1/boneChainCount)*(1/(frameCount+1))*100 )
            # save for next frame use
            previousBoneWorldTranlation = copy.copy(boneWorldTranlation)
    print pickedBone,boneChain   
    if pm.nodeType(pickedBone)!='joint':
        for o in boneObs:
            if o[1]:
                pm.bakeResults(o[1],at=['rotate'], t=(startFrame,endFrame))
        pm.delete(boneChain)
    #return Unit
    pm.currentUnit(l=sceneUnit)
    # revert evaluationManager mode for 2016 or newer
    if pm.versions.current() > 201600:
        pm.evaluationManager( mode = currentMode )
コード例 #31
0
ファイル: mayaEnv.py プロジェクト: dshlai/oyprojectmanager
    def get_fps(self):
        """returns the fps of the environment
        """

        # return directly from maya, it uses the same format
        return self.time_to_fps[pm.currentUnit(q=1, t=1)]
コード例 #32
0
ファイル: sceneBuild.py プロジェクト: leocadaval/lcPipe
def build(itemType, task, code):
    parcial = False
    empty = True

    item = Item(task=task, code=code, itemType=itemType)

    if not item.source:
        itemList = item.components
    else:
        itemList = item.source

    pm.newFile(f=True, new=True)
    newComponentsDict = {}

    if item.type == 'shot':
        print 'creating camera...'
        cameraItem = Item(task='rig', code='0000', itemType='asset')
        print cameraItem.noData
        if cameraItem.noData:
            pm.confirmDialog(title='No base camera', ma='center',
                             message='Please make an asset code:0000 as base camera',
                             button=['OK'], defaultButton='OK', dismissString='OK')
            return

        cameraMData = {'code': '0000', 'ver': cameraItem.publishVer, 'updateMode': 'last',
                      'task': 'rig', 'assembleMode': 'camera','proxyMode':'rig', 'type': 'asset'}
        camera = CameraComponent('cam', cameraMData, parent=item)



        camera.wrapData()
        if not camera.cameraTransform:
            camera.addToScene()
        newComponentsDict['cam'] = camera.getDataDict()


    for ns, sourceMData in itemList.iteritems():
        source = SceneSource(ns, sourceMData, parent=item)
        sourceItem = source.getItem()

        if sourceItem.publishVer == 0:
            print 'Component %s not yet published!!' % (ns + ':' + source.task + source.code)
            parcial = True
            continue

        empty = False

        if source.assembleMode == 'import':
            source.importToScene()

        elif source.assembleMode == 'reference':
            newComponentsDict[ns] = source.addReferenceToScene()

        elif source.assembleMode == 'copy':
            newComponentsDict = source.copyToScene()

        elif source.assembleMode == 'cache':
            newComponentsDict = source.addCacheToScene()

        elif source.assembleMode == 'xlo':
            newComponentsDict = source.addXloToScene()

    item.components = newComponentsDict

    # update infos on scene and database
    if not empty or not item.components:
        pm.fileInfo['projectName'] = database.getCurrentProject()
        pm.fileInfo['task'] = item.task
        pm.fileInfo['code'] = item.code
        pm.fileInfo['type'] = item.type

        if item.type == 'shot':
            pm.playbackOptions(ast=item.frameRange[0], aet=item.frameRange[1])
            pm.currentUnit(time='film')

        item.workVer = 1
        item.status = 'created'

        item.putDataToDB()
        sceneDirPath = item.getPath()[0]
        sceneFullPath = item.getWorkPath()

        if not os.path.exists(sceneDirPath):
            os.makedirs(sceneDirPath)

        pm.saveAs(sceneFullPath)

        if parcial:
            item.status = 'partial'
            pm.confirmDialog(title='Warning', ma='center',
                             message='WARNING build: Some components have no publish to complete build this file!',
                             button=['OK'], defaultButton='OK', dismissString='OK')
            item.putDataToDB()
        else:
            pm.confirmDialog(title='Warning', ma='center',
                             message='%s assembled sucessfully!' % item.filename,
                             button=['OK'], defaultButton='OK', dismissString='OK')

    else:
        pm.confirmDialog(title='Warning', ma='center',
                         message='ERROR build: No component published to build this file',
                         button=['OK'], defaultButton='OK', dismissString='OK')
コード例 #33
0
ファイル: threeMaya.py プロジェクト: wougzy/threeMaya
    def exportAnimation(self, _start, _end):

            self.infs = [pm.PyNode(str(x)) for x in self.infs]

            # export simple anim
            _keys = pm.keyframe(self.infs, query=True, timeChange=True)

            if _keys:
                anim = {}
                self.db['animation'] = anim

                anim['name'] = 'anim0'

                fps = dict(
                    game = 15,
                    film = 24,
                    pal = 25,
                    ntsc = 30,
                    show = 48,
                    palf = 50,
                    ntscf = 60
                    )[ pm.currentUnit(query=True, time=True) ]

                anim['fps'] = fps

                anim['hierarchy'] = []

                for i,inf in enumerate(self.infs):
                    _inf = {}

                    _parent = self.bones[i]['parent']
                    _inf['parent'] = _parent

                    if _parent != -1:
                        _parent = self.infs[_parent]
                    else:
                        _parent = None

                    _inf['keys'] = []
                    #_start = min(_keys)
                    #_end = max(_keys)
                    anim['length'] = round( (_end-_start)/float(anim['fps']), DECIMALS_TIME )

                    for frame in xrange( int(_end - _start) ):
                        _t = frame+_start

                        _key = {}
                        _key['time'] = round( frame/float(fps), DECIMALS_TIME )

                        _m = pm.dt.TransformationMatrix( inf.worldMatrix.get(time=_t) )
                        if _parent:
                            _m *= _parent.worldInverseMatrix.get(time=_t)

                        _key['pos'] = roundList( _m.getTranslation('transform'), DECIMALS_POS )
                        _key['rot'] = roundList( _m.getRotationQuaternion(), DECIMALS_ROT )
                        if frame==0:
                            _key['scl'] = [1,1,1]

                        _inf['keys'].append(_key)

                    _inf['keys'].append( {'time': anim['length']} )

                    anim['hierarchy'].append(_inf)
コード例 #34
0
def preBake():
    pm.currentUnit(t='pal')
    pm.select("all_ctrls_set*")
    mel.eval('ogs - pause;')
コード例 #35
0
def import_animfile(animpath, timestart=1.0, progress_fn=None):
    start = time.time()
    print "[io_pdx_mesh] importing {}".format(animpath)

    progress = None
    if progress_fn:
        progress = progress_fn('Importing', 10)

    # read the file into an XML structure
    asset_elem = pdx_data.read_meshfile(animpath)

    # find animation info and samples
    info = asset_elem.find('info')
    samples = asset_elem.find('samples')
    framecount = info.attrib['sa'][0]

    # set scene animation and playback settings
    fps = info.attrib['fps'][0]
    try:
        pmc.currentUnit(time=('{}fps'.format(fps)))
    except RuntimeError:
        fps = int(fps)
        if fps == 15:
            pmc.currentUnit(time='game')
        elif fps == 30:
            pmc.currentUnit(time='ntsc')
        else:
            raise NotImplementedError("Unsupported animation speed. {}".format(fps))

    print "[io_pdx_mesh] setting playback speed - {}".format(fps)
    if progress_fn:
        progress.update(1, 'setting playback speed')
    pmc.playbackOptions(e=True, playbackSpeed=1.0)
    pmc.playbackOptions(e=True, animationStartTime=0.0)

    print "[io_pdx_mesh] setting playback range - ({},{})".format(timestart, (timestart + framecount - 1))
    if progress_fn:
        progress.update(1, 'setting playback range')
    pmc.playbackOptions(e=True, minTime=timestart)
    pmc.playbackOptions(e=True, maxTime=(timestart + framecount - 1))

    pmc.currentTime(0, edit=True)

    # find bones being animated in the scene
    print "[io_pdx_mesh] finding bones -"
    if progress_fn:
        progress.update(1, 'finding bones')
    bone_errors = []
    for bone in info:
        bone_joint = None
        bone_name = clean_imported_name(bone.tag)
        try:
            matching_bones = pmc.ls(bone_name, type=pmc.nt.Joint, long=True)  # type: pmc.nodetypes.joint
            bone_joint = matching_bones[0]
        except IndexError:
            bone_errors.append(bone_name)
            print "[io_pdx_mesh] failed to find bone '{}'".format(bone_name)
            if progress_fn:
                progress.update(1, 'failed to find bone!')

        # set initial transform and remove any joint orientation (this is baked into rotation values in the .anim file)
        if bone_joint:
            # compose transform parts
            _scale = [bone.attrib['s'][0], bone.attrib['s'][0], bone.attrib['s'][0]]
            _rotation = MQuaternion(*bone.attrib['q'])
            _translation = MVector(*bone.attrib['t'])

            # convert to Game space
            bone_joint.setScale(_scale)
            bone_joint.setRotation(swap_coord_space(_rotation))
            bone_joint.setTranslation(swap_coord_space(_translation))

            # zero out joint orientation
            bone_joint.jointOrient.set(0.0, 0.0, 0.0)

    # break on bone errors
    if bone_errors:
        raise RuntimeError("Missing bones required for animation:\n{}".format(bone_errors))

    # check which transform types are animated on each bone
    all_bone_keyframes = OrderedDict()
    for bone in info:
        bone_name = clean_imported_name(bone.tag)
        key_data = dict()
        all_bone_keyframes[bone_name] = key_data

        for sample_type in bone.attrib['sa'][0]:
            key_data[sample_type] = []

    # then traverse the samples data to store keys per bone
    s_index, q_index, t_index = 0, 0, 0
    for f in range(0, framecount):
        for i, bone_name in enumerate(all_bone_keyframes):
            bone_key_data = all_bone_keyframes[bone_name]

            if 's' in bone_key_data:
                bone_key_data['s'].append(samples.attrib['s'][s_index : s_index + 1])
                s_index += 1
            if 'q' in bone_key_data:
                bone_key_data['q'].append(samples.attrib['q'][q_index : q_index + 4])
                q_index += 4
            if 't' in bone_key_data:
                bone_key_data['t'].append(samples.attrib['t'][t_index : t_index + 3])
                t_index += 3

    for bone_name in all_bone_keyframes:
        bone_keys = all_bone_keyframes[bone_name]
        # check bone has keyframe values
        if bone_keys.values():
            print "[io_pdx_mesh] setting {} keyframes on bone '{}'".format(list(bone_keys.keys()), bone_name)
            if progress_fn:
                progress.update(1, 'setting keyframes on bone')
            bone_long_name = pmc.ls(bone_name, type=pmc.nt.Joint, long=True)[0].name()
            create_anim_keys(bone_long_name, bone_keys, timestart)

    pmc.select(None)
    print "[io_pdx_mesh] import finished! ({:.4f} sec)".format(time.time() - start)
    if progress_fn:
        progress.finished()
コード例 #36
0
 def __enter__(self):
     self.oldlin = pmc.currentUnit(q=True, linear=True)
     self.oldang = pmc.currentUnit(q=True, angle=True)
     self.oldtim = pmc.currentUnit(q=True, time=True)
     pmc.currentUnit(*self.args, **self.kwargs)
コード例 #37
0
from functools import wraps
import copy
import os
import inspect
import math
import maya.cmds as cmds
import pymel.core as pm
import pymel.core.datatypes as dt
import maya.mel as mm


versionList=['v',0.2,2017,10,1]
version= ".".join([str(o) for o in versionList])
#################### Global Variable
sceneUnit= pm.currentUnit(l=True,q=True)
timeRange=1
pickMethod=1
springMethod=1
startFrame = int(pm.playbackOptions(q=True,minTime=True))
endFrame = int(pm.playbackOptions(q=True,maxTime=True))
detailValue = 1
falloffValue = 0
dampValue=0.1
stiffValue=0.25
springValue=0.3
twistValue=0.3
loopValue=False
scriptName = inspect.getframeinfo(inspect.currentframe()).filename
scriptPath = os.path.dirname(os.path.abspath(scriptName))
scriptPath = "/".join(scriptPath.split('\\'))
#mm.eval('source "%s/driveJointsWithHair.mel";' % scriptPath)
コード例 #38
0
 def __enter__(self):
     self.oldlin = pmc.currentUnit(q=True, linear=True)
     self.oldang = pmc.currentUnit(q=True, angle=True)
     self.oldtim = pmc.currentUnit(q=True, time=True)
     pmc.currentUnit(*self.args, **self.kwargs)
コード例 #39
0
 def assertUnit(kw, ideal):
     self.assertEqual(pmc.currentUnit(q=True, **{kw: True}), ideal)
コード例 #40
0
ファイル: palrillaLT.py プロジェクト: jiwonchoe/pysideUI
    def unitCovert(self):

        pm.currentUnit(l='cm')
コード例 #41
0
 def assertUnit(kw, ideal):
     self.assertEqual(pmc.currentUnit(q=True, **{kw: True}), ideal)