Esempio n. 1
0
    def save_screenshot(self, name, directory=DIRECTORY):
        '''[summary]

        Arguments:
            name {string} -- Name of the asset to be used to make
                              screenshot file

        Keyword Arguments:
            directory {string} -- Path of the asset library
                                    (default: {LIBRARY_PATH})

        Returns:
            string -- Returns path of the screenshot file
        '''

        path = os.path.join(directory, '{0}.jpg'.format(name))

        cmds.viewFit()
        cmds.setAttr('defaultRenderGlobals.imageFormat', 8)

        cmds.playblast(
            completeFilename=path,
            forceOverwrite=True,
            format='image',
            width=200,
            height=200,
            showOrnaments=False,
            startTime=1,
            endTime=1,
            viewer=False)

        return path
Esempio n. 2
0
    def playblast(self, filename, **kwargs):
        '''Playblasting with reasonable default arguments. Automatically sets
        this viewport to the active view, ensuring that we playblast the
        correct view.

        :param filename: Absolute path to output file
        :param kwargs: Same kwargs as :func:`maya.cmds.playblast`'''

        playblast_kwargs = {
            'filename': filename,
            'offScreen': False,
            'percent': 100,
            'quality': 100,
            'viewer': True,
            'width': 960,
            'height': 540,
            'framePadding': 4,
            'format': 'qt',
            'compression': 'H.264',
            'forceOverwrite': True,
        }
        playblast_kwargs.update(kwargs)

        if not self.focus:
            self.focus = True
        cmds.playblast(**playblast_kwargs)
Esempio n. 3
0
 def recordPlayblastForSequence(self, tab, level1, level2, level3, offset=0, archive=0):
     # "/Users/higgsdecay/test"
     playblastFile = self.getFileName(tab, level1, level2, level3, "playblastFile2", offset, archive)
     # create the preview folder
     previewFolder = os.path.dirname(playblastFile)
     if not os.path.exists(previewFolder):
         os.makedirs(previewFolder)
         os.chmod( previewFolder , 0777 )
     else : 
         os.chmod( previewFolder , 0777 )
     startFrame = cmds.getAttr("defaultRenderGlobals.startFrame")
     endFrame = cmds.getAttr("defaultRenderGlobals.endFrame")
     format = cmds.getAttr("defaultRenderGlobals.imageFormat")
     
     width = cmds.getAttr("defaultResolution.width")
     height = cmds.getAttr("defaultResolution.height")
     ratio = cmds.getAttr("defaultResolution.deviceAspectRatio")
     
     cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
     # playblast -startTime 1 -endTime 10  -format iff -filename "/Users/higgsdecay/output/ACR_rig_v02_w03" 
     #-forceOverwrite  -sequenceTime 0 -clearCache 0 -viewer 1 -showOrnaments 1 -fp 4 -percent 50 -widthHeight 1920 1080;
     
     cmds.playblast(startTime=startFrame, endTime=endFrame, format="image",
                    filename=str(playblastFile), showOrnaments=False, viewer=False, percent=100,os=1,
                    sequenceTime=False, forceOverwrite=True,
                    widthHeight=[int(width), int(height)])
     cmds.setAttr("defaultRenderGlobals.imageFormat", format)
     
     return (playblastFile+".####.jpg", int(startFrame), int(endFrame), int(width), int(height), ratio)
Esempio n. 4
0
def save_scene(search_key, context, description, all_process):

    # add info about particular scene
    skey_link = 'skey://{0}&context={1}'.format(search_key, context)
    if not cmds.attributeQuery('tacticHandler_skey', node='defaultObjectSet', exists=True):
        cmds.addAttr('defaultObjectSet', longName='tacticHandler_skey', dataType='string')
    cmds.setAttr('defaultObjectSet.tacticHandler_skey', skey_link, type='string')

    # get template names for scene and playblast image
    temp_dir = env.Env().get_temp_dir()
    random_uuid = uuid.uuid4()

    types = {
        'mayaBinary': 'mb',
        'mayaAscii': 'ma',
    }
    temp_file = '{0}/{1}.ma'.format(temp_dir, random_uuid)
    temp_playblast = '{0}/{1}.jpg'.format(temp_dir, random_uuid)

    # rename file, save scene, playblast, get saving format
    cmds.file(rename=temp_file)
    cmds.file(save=True, type='mayaAscii')
    current_frame = cmds.currentTime(query=True)
    cmds.playblast(
        forceOverwrite=True,
        format='image',
        completeFilename=temp_playblast,
        showOrnaments=False,
        widthHeight=[960, 540],
        sequenceTime=False,
        frame=[current_frame],
        compression='jpg',
        offScreen=True,
        viewer=False,
        percent=100
    )

    # check in snapshot
    snapshot = tc.checkin_snapshot(search_key, context, temp_file, file_type='maya', is_current=True,
                                   description=description)

    # from pprint import pprint
    # pprint(snapshot)
    # retrieve checked in snapshot file info
    asset_dir = env.Env().get_asset_dir()
    file_sobject = snapshot['__file_sobjects__'][0]
    relative_dir = file_sobject['relative_dir']
    file_name = file_sobject['file_name']

    # make proper file path, and dir path to set workspace
    new_file = '{0}/{1}/{2}'.format(asset_dir, relative_dir, file_name)
    split_path = relative_dir.split('/')
    dir_path = '{0}/{1}'.format(asset_dir, '{0}/{1}/{2}'.format(*split_path))
    set_workspace(dir_path, all_process)

    # check in playblast
    tc.checkin_playblast(snapshot['code'], temp_playblast)

    # set proper scene name
    cmds.file(rename=new_file)
Esempio n. 5
0
def quick_pb():
    format = prefs().format
    project_path = prefs().project_path
    local_project_path = prefs().local_project_path
    start = cmds.playbackOptions(q=True, min=True)
    end = cmds.playbackOptions(q=True, max=True)

    if local_project_path and local_project_path != '':
        quickpb_path = utils.convert_local_path(
            os.path.join(os.path.dirname(cmds.file(q=True, sn=True)),
                         'quick_playblasts'), project_path, local_project_path)
        quick_file = utils.get_filename_without_override(
            os.path.join(quickpb_path, 'quick_playblast_0001.avi'))
        cmds.playblast(st=start,
                       et=end,
                       p=100,
                       f=quick_file,
                       wh=format,
                       qlt=70,
                       fp=4,
                       fmt='movie',
                       fo=1,
                       v=1)
        logger.info("Playblast saved as {}".format(quick_file))
    else:
        logger.warning('Please set a local project path in wizard before')
Esempio n. 6
0
def playblast(path=None,
              format=None,
              compression=None,
              hud=None,
              offscreen=None,
              range=None,
              scale=None):
    if range is None:

        range = playback_selection_range()
        print range
        if range is None:

            start = cmds.playbackOptions(q=True, min=True)
            end = cmds.playbackOptions(q=True, max=True)
            range = [start, end]

    cmds.playblast(startTime=range[0],
                   endTime=range[1],
                   f=path,
                   fmt=format,
                   orn=hud,
                   os=offscreen,
                   wh=scene_resolution(),
                   p=scale,
                   qlt=90,
                   c=compression,
                   v=True,
                   s=qeury_active_sound_node())
Esempio n. 7
0
def playblast_snapshot(path=None,
                       format=None,
                       compression=None,
                       hud=None,
                       offscreen=None,
                       range=None,
                       scale=None):
    current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32)  # *.png

    if range is None:

        range = playback_selection_range()
        print range
        if range is None:

            start = cmds.playbackOptions(q=True, min=True)
            end = cmds.playbackOptions(q=True, max=True)
            range = [start, end]

    cmds.playblast(frame=int((range[0] + range[1]) / 2),
                   cf=path,
                   fmt="image",
                   orn=hud,
                   os=offscreen,
                   wh=scene_resolution(),
                   p=scale,
                   v=False)

    cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
Esempio n. 8
0
def playblastStart(cameraList):
	for x in cameraList:
		i = cmds.listRelatives( x, p=True )
		cmds.select(i)
		start = cmds.findKeyframe( i, which="first" )
		end = cmds.findKeyframe( i, which="last" )
		sceneNameFull = cmds.file(query = True, shortName = True, sceneName = True)
		if '.mb' in sceneNameFull or '.ma' in sceneNameFull:
			sceneName = sceneNameFull[:-3] 
		else:
			sceneName = sceneNameFull
		cmds.select(cl = 1)
		focus = cmds.getPanel( withFocus=True )
		cmds.modelPanel( focus, edit=True, camera = x )
		cmds.modelEditor( focus, edit = True, cameras = False, locators = False)
		print start, end
		if start == end: # this means there's no keyframes
			print 'no keyframes on this one, playblasting timeline duration'
			cmds.playblast (format = "qt", compression = "Sorenson Video 3", filename = desktop + sceneName + '_' + str(i[0]) + '.mov', clearCache = 1 , viewer = 0, showOrnaments = 1, fp = 4, percent = 100, quality = 100, widthHeight = [1280, 720])
		else:
			print 'keyframes found, playblasting their start to end'
			cmds.playblast (startTime = start, endTime = end, format = "qt", compression = "Sorenson Video 3", filename = desktop + sceneName + '_' + str(i[0]) + '.mov', sequenceTime = 0, clearCache = 1 , viewer = 0, showOrnaments = 1, fp = 4, percent = 100, quality = 100, widthHeight = [1280, 720])
		#cmds.playblast( completeFilename = str(i) + '.mov', startTime = start, endTime = end, viewer = True, clearCache = True, percent = 100, quality = 100, format = "qt", framePadding = 20 )
		cmds.modelEditor( focus, edit = True, cameras = True, locators = True)
		print ' moving to the next one '
Esempio n. 9
0
def playblast():

    cmds.file(sn=True, q=True)
    scene_path, scene_name = os.path.split(cmds.file(sn=True, q=True))
    print scene_path, scene_name

    scene_name = os.path.splitext(scene_name)[0]
    print scene_name

    out_path = os.path.abspath(
        os.path.join(
            scene_path,
            'playblast',
            scene_name
        )
    )

    print out_path

    # if not os.path.exists(os.path.basename(out_path)):
    #     os.makedirs(out_path)

    # playblast  -format image -filename "E:/Dropbox/projects/2018/0100_seq_kabam/3d/sequences/KBL001/010/anim/work/maya/playblast/kabam_KBL001_010_anim_v036/kabam_KBL001_010_anim_v036" -sequenceTime 0 -clearCache 1 -viewer 0 -showOrnaments 0 -fp 4 -percent 100 -compression "png" -quality 100 -widthHeight 1920 1080;
    cmds.playblast(fmt='image',
                   compression='png',
                   filename=os.path.join(out_path, scene_name),
                   orn=False,
                   v=False,
                   percent=100,
                   quality=100,
                   width=1920,
                   height=1080,
                   fo=True
                   )
Esempio n. 10
0
    def saveScreenshot(self, name):
        """
    This function saves a screenshot of the library mesh
    Args:
      name: The name of the file to be saved

    Returns: The path to the screenshot

    """
        directory = self.DIRECTORY
        screenshotPath = os.path.join(directory, "%s.jpg" % name)
        cmds.viewFit()
        #We deselect the mesh so we can screenshot it prettier
        cmds.select(clear=True)
        #Save as jpeg
        cmds.setAttr('defaultRenderGlobals.imageFormat', 8)
        cmds.playblast(completeFilename=screenshotPath,
                       forceOverwrite=True,
                       format='image',
                       width=200,
                       height=200,
                       showOrnaments=False,
                       startTime=1,
                       endTime=1,
                       viewer=False)

        return screenshotPath
Esempio n. 11
0
def TimeToPlayBlast(*args):
    resolution = {'HD 720': [1280, 720], 'HD 1080': [1920, 1080], 'HD 540': [960, 540]}
    # Playblasts The Scene
    res = cmds.optionMenu('resViewPanel', q=True, v=True)
    filePath = cmds.textField("FilePathGoesHere", q=True, text=True)
    fileName = cmds.textField("FileNameGoesHere", q=True, text=True)
    NameOfFile = os.path.join(filePath, fileName)

    WidthField = resolution[res][0]
    HeightField = resolution[res][1]
    # make the integer field for quality 0-100
    QualityField = cmds.intField("QualityField", q=True, value=True)
    # Make the checkbox for the show ornaments
    OrnamentsCheck = cmds.checkBox("OrnamentsCheck", q=True, value=True)
    # get ready to print the width of the play blast in the script editor
    editor = cmds.playblast(activeEditor=True)
    # hide all objects in view
    cmds.modelEditor(editor, edit=True, allObjects=False)
    # make polygons visible only
    cmds.modelEditor(editor, edit=True, polymeshes=True)
    # make cv's hidden
    cmds.modelEditor(editor, edit=True, cv=False)
    # make hulls hidden
    cmds.modelEditor(editor, edit=True, hulls=False)
    # make grid hidden
    cmds.modelEditor(editor, edit=True, grid=False)
    # make selected items hidden
    cmds.modelEditor(editor, edit=True, sel=False)
    # make heads up display hidden
    cmds.modelEditor(editor, edit=True, hud=False)
    # playblast from selected settings
    cmds.playblast(filename=NameOfFile, format="qt", sequenceTime=0, clearCache=1, viewer=True,
                   showOrnaments=OrnamentsCheck, framePadding=4, percent=100, compression="H.264",
                   quality=QualityField, widthHeight=(WidthField, HeightField), forceOverwrite=True)
Esempio n. 12
0
    def screenshot(self):
        self.playblastpath = r"Q:\rig\scripts\test\q_repos\aas_scripts\aas_mayaTools\ani_scripts\strack_asset\midchangepic.jpg"  # 设置截图保存路径
        filename = pm.sceneName()
        if filename:
            strinfo = re.compile('.ma|.mb')
            self.path = strinfo.sub('.jpg', filename)
            cmds.viewFit()
            cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
            if os.path.exists(self.path):
                picplayblast = cmds.playblast(
                    completeFilename=self.playblastpath,
                    forceOverwrite=True,
                    format='image',
                    width=500,
                    height=500,
                    showOrnaments=False,
                    startTime=1,
                    endTime=1,
                    viewer=False)

            else:
                picplayblast = cmds.playblast(completeFilename=self.path,
                                              forceOverwrite=True,
                                              format='image',
                                              width=500,
                                              height=500,
                                              showOrnaments=False,
                                              startTime=1,
                                              endTime=1,
                                              viewer=False)

            map = QtGui.QPixmap(picplayblast)
            self.screenshotbtn.setPixmap(map)
        else:
            self.Message.setText("<h3>请打开这个文件(注意不要导入)</h3>")
Esempio n. 13
0
    def recordPlayblastForSequenceN(self, tab, level1, level2, level3, width , height , fileName ,sframe , eframe , folder = 'devFolder' ):
        # "/Users/higgsdecay/test"
        playblastFile = os.path.join(str(self.getFileName(tab, level1, level2, level3, folder , 0, 1)), "preview", os.path.splitext(str(fileName))[0], str(fileName))
        # create the preview folder
        previewFolder = os.path.dirname(playblastFile)
        if not os.path.exists(previewFolder):
            os.makedirs(previewFolder)
            os.chmod( previewFolder , 0777 )
#        startFrame = cmds.getAttr("defaultRenderGlobals.startFrame")
#        endFrame = cmds.getAttr("defaultRenderGlobals.endFrame")
        format = cmds.getAttr("defaultRenderGlobals.imageFormat")
        
#        width = cmds.getAttr("defaultResolution.width")
#        height = cmds.getAttr("defaultResolution.height")
        ratio = cmds.getAttr("defaultResolution.deviceAspectRatio")
        cams = [ x for x in cmds.ls(typ='camera') if cmds.getAttr(x+'.renderable')]
        thecam = cmds.listRelatives( cams[0] , p = 1) if cams != [] else None

        cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
        # playblast -startTime 1 -endTime 10  -format iff -filename "/Users/higgsdecay/output/ACR_rig_v02_w03" 
        #-forceOverwrite  -sequenceTime 0 -clearCache 0 -viewer 1 -showOrnaments 1 -fp 4 -percent 50 -widthHeight 1920 1080;
        cmds.playblast(startTime=sframe, endTime=eframe, format="image",percent = 100 , qlt = 100,
                       filename=os.path.splitext(str(playblastFile))[0], showOrnaments=False, viewer=False, os=1,
                       sequenceTime=False, forceOverwrite=True,
                       widthHeight=[int(width), int(height)]  )
        
        for x in glob.glob( previewFolder+os.sep+'*.*' ):
            print 'glob : ' , x
            os.chmod(x , 0777)
        cmds.setAttr("defaultRenderGlobals.imageFormat", format)
        return (playblastFile, ratio)
def ScreenCapture(filename,resolution, color = 0.361):
	cmds.undoInfo(stateWithoutFlush = False)
	try:
		oldFormat = cmds.getAttr("defaultRenderGlobals.imageFormat")
		
		cmds.setAttr("defaultRenderGlobals.imageFormat", 32)
		
		#Store the current display colors
		colors = [cmds.displayRGBColor("background", query = True), 
				cmds.displayRGBColor("backgroundTop", query = True), 
				cmds.displayRGBColor("backgroundBottom", query = True)]
		
		#To make the UI prettier
		cmds.displayRGBColor("background", color, color, color)
		cmds.displayRGBColor("backgroundTop", color, color, color)
		cmds.displayRGBColor("backgroundBottom", color, color, color)
		
		#Take a snap for the UI
		cmds.playblast(frame=0,fmt="image",viewer=0,fp=4,orn=0,p=100,wh=resolution,ifz=0,fo=1,offScreen=1,cf=filename)
		
		#Revert to the old colors
		cmds.displayRGBColor("background", colors[0][0], colors[0][1], colors[0][2])
		cmds.displayRGBColor("backgroundTop", colors[1][0], colors[1][1], colors[1][2])
		cmds.displayRGBColor("backgroundBottom", colors[2][0], colors[2][1], colors[2][2])
	
		cmds.setAttr("defaultRenderGlobals.imageFormat", oldFormat)
		
	except:
		pass
	cmds.undoInfo(stateWithoutFlush = True)
Esempio n. 15
0
def screenshot(fileDir, width, height, format=".jpg", override="", ogs=True):
    # check if fileDir has image format
    if format not in fileDir:
        fileDir += format

    # get existing values
    prevFormat = cmds.getAttr("defaultRenderGlobals.imageFormat")
    prevOverride = cmds.getAttr("hardwareRenderingGlobals.renderOverrideName")

    # set render settings
    cmds.setAttr("defaultRenderGlobals.imageFormat", IMGFORMATS[format])
    if override:
        cmds.setAttr("hardwareRenderingGlobals.renderOverrideName", override, type="string")

    if ogs:
        # render viewport
        renderedDir = cmds.ogsRender(cv=True, w=width, h=height)  # render the frame
        shutil.move(os.path.abspath(renderedDir), os.path.abspath(fileDir))  # move to specified dir
    else:
        frame = cmds.currentTime(q=True)
        cmds.playblast(cf=fileDir, fo=True, fmt='image', w=width, h=height,
                       st=frame, et=frame, v=False, os=True)

    # bring everything back to normal
    cmds.setAttr("defaultRenderGlobals.imageFormat", prevFormat)
    cmds.setAttr("hardwareRenderingGlobals.renderOverrideName", prevOverride, type="string")

    printInfo("Image saved successfully in {0}".format(fileDir))
    return fileDir
def playblast_scene():
    """ Playblast the current scene using the min and max playback
    values as the start and end value for the playblast.

    :todo: Add a configuration (json) file that lets the user save
           their file to a particular location.
    :todo: Add a function in the utils folder that time stamps or
           versions the maya file.
    """
    # Get the start and end frames of the animation scene:
    start_frame = cmds.playbackOptions(min=True, query=True)
    end_frame   = cmds.playbackOptions(max=True, query=True)

    # Create the filename of the playblast:
    time_code = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())

    filename = cmds.file(query=True, sceneName=True)
    filename += time_code
    filename += ".mov"

    location = os.path.join(_get_images_directory(), filename)

    # Playblast the scene:
    cmds.playblast(filename=location, fmt="qt", offScreen=True)

    # Return
    return
Esempio n. 17
0
def playblastLocal(blastFilename, format, start, end, offscreen, width, height):
    '''
    Perform a playblast.
    '''
    # Check
    if format not in IMAGE_FORMAT_DICT:
        raise ImageFormatException, 'Invalid image format: %s' % format

    # Set the image format from the list and backup the old one
    oldRenderFormat = cmds.getAttr('defaultRenderGlobals.imageFormat')
    cmds.setAttr('defaultRenderGlobals.imageFormat', IMAGE_FORMAT_DICT[format])

    # Do the blast
    cmds.playblast(filename=blastFilename,
                   format='image',
                   startTime=start,
                   endTime=end,
                   forceOverwrite=True,
                   viewer=False,
                   offScreen=offscreen,
                   widthHeight=[int(width), int(height)],
                   percent=100
                   )
    
    # Restore the old render globals image format
    cmds.setAttr('defaultRenderGlobals.imageFormat', oldRenderFormat) 
Esempio n. 18
0
    def saveScreenshot(self, name):
        path = os.path.join(self.userPath, '%s.jpg' % name)
        activePanel = cmds.paneLayout('viewPanes', q=True, pane1=True)

        cmds.viewFit()
        cmds.setAttr('defaultRenderGlobals.imageFormat', 8)

        # Isolate selection
        if cmds.ls(selection=True):
            cmds.isolateSelect(activePanel, update=1)
            cmds.isolateSelect(activePanel, state=1)
            cmds.isolateSelect(activePanel, addSelected=1)

        cmds.modelEditor(activePanel, edit=True, sel=False)

        cmds.playblast(completeFilename=path,
                       forceOverwrite=True,
                       format='image',
                       width=200,
                       height=200,
                       showOrnaments=False,
                       startTime=1,
                       endTime=1,
                       viewer=False)

        cmds.modelEditor(activePanel, edit=True, sel=True)

        cmds.isolateSelect(activePanel, state=0)
Esempio n. 19
0
 def saveScreenShot(self, name, directory=DIRECTORY):
     path = os.path.join(directory, '%s.jpg'%name)
     cmds.viewFit()
     cmds.setAttr('defaultRenderGlobals.imageFormat', 8)
     cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200,
                    showOrnaments = False, startTime=1, endTime=1, viewer=False )
     return path
Esempio n. 20
0
def main():
    cam = cm.modelPanel(cm.getPanel(withFocus=True), q=True, cam=True)

    workDir = cm.workspace(rootDirectory=True, q=True)
    blastPath = workDir + "playblasts"

    filename = os.path.basename(cm.file(q=True, sceneName=True))
    filename = os.path.splitext(filename)[0]

    currRenderLayer = cm.editRenderLayerGlobals(currentRenderLayer=True,
                                                q=True)

    folderName = filename + "__" + cam + "__" + currRenderLayer

    savingPath = blastPath + "\\" + folderName + "\\" + folderName

    print savingPath
    # if ":" in savingPath:
    #     savingPath = savingPath.replace(":","_")

    imageWidth = cm.getAttr("defaultResolution.width")
    imageHeight = cm.getAttr("defaultResolution.height")

    cm.playblast(filename=savingPath,
                 format="image",
                 width=imageWidth,
                 height=imageHeight,
                 percent=100,
                 offScreen=True,
                 showOrnaments=False,
                 compression="png")

    print "playblast done"
Esempio n. 21
0
def runFacialExpressions():
    #Open Eyes
    cmds.setAttr(leftEyeLid + '.translateX', 0)
    cmds.setAttr(leftEyeLid + '.translateY', 0.8)
    cmds.setAttr(rightEyeLid + '.translateX', 0)
    cmds.setAttr(rightEyeLid + '.translateY', 0.8)
    #audioLoc = 'C:\\Users\\gthak\\OneDrive\\Documents\\maya\\mery\\temp.mp3'
    base = os.path.dirname(os.path.abspath(
        __file__))  #"C:\\Users\\gthak\\OneDrive\\Documents\\maya\\mery\\"
    print base
    phenome_dict = load_phenome_dict(base + "\\cmudict\\cmudict-0.7b.txt")
    while (True):
        str = raw_input()
        str = str.strip()
        #os.system('gtts-cli '+str+' -l "en" -o '+audioLoc)
        resetParts()
        frame = 0
        frame = setPartsToIdle(frame)
        for x in phenome_dict[str.upper()]:
            print x,
            frame = express(x, frame)
        print ''
        frame = setPartsToIdle(frame)
        cmds.playbackOptions(animationStartTime=0,
                             animationEndTime=frame,
                             playbackSpeed=12)
        #cmds.playblast(  sound = audioLoc, format="movie", compression="" )
        cmds.playblast(startTime=0,
                       endTime=frame,
                       format="image",
                       compression="gif")
        cmds.cutKey(cmds.ls(), time=(0, frame))
    def saveScreenshot(self, name, camera, directory=DIRECTORY):
        path = os.path.join(directory, '%s.jpg' % name)
        if not os.path.exists(directory):
            os.mkdir(directory)

        time = cmds.currentTime(q=True)
        cmds.modelEditor('modelPanel4',
                         edit=True,
                         grid=False,
                         displayTextures=True,
                         rnm='base_OpenGL_Renderer',
                         displayAppearance="smoothShaded",
                         allObjects=False,
                         polymeshes=True,
                         camera=camera)
        cmds.setAttr('defaultRenderGlobals.imageFormat', 8)
        cmds.playblast(editorPanelName='modelPanel4',
                       completeFilename=path,
                       forceOverwrite=True,
                       format='image',
                       width=500,
                       height=500,
                       showOrnaments=False,
                       startTime=time,
                       endTime=time,
                       viewer=False)
        cmds.modelEditor('modelPanel4',
                         edit=True,
                         allObjects=True,
                         camera='persp')
        return path
Esempio n. 23
0
    def grab(self):
        """
        generate screen grab for specified path / board

        :type   image_path: C{str}
        :param  image_path: path to save screen board
        :type   quality: C{int}
        :param  quality: expected image quality
        :type   width_height: C{tuple}
        :param  width_height: expected width and height values for resulting
                                image; values of 0 means current panel size
        """
        sys.stdout.write("Generating screen board image %s" % self.image_path)
        mc.playblast(
            frame=1,
            format="image",
            completeFilename=self.image_path,
            clearCache=True,
            viewer=False,
            showOrnaments=False,
            compression=self.image_ext,
            quality=self.quality,
            percent=100,
            widthHeight=self.width_height,
        )
Esempio n. 24
0
def playblast(path=None, format=None, compression=None, hud=None, offscreen=None, range=None, scale=None):
    if range is None:

        range = playback_selection_range()
        print range
        if range is None:
            start = cmds.playbackOptions(q=True, min=True)
            end = cmds.playbackOptions(q=True, max=True)
            range = [start, end]

    #query users's focalLengthVisibility
    # focalLengthVisibility = cmds.optionVar(query="focalLengthVisibility")

    #set focalLengthVisibility On for the recording
    # mel.eval('setFocalLengthVisibility({})'.format(str(1)))
    #
    # if camera == 'Active camera':
    #     cam = ''
    # elif camera == 'Render camera':
    #     cam = ''

    if compression:
        cmds.playblast(startTime=range[0], endTime=range[1], f=path, fmt=format, orn=hud, os=offscreen,
                       wh=scene_resolution(), p=scale, qlt=90, c=compression, v=False, s = qeury_active_sound_node())
    else:
        cmds.playblast(startTime=range[0], endTime=range[1], f=path, fmt=format, orn=hud, os=offscreen,
                       wh=scene_resolution(), p=scale, qlt=90, v=False, s=qeury_active_sound_node())
    def saveScreenshot(self, name, directory=DIRECTORY):
        """
         to save screenshot of the model
        Args:
            name: (str) name of the model
            directory: (str) (path) path of the control library

        Returns:
            path: path of image of the screenshot

        """

        path = os.path.join(directory, '%s.jpg' %
                            name)  # to get the path of the screenshot

        cmds.viewFit(
        )  # view fit from maya commands of selected object i.e click 'f' key
        cmds.setAttr('defaultRenderGlobals.imageFormat',
                     8)  # set maya render to image format of jpg

        cmds.playblast(
            completeFilename=path,
            forceOverwrite=True,
            format='image',
            width=200,
            height=200,
            showOrnaments=False,
            startTime=1,
            endTime=1,
            viewer=False)  # get playblast of 1 frame and save in given path

        # return the path of the image
        return path
Esempio n. 26
0
    def playblast_and_publish(self):
        self.main01()
        #    Playblast in local and move to server
        local_dir = 'C:/Temp'
        if not os.path.exists(local_dir):
            os.mkdir(local_dir)
        local_path = os.path.join(local_dir, os.path.basename(self.path))
        
        if os.path.exists(local_path):
            os.remove(local_path)
        cmds.playblast(format="qt", filename= local_path, forceOverwrite=True, sequenceTime=0, clearCache=1, viewer=0, showOrnaments=1, fp=4, percent=100, compression="Photo - JPEG", quality=70, widthHeight=(1280,720))
        
        #    Publish playblast
        move(local_path, self.path)
        verData= {
                "code": os.path.basename(self.path),
                "entity": self.ctx.entity,
                "sg_task": self.ctx.task,
                "project": self.ctx.project,
                "description": self.comment_Field.toPlainText(),
                "sg_path_to_movie": self.path,
        }

        sg_version = self._app.tank.shotgun.create("Version", verData)
        self._app.tank.shotgun.upload("Version", sg_version["id"], self.path, "sg_uploaded_movie")
        cmds.confirmDialog(t='Playblast Published', m='Playblast finished and published to shotgun', b='Ok')
Esempio n. 27
0
def tumbnailCreator(args=None):
    sel = selo()
    shapesel = '\n'.join(cmds.listRelatives(sel[0], shapes=True))

    obj = str(sel[0]).split("|")[-1]

    selectionCurve = sel

    detShp = fFiesta.getShape(crv=sel)
    saveCrv = fFiesta.saveToLib(crv=sel, shapeName=shapesel)
    validateCrv = fFiesta.validateCurve(crv=sel)

    for obj in selectionCurve:
        shortName = obj.split("|")[-1]
        cmds.rename(obj, shortName)

    cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
    cmds.playblast(viewer=False,
                   completeFilename=path + obj + ".jpg",
                   startTime=0,
                   endTime=0,
                   forceOverwrite=True,
                   showOrnaments=False,
                   percent=100,
                   width=70,
                   height=70,
                   framePadding=0,
                   format="image")
    createFKWindow()
Esempio n. 28
0
    def playblast(self, frames):
        '''Playblasts the current range to the project's 'pencil' folder'''

        #make sure the projects pencil path and name.data path exists
        self.initPaths()

        filename = os.path.join(self.data['pencilDataPath'], self.name)

        #temporarily set image format to png
        curTime = cmds.currentTime(q=True)  #remember current time
        oldFormat = cmds.getAttr(
            'defaultRenderGlobals.imageFormat')  #remember image format
        cmds.setAttr('defaultRenderGlobals.imageFormat', 32)
        cmds.playblast(filename=filename,
                       frame=frames,
                       format='image',
                       forceOverwrite=True,
                       framePadding=4,
                       w=self.data['res'][0],
                       h=self.data['res'][1],
                       percent=100,
                       viewer=False)
        cmds.setAttr('defaultRenderGlobals.imageFormat',
                     oldFormat)  #restore last image format
        cmds.currentTime(curTime)  #restore current time
def blast(*args):
    """Playblast and settings. Change to your liking."""
    fileNameLong = cmds.file(query=True, sceneName=True, shortName=True)

    if fileNameLong == "":
        fileNameLong = "untitled"
    else:
        fileNameLong = cmds.file(query=True, sceneName=True, shortName=True)

    fileNameShort = fileNameLong.split(".")

    TimeRange = mel.eval('$tmpVar=$gPlayBackSlider')
    SoundNode = cmds.timeControl(TimeRange, query=True, sound=True)

    # Disable 2D Pan & Zoom in current viewport
    activepanel = cmds.getPanel(withFocus=True)
    cam = cmds.modelEditor(activepanel, query=True, camera=True)
    # camShape = cmds.listRelatives(cam, shapes=True)[0]
    cmds.setAttr(cam + '.panZoomEnabled', False)

    if cmds.ls(renderResolutions=True):
        ResX = cmds.getAttr("defaultResolution.width")
        ResY = cmds.getAttr("defaultResolution.height")

        cmds.playblast(
            filename=("movies/" + fileNameShort[0] + ".mov"),
            forceOverwrite=True, format="qt", compression="png",
            offScreen=True, width=ResX, height=ResY, quality=100,
            percent=100, sound=SoundNode
        )
    else:
        cmds.error("No resolution data in file. \
                    Please set resolution and save.")
Esempio n. 30
0
def incremental_save():
    current_file_ext = cmds.file(query=True, sceneName=True)
    current_file = current_file_ext.strip(".ma")
    directory = path.dirname(current_file_ext)
    file_name = path.basename(current_file)

    if "edits" in directory:
        for f in listdir(directory + "/.."):
            if file_name[:-2] in f:
                current_file_ext = f
                current_file = current_file_ext.strip(".ma")
                version = int(current_file[-2:]) + 1
    else:
        version = int(file_name[-2:]) + 1

    if version < 10:
        new_file_name = file_name[:-2] + "0" + str(version)
    else:
        new_file_name = file_name[:-2] + str(version)

    ## SCREENSHOT ##
    frm = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 0)
    if "edits" in directory:
        if not path.isdir(directory + "/../../images/screenshots"):
            mkdir(directory + "/../../images/screenshots")
        cmds.playblast(frame=1,
                       format="image",
                       cf=directory + "/../../images/screenshots/" +
                       new_file_name + ".gif",
                       v=False,
                       wh=(498, 270),
                       p=100,
                       orn=False)
    else:
        if not path.isdir(directory + "/../images/screenshots"):
            mkdir(directory + "/../images/screenshots")
        cmds.playblast(frame=1,
                       format="image",
                       cf=directory + "/../images/screenshots/" +
                       new_file_name + ".gif",
                       v=False,
                       wh=(498, 270),
                       p=100,
                       orn=False)

    cmds.setAttr("defaultRenderGlobals.imageFormat", frm)

    ## SAVE ##
    if "edits" in directory:
        cmds.file(rename=directory + "/../" + new_file_name + ".ma")
        cmds.file(save=True, type="mayaAscii")
        copyfile(directory + "/../" + current_file_ext,
                 directory + "/" + current_file_ext)
        remove(directory + "/../" + current_file_ext)
    else:
        cmds.file(rename=directory + "/" + new_file_name + ".ma")
        cmds.file(save=True, type="mayaAscii")
        copyfile(current_file_ext, directory + "/edits/" + file_name + ".ma")
        remove(current_file_ext)
Esempio n. 31
0
    def do_playblast(self, cam_namespace):

        cmds.file(self.file, o=True, f=True)

        if self.refresh_assets:
            reference_asset.refresh_all()

        temp_file = os.path.join(self.temp_dir, 'temp_blast')

        reference_asset.import_camera()

        camera = self.select_cam(cam_namespace)
        # get camera focal length and write it to a file. File is later deleted in 'tools/playblast.py'
        camera_focal = cmds.getAttr(camera + '.focalLength')
        camera_focal = str(round(camera_focal, 1))
        with open('{}/focal.txt'.format(self.temp_dir), 'w') as f:
            f.write(camera_focal)

        cmds.playblast(st=self.range[0],
                       et=self.range[-1],
                       p=100,
                       f=temp_file,
                       wh=self.format,
                       qlt=100,
                       fp=4,
                       fmt='image',
                       compression='png',
                       fo=1,
                       v=False)
Esempio n. 32
0
    def playblast(self, **kwargs):
        '''Playblasting with reasonable default arguments. Automatically sets
        this viewport to the active view, ensuring that we playblast the
        correct view.

        :param filename: Absolute path to output file
        :param kwargs: Same kwargs as :func:`maya.cmds.playblast`'''

        playblast_kwargs = {
            'offScreen': False,
            'percent': 100,
            'quality': 100,
            'viewer': True,
            'width': 960,
            'height': 540,
            'framePadding': 4,
            'format': 'qt',
            'compression': 'H.264',
            'forceOverwrite': True,
        }
        playblast_kwargs.update(kwargs)

        if not self.focus:
            self.focus = True
        cmds.playblast(**playblast_kwargs)
Esempio n. 33
0
    def snapShotFunc(self):
        if cmds.playblast(activeEditor=True) != self.editorShot:
            cmds.modelEditor(self.editorShot, edit=True, activeView=True)

        try:
            name = cmds.textField(self.NameInput, q=True, tx=True)
            if not os.path.exists(PoseIconPath):
                os.makedirs(PoseIconPath)
            fullNamePath = PoseIconPath + name + ".bmp"
            f = open(fullNamePath, 'w')
            f.close()
            success = True
        except:
            cmds.confirmDialog(
                title="Save Pose",
                icon="critical",
                message=
                "Perforce operation unsucessful. Could not save file. Aborting operation."
            )
            return
        currentTime = cmds.currentTime(query=True)
        cmds.playblast(frame=currentTime,
                       format="image",
                       cf=fullNamePath,
                       v=False,
                       wh=[100, 100],
                       p=100,
                       compression="bmp")
        self.savePoseDataToFile(name, fullNamePath)
Esempio n. 34
0
def doPlayblast():

    parentFolder, remainingPath = getParentFolder()

    Ep = remainingPath.split('/')[0]
    Seq = remainingPath.split('/')[1]

    filename = cmds.file(q=True, sn=True, shn=True)
    filename = filename.split('.')[0]

    filePath = '%s/Previs/%s/%s' % (Ep, Seq, filename)

    if platform.system() == "Windows":
        pbformat = 'qt'
    else:
        pbformat = 'avfoundation'

    #get sound
    aPlayBackSliderPython = maya.mel.eval('$tmpVar=$gPlayBackSlider')
    timelineSound = cmds.timeControl(aPlayBackSliderPython, q=True, sound=True)

    cmds.playblast(format=pbformat,
                   sound=timelineSound,
                   filename='movies/%s' % filePath,
                   sequenceTime=0,
                   clearCache=1,
                   viewer=1,
                   showOrnaments=1,
                   percent=100,
                   compression="H.264",
                   quality=80,
                   widthHeight=[1920, 1080],
                   offScreen=True)
Esempio n. 35
0
    def doPlayblast(self, camera):
        
        G.TU_movie              = None
        G.TU_audioFile          = None
        G.TU_audioOffsetSec     = None        
        winName                 = 'playblastWindow'
        overscan                = cmds.getAttr("%s.overscan"%camera)   
        audioTrack              = cmds.timeControl(G.playBackSliderPython, query=True, sound=True)
        rangeVisible            = cmds.timeControl(G.playBackSliderPython, query=True, rangeVisible=True )  
        widthHeight             = utilMod.getRenderResolution()  
        
        if cmds.window(winName, query=True, exists=True): cmds.deleteUI(winName)
        
        window                  = cmds.window(winName, widthHeight=widthHeight)
        form                    = cmds.formLayout()
        editor                  = cmds.modelEditor()
        column                  = cmds.columnLayout('true')
        
        cmds.formLayout( form, edit=True, attachForm=[(column, 'top', 0), (column, 'left', 0), (editor, 'top', 0), (editor, 'bottom', 0), (editor, 'right', 0)], attachNone=[(column, 'bottom'), (column, 'right')], attachControl=(editor, 'left', 0, column))
        cmds.modelEditor(editor, edit=True, camera=camera, activeView=True)
        cmds.showWindow( window )
        cmds.window( winName, edit=True, topLeftCorner=(0, 0), widthHeight=[200,200])        
        utilMod.cameraViewMode(editor)        
        cmds.setAttr("%s.overscan"%camera, 1)
        
        
        if rangeVisible:
            range = animMod.getTimelineRange(float=False)
            rFrom   = range[0]
            rTo     = range[1]-1
        else:
            rFrom = cmds.playbackOptions(query=True, minTime=True)
            rTo   = cmds.playbackOptions(query=True, maxTime=True)
        

        if G.currentStudio == None:
            G.TU_movie = cmds.playblast(format="qt", sound=audioTrack, startTime=rFrom ,endTime=rTo , viewer=1, showOrnaments=0, offScreen=True, fp=4, percent=50, compression="png", quality=70, widthHeight=widthHeight, clearCache=True)
            
        else:
            
            fps             = mel.eval("currentTimeUnitToFPS") 
            if audioTrack:
                G.TU_audioFile      = cmds.sound(audioTrack, query=True, file=True)
                audioOffset         = cmds.sound(audioTrack, query=True, offset=True)
                G.TU_audioOffsetSec = str((rFrom - audioOffset)/-fps)
                
            movieName       = cmds.playblast(format="image", startTime=rFrom ,endTime=rTo , viewer=0, showOrnaments=0, offScreen=True, fp=4, percent=50, compression="jpg", quality=70, widthHeight=widthHeight, clearCache=True)
            if movieName: 
                G.TU_movie           = "%s.%s-%s#.jpg"%(movieName.split(".")[0], int(rFrom), int(rTo))
                if audioTrack:  G.TU_audioOffsetSec = audioOffset
                self.playMovie(G.TU_movie, G.TU_audioFile, G.TU_audioOffsetSec)
            
        if cmds.window(winName, query=True, exists=True): cmds.deleteUI(winName)
        
        cmds.setAttr("%s.overscan"%camera, overscan)
        
        if not G.TU_movie: return
        save = aToolsMod.getUserPref("saveAfterPlayblasting", default=True)
        if save and not rangeVisible: cmds.file(save=True)
def thumbnailFromPlayBlast(filepath, width, height, modelPanel=None):
    '''
    Generate a ThumbNail of the screen
    Note: 'cf' flag is broken in 2012

    :param filepath: path to Thumbnail
    :param width: width of capture
    :param height: height of capture
    :param modePanel: modelPanel to grab the image from, default=None, works it out internally
    '''
    filepath = os.path.splitext(filepath)[0]
    filename = os.path.basename(filepath)
    filedir = os.path.dirname(filepath)

    # get modelPanel and camera
    if not modelPanel or not cmds.modelPanel(modelPanel, exists=True):
        modelPanel = cmds.playblast(activeEditor=True).split('|')[-1]

    cam = cmds.modelPanel(modelPanel, q=True, camera=True)
    if not cmds.nodeType(cam) == 'camera':
        cam = cmds.listRelatives(cam)[0]

    storedformat = cmds.getAttr('defaultRenderGlobals.imageFormat')
    storedResolutionGate = cmds.getAttr('%s.filmFit' % cam)

    cmds.setAttr('defaultRenderGlobals.imageFormat', 20)
    cmds.setAttr('%s.filmFit' % cam,
                 2)  # set to Vertical so we don't get so much overscan

    cmds.playblast(
        frame=cmds.currentTime(q=True),  # startTime=cmds.currentTime(q=True),
        # endTime=cmds.currentTime(q=True),
        format="image",
        filename=filepath,
        width=width,
        height=height,
        percent=100,
        quality=90,
        forceOverwrite=True,
        framePadding=0,
        showOrnaments=False,
        compression="BMP",
        viewer=False)
    cmds.setAttr('defaultRenderGlobals.imageFormat', storedformat)
    cmds.setAttr('%s.filmFit' % cam, storedResolutionGate)
    # Why do this rename? In Maya2012 the 'cf' flag fails which means you have to use
    # the 'f' flag and that adds framePadding, crap I know! So we strip it and rename
    # the file after it's made.
    try:
        newfile = [
            f for f in os.listdir(filedir) if
            f.split('.bmp')[0].split('.')[0] == filename and '.pose' not in f
        ]
        log.debug('Original Playblast file : %s' % newfile)
        os.rename(os.path.join(filedir, newfile[0]), '%s.bmp' % filepath)
        log.debug('Thumbnail Renamed : %s' % ('%s.bmp' % filepath))
        return '%s.bmp' % filepath
    except:
        pass
Esempio n. 37
0
 def createThumbnailN(self, tab, level1, level2, level3, fileName):
     fileName = self.getFileName(tab, level1, level2, level3, "sceneFolder", 0, 1)+fileName
     currFrame = cmds.currentTime(query=True)
     format = cmds.getAttr("defaultRenderGlobals.imageFormat")
     cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
     cmds.playblast(frame=currFrame, format="image", completeFilename=str(fileName), showOrnaments=False, viewer=False, widthHeight=[164, 105], percent=100 , os=1)
     cmds.setAttr("defaultRenderGlobals.imageFormat", format)
     return fileName
Esempio n. 38
0
 def playblast_picture(self):
     filename=(str(self.playblast_filename))
     strinfo = re.compile('.ma|.mb')
     path= strinfo.sub('.jpg',filename)
     cmds.viewFit()
     cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
     cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=800, height=800,
                    showOrnaments=False, startTime=1, endTime=1, viewer=False)
Esempio n. 39
0
 def playBlase(self):
     #拍屏 进入创建的摄像机视角
     cmds.lookThru(CameraName)
     #获得下拉列表当前的文本内容(foramt)
     ComboxText=self.formatCombox.currentText()
     #存储路径与文件名称 nameAndPath
     #拍屏
     cmds.playblast(format=ComboxText,filename=nameAndPath[0])
def GrabKey(*args):
    print(mc.findKeyframe(timeSlider=True, which="first"))
    print(mc.findKeyframe(timeSlider=True, which="last"))
    selection = mc.ls(sl=True)
    #print(mc.ls(sl=True))
    firstKey = mc.findKeyframe(timeSlider=True, which="first")
    lastKey = mc.findKeyframe(timeSlider=True, which="last")
    mc.playblast(startTime=firstKey, endTime=lastKey)
Esempio n. 41
0
    def writeFile(self,*args):
        self.infoDict = {} #redefines self.infoDict
        self.selection = cmds.ls(sl = True) #gets names of selected objects
        poseQuery = cmds.textFieldGrp(self.fileName, q = True, text = True) #queries the pose name text field
        charQuery = cmds. textScrollList(self.folderName, q = True, selectItem = True) #queries the folder name text scroll list

        if self.selection == []: #if selection is empty, raises a warning
            cmds.warning('Please make a selection!!')
        elif not poseQuery: #if pose is not named, raises a warning
            cmds.warning('Please name the pose!!')
        
        if not charQuery: #if a character is not selected, raises a warning
            cmds.warning('Please select a character!!')
    
        poses = os.listdir(self.fileLoc + '/Characters/'+ charQuery[0]) #gets files in directory
        poseFile =('POSE_' + poseQuery + '.txt') #gets pose name
        if poseFile in poses: # if a file with the same name already exists, raises a warning.
            cmds.warning('There is already a pose with that name!!')
            return False
        else: #else: runs writeFile
            cmds.select(cl=True)	#clears selection
            self.outputDict()
            # Get file name from user and write to file
            self.fileNameQuery = cmds.textFieldGrp(self.fileName,query=True,text=True) #queries the file name
            if (self.fileNameQuery =='') or (self.fileNameQuery == 'Please enter desired file name'):
                cmds.warning('Please name the file!') #if the text box is empy, requests input.
            else:
                self.folderQuery = cmds.textScrollList(self.folderName, q = True, selectItem = True)  #Queries the text scroll list for character name
                self.listFiles = os.listdir(self.fileLoc + "/Characters") #lists files in the characters directory
                if not self.folderQuery: #if there's nothing selected, raises a warning
                    cmds.warning('Select a character!!')
                else:
                    self.listSubFiles = os.listdir(self.fileLoc + '/Characters/' + self.folderQuery[0]) #lists the files in the character folder
                    self.listToAdd = [] #defines listToAdd
                    cmds.textScrollList(self.poseToLoad, e= True, removeAll = True)  #empties the textScrollList
                    with open(self.fileLoc + '/Characters/' +self.folderQuery[0] + '/POSE_' + self.fileNameQuery + '.txt', "w+") as fileOpen: #opens the file
                        fileOpen.write(cPickle.dumps (self.infoDict)) #dumps cpickle into file
                        fileOpen.close() #closes file
                        charQuery = cmds.textScrollList(self.folderName, q = True, selectItem = True) #Queries the character name
                        poseQuery = cmds.textFieldGrp(self.fileName, q = True, text = True) #queries the pose name
                        picName = (self.fileLoc + '/Images/'+ charQuery[0] + '/POSE_' + poseQuery) # defines pic name
                        picNameB = (picName) #is useless
                        cmds.playblast(format  = 'image', frame = 1, f = picNameB) #creates image for preview
                        self.listDir = os.listdir(self.fileLoc + "/Characters/" + self.folderQuery[0]) # lists the directory
                # Update option Menu
                #if item is not in the list, adds it to directory
            if not self.folderQuery: 
                cmds.warning('Please select a character!!')
            else:    
                for items in os.listdir(self.fileLoc  + "/Characters/"+ self.folderQuery[0]):# for every item in the pose directory
                    if items not in self.listToAdd:#if the item is not in the list to add
                        self.listToAdd.append(items) #adds it to the list
                        cmds.deleteUI(self.poseToLoad) # delete the UI element
                        self.poseToLoad = cmds.textScrollList(parent = self.refreshLayout, numberOfRows=8, allowMultiSelection= False, append = self.listToAdd, sc = self.refreshPic, en = True) #recreates the UI element
                    else:
                        cmds.warning('There is already a pose with that name!') #raises a warning
            if not self.folderQuery: 
                cmds.warning('Please Select a character') #raises a warning
 def get_thumbnail(self):
     for camera in mc.listCameras():
         if camera == "persp":
             pass
         else:
             mm.eval("viewFit -all;")
             mc.lookThru(camera)
             mc.playblast( cf= "H:\\Image Test\\" + camera + ".jpg" , fr=1, fmt="image", v=False, wh=[500, 300], orn=False,
                 compression="jpg", quality=100, percent=100 )
Esempio n. 43
0
    def GeneratePlayblast(self, extraArg=None):
        prefixText = Cmds.textField(self.prefixTextBox, q=True, text=True)
        if not IsNoneOrEmpty(prefixText):
            prefixText = "%s_" % prefixText

        cameraName = 'persp'
        blackThick = 1
        horizontalResolution = 320
        verticalResolution = 240
        scalePercentage = 100

        if not Cmds.objExists(cameraName):
            self.MessageBox(
                'Playblast generation requires a camera named %s.' %
                (cameraName), 'Playblast pre-requisite error')
            return

        self.PlayblastDisplayEnable(False)

        directoryName = os.path.dirname(Cmds.file(q=True, sn=True))
        if not directoryName:
            self.MessageBox('Please save Maya file before blasting!')
            return

        selectedCount = self.CountSelected()
        if selectedCount == 0:
            self.MessageBox('Please select animations to blast!')
            return

        self.StartProgressBar('Generating Playblast', selectedCount)
        for animation in self.sequencer.Animations.values():
            if self.IsProgressBarCanceled():
                self.EndProgressBar()
                self.MessageBox('Playblast generation canceled by the user')
                return

            if animation.Selected == True:
                self.SetPlaybackRange(animation.StartFrame, animation.EndFrame)

                movieFilename = self.GetPlayblastMovieFilename(
                    directoryName, prefixText, animation)
                Cmds.playblast(format='movie',
                               filename=movieFilename,
                               clearCache=True,
                               viewer=False,
                               showOrnaments=True,
                               fp=4,
                               percent=scalePercentage,
                               compression='none',
                               widthHeight=(horizontalResolution,
                                            verticalResolution),
                               fo=True)
                self.StepProgressBar(1)

        self.EndProgressBar()
        self.MessageBox('Playblast generation complete!')
Esempio n. 44
0
def _generate_quicktime(quicktime_path):
    """
    Returns a Quicktime object with info about the generated quicktime.
    """

    quicktime_dir = os.path.dirname(quicktime_path)

    if not os.path.exists(quicktime_dir):
        try:
            os.makedirs(quicktime_dir)
        except os.error as e:
            return Quicktime(
                success=False,
                error_msg=str(e),
                frame_count=None,
                frame_range=None,
                first_frame=None,
                last_frame=None,
                path=None,
            )

    # use the min/max frames from frame slider
    first_frame = int(cmds.playbackOptions(query=True, minTime=True))
    last_frame = int(cmds.playbackOptions(query=True, maxTime=True))

    # initiate the playblast
    try:
        cmds.playblast(
            compression="jpeg",
            endTime=last_frame,
            filename=quicktime_path,
            forceOverwrite=True,
            format="movie",
            offScreen=True,
            startTime=first_frame,
            viewer=False,
        )
    except Exception as e:
        error_msg = str(e)
        success = False
    else:
        error_msg = None
        success = True

    # return all the info for the new quicktime
    return Quicktime(
        success=success,
        error_msg=error_msg,
        frame_count=int(last_frame - first_frame + 1),
        frame_range="{f}-{l}".format(f=first_frame, l=last_frame),
        first_frame=first_frame,
        last_frame=last_frame,
        path=quicktime_path,
    )
Esempio n. 45
0
def snapshot(path = None, width = 96, height = 96):
    current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png
    #path = "/Users/liorbenhorin/Library/Preferences/Autodesk/maya/2015-x64/scripts/pipeline/thumb.png"
    cmds.playblast(cf = path, fmt="image", frame = cmds.currentTime( query=True ), orn=False, wh = [width,height], p=100, v=False)
    cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
    
    if os.path.isfile(path):
        return path
    else:
        return False
Esempio n. 46
0
def playblast(path = None,format = None, compression = None, hud = None, offscreen = None, range=None, scale = None):
    if range is None:
        
        range = playback_selection_range()
        print range
        if range is None:
        
            start = cmds.playbackOptions( q=True,min=True )
            end  = cmds.playbackOptions( q=True,max=True )
            range = [start, end]
 	
    cmds.playblast(startTime =range[0] ,endTime =range[1], f = path, fmt=format,  orn=hud, os=offscreen, wh = scene_resolution(), p=scale, qlt=90,c=compression, v=True, s = qeury_active_sound_node())
Esempio n. 47
0
def SundayWarehouseViewPortCreateIcon():
    iconFile = cmds.internalVar(userTmpDir = True) + 'SundayWarehouseIcon_' + time.strftime('%a-%d-%b-%Y_%H-%M-%S', gmtime()) + '.png'
    iconSize = [
        512,
        512]
    curRenderImage = cmds.getAttr('defaultRenderGlobals.imageFormat')
    cmds.setAttr('defaultRenderGlobals.imageFormat', 32)
    cmds.playblast(forceOverwrite = True, framePadding = 0, viewer = False, showOrnaments = False, frame = cmds.currentTime(query = True), widthHeight = iconSize, percent = 100, format = 'iff', compression = 'png', filename = iconFile)
    cmds.setAttr('defaultRenderGlobals.imageFormat', curRenderImage)
    icon = iconFile + '.0.png'
    cmds.iconTextButton('iconImage', edit = True, image = icon)
    cmds.button('whCreateIcon', edit = True, label = 'Re-Create Icon')
Esempio n. 48
0
def thumbnailFromPlayBlast(filepath, width, height):
    '''
    Generate a ThumbNail of the screen
    Note: 'cf' flag is broken in 2012
    :param filepath: path to Thumbnail
    :param width: width of capture
    :param height: height of capture
    '''
    filepath=os.path.splitext(filepath)[0]
    filename=os.path.basename(filepath)
    filedir=os.path.dirname(filepath)
    
    #get modelPanel and camera
    win = cmds.playblast(activeEditor=True).split('|')[-1]
    cam = cmds.modelPanel(win, q=True, camera=True)
    if not cmds.nodeType(cam) == 'camera':
        cam = cmds.listRelatives(cam)[0]
    
    storedformat = cmds.getAttr('defaultRenderGlobals.imageFormat')
    storedResolutionGate = cmds.getAttr('%s.filmFit' % cam)
    
    cmds.setAttr('defaultRenderGlobals.imageFormat', 20)
    cmds.setAttr('%s.filmFit' % cam, 2)  # set to Vertical so we don't get so much overscan
    
    cmds.playblast(frame=cmds.currentTime(q=True),  # startTime=cmds.currentTime(q=True),
                          # endTime=cmds.currentTime(q=True),
                          format="image",
                          filename=filepath,
                          width=width,
                          height=height,
                          percent=100,
                          quality=90,
                          forceOverwrite=True,
                          framePadding=0,
                          showOrnaments=False,
                          compression="BMP",
                          viewer=False)
    cmds.setAttr('defaultRenderGlobals.imageFormat', storedformat)
    cmds.setAttr('%s.filmFit' % cam, storedResolutionGate)
    #Why do this rename? In Maya2012 the 'cf' flag fails which means you have to use
    #the 'f' flag and that adds framePadding, crap I know! So we strip it and rename
    #the file after it's made.
    try:
        newfile=[f for f in os.listdir(filedir)
                 if f.split('.bmp')[0].split('.')[0] == filename and not
                 '.pose' in f]
        log.debug('Original Playblast file : %s' % newfile)
        os.rename(os.path.join(filedir, newfile[0]), '%s.bmp' % filepath)
        log.debug('Thumbnail Renamed : %s' % ('%s.bmp' % filepath))
        return '%s.bmp' % filepath
    except:
        pass
Esempio n. 49
0
 def capture(s, pixels, camera, frame):
     """
     Capture a thumbnail
     """
     # Validate our inputs
     if not cmds.objExists(camera):
         raise RuntimeError, "%s does not exist." % camera
     if not pixels or type(pixels) != int:
         raise RuntimeError, "No valid size provided"
     # Collect information:
     view = cmds.playblast(activeEditor=True) # Panel to capture from
     state = cmds.modelEditor(view, q=True, sts=True)
     oldFrame = cmds.currentTime(q=True) # Get current time
     imgFormat = cmds.getAttr("defaultRenderGlobals.imageFormat")
     selection = cmds.ls(sl=True) # Current selection
     with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as f: path = Temp_Path(f.name)
     # Capture our thumbnail
     try:
         cmds.currentTime(frame)
         cmds.select(cl=True) # Clear selection for pretty image
         cmds.setAttr("defaultRenderGlobals.imageFormat", 32)
         cmds.modelEditor( # Tweak nice default visuals
             view,
             e=True,
             grid=False,
             camera=camera,
             da="smoothShaded",
             allObjects=False,
             nurbsSurfaces=True,
             polymeshes=True,
             subdivSurfaces=True,
             displayTextures=True,
             )
         cmds.playblast(
             frame=frame, # Frame range
             fo=True, # Force override the file if it exists
             viewer=False, # Don't popup window during render
             width=pixels*2, # Width in pixels, duh
             height=pixels*2, # Height in pixels. Who knew
             showOrnaments=False, # Hide tools, ie move tool etc
             format="image", # We just want a single image
             completeFilename=f.name.replace("\\", "/") # Output file
             )
     # # Put everything back as we found it.
     finally:
         # Reset options
         cmds.currentTime(oldFrame)
         cmds.select(selection, r=True)
         cmds.setAttr("defaultRenderGlobals.imageFormat", imgFormat)
         mel.eval("$editorName = \"%s\"" % view)
         mel.eval(state)
     return path
Esempio n. 50
0
def viewportSnapshot():
	"""
	This definition does a viewport snapshot.
	"""

	filter = "Tif files (*.tif)"
	file = cmds.fileDialog2(fileFilter=filter, fm=0, dialogStyle=2)

	if file:
		imageFormat = cmds.getAttr("defaultRenderGlobals.imageFormat")
		cmds.setAttr("defaultRenderGlobals.imageFormat", 3)
		cmds.playblast(frame=[cmds.getAttr("time1.outTime")], format="image", os=True, quality=100, p=100, cf=file[0])
		cmds.setAttr("defaultRenderGlobals.imageFormat", imageFormat)
def userPlayblast(whichC, whichCode, width, height, percentt):
    if whichC == "":
        efile = checkFile()
    else:
        efile = checkFileE(whichC)
    whatVison = mayaVision()
    soundNodes = mc.ls(type="audio")
    cameraToUse = checkCam()
    showTexture = 1
    # pfile = checkFile()
    # width = size[0]
    # height = size[1]
    # widthS = sizeS[0]
    # heightS = sizeS[1]
    pfile = checkFile()
    try:
        if soundNodes != []:
            mc.playblast(
                format=ext,
                sound=soundNodes[0],
                filename=efile,
                forceOverwrite=1,
                sequenceTime=0,
                clearCache=1,
                viewer=1,
                showOrnaments=1,
                fp=4,
                percent=percentt,
                compression=whichCode,
                quality=70,
                widthHeight=(width, height),
            )
        else:
            mc.playblast(
                format=ext,
                filename=efile,
                forceOverwrite=1,
                sequenceTime=0,
                clearCache=1,
                viewer=1,
                showOrnaments=1,
                fp=4,
                percent=percentt,
                compression=whichCode,
                quality=70,
                widthHeight=(width, height),
            )
    except:
        mc.warning("Playblast:failed")
Esempio n. 52
0
	def playblast(self, frames):
		'''Playblasts the current range to the project's 'pencil' folder'''
		
		#make sure the projects pencil path and name.data path exists
		self.initPaths()
		
		filename = os.path.join(self.data['pencilDataPath'], self.name)
		
		#temporarily set image format to png
		curTime = cmds.currentTime(q=True)#remember current time
		oldFormat = cmds.getAttr('defaultRenderGlobals.imageFormat')#remember image format
		cmds.setAttr('defaultRenderGlobals.imageFormat', 32)
		cmds.playblast(filename=filename, frame=frames, format='image', forceOverwrite=True, framePadding=4, w=self.data['res'][0], h=self.data['res'][1], percent=100, viewer=False)
		cmds.setAttr('defaultRenderGlobals.imageFormat', oldFormat)#restore last image format
		cmds.currentTime(curTime)#restore current time
Esempio n. 53
0
    def start(self):
        self.setRenderGlobals()
        self.setDisplay()
        self.setHUD()

        cmds.playblast(filename=os.path.join(self.pathName, self.fileName),
                       fo=True, fp=4, orn=True, 
                       wh = (960, 540), 
                       format='qt', percent=100, compression='H.264', quality=100, 
                       st=self.range[0], et=self.range[1])

        self.delHUD()


#blast = PlayBlaster()
#blast.start()
    def _publish_playblast_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb):
        """
        Export playblast video for the specified item and publish it
        to Shotgun.
        """
        camera_name = item["name"].strip("|")
        tank_type = output["tank_type"]
        publish_template = output["publish_template"]        

        # get the current scene path and extract fields from it
        # using the work template:
        scene_path = os.path.abspath(cmds.file(query=True, sn=True))
        fields = work_template.get_fields(scene_path)
        #publish_version = fields["version"]
        
        # create the publish path by applying the fields 
        # with the publish template:
        playblast_path = publish_template.apply_fields(fields)
        
        
        # build and execute the Alembic export command for this item:
        height = 360
        width = 640
        #abc_export_cmd = "AbcExport -j \"-frameRange 1 100 -stripNamespaces -uvWrite -worldSpace -wholeFrameGeo -writeVisibility %s -file %s\"" % (nodesString,publish_path)    
        try:
            mov = cmds.playblast(f=playblast_path,format='qt',forceOverwrite=True,offScreen=True,percent=100,compression='H.264',quality=100,width=width,height=height,viewer=False)
        except Exception, e:
            raise TankError("Failed to export Playblast: %s" % e)
Esempio n. 55
0
def captureScreen(dst, format, st, sequencer, w, h) : 
	mm.eval('setAttr "defaultRenderGlobals.imageFormat" 8;')
	outputFile = dst.split('.')[0]
	extension = dst.split('.')[-1]

	start = st
	end = start

	result = mc.playblast( format= 'iff' ,
							filename= outputFile,
							st=start ,
							et=end ,
							forceOverwrite=True ,
							sequenceTime=sequencer ,
							clearCache=1 ,
							viewer= 0 ,
							showOrnaments=1 ,
							fp=4 ,
							widthHeight= [w,h] ,
							percent=100 ,
							compression= format ,
							offScreen=True ,
							quality=70
							)


	if result : 
		padding = '%04d' % start 
		output = result.replace('####', padding)
		if os.path.exists(dst) : 
			os.remove(dst)
		os.rename(output, dst)

		return dst
Esempio n. 56
0
def playblast( movFil ):
	"""main playblast function
	param path: string for the path for the playblast"""
	mm.eval( 'setAllMainWindowComponentsVisible 0;' )
	try:
		resNode = mn.Node( 'defaultResolution' )
		#resolution = [ resNode.a.width.v, resNode.a.height.v ]
		resolution = [ 1280, 720 ]
		#CREATE PLAYBLAST
		#write files in tmp dir
		mc.setAttr ('defaultRenderGlobals.imageFormat',32)
		tmpFile = tempfile.gettempdir() + '/playblastTmp/' + movFil.name
		asd = mc.playblast( format = "image", filename = tmpFile, forceOverwrite = True, viewer = 0, showOrnaments = 0, percent = 100, widthHeight = resolution )
		print asd
	finally:
		mm.eval( 'setAllMainWindowComponentsVisible 1;' )
	#ADD FRAME NUMBERS
	print tmpFile + '.png'
	#sqFil.sequenceFile( tmpFile + '.png' ).insertFrameNumber( tempfile.gettempdir() + '/playblastTmp/', 1, movFil.name )
	#EXPORT MOV FILE
	audioPath = ''
	audio =[a for a in  mn.ls( typ = 'audio' ) if a.a.mute.v == 0]
	if audio:
		audioPath = audio[0].a.filename.v
	fps = { 'film':24, 'pal':25 }
	curFps = mc.currentUnit( q = True, time=True)
	sqFile = sqFil.sequenceFile( tmpFile + '.png' )
	sqFile.createMov( movFil.dirPath.replace( '\\', '/').replace('//','/'), audioPath, fps[curFps], movFil.name )
	os.system("start "+ str( movFil.path ) )
	shutil.rmtree( tempfile.gettempdir() + '/playblastTmp/' )
Esempio n. 57
0
def playblast_snapshot(path = None,format = None, compression = None, hud = None, offscreen = None, range=None, scale = None):
    current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png

    if range is None:
        
        range = playback_selection_range()
        print range
        if range is None:
        
            start = cmds.playbackOptions( q=True,min=True )
            end  = cmds.playbackOptions( q=True,max=True )
            range = [start, end]
 	
    cmds.playblast(frame =int((range[0] + range[1])/2), cf = path, fmt="image",  orn=hud, os=offscreen, wh = scene_resolution(), p=scale, v=False) 
    
    cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
Esempio n. 58
0
def createThumbnail( width=450 , height=300 ) :

	currentUserPath = os.path.normpath( os.path.expanduser('~') )
	tmpFilePath = os.path.join(
									currentUserPath ,
									'playblastTemp'
								)
	
	oWidth = mc.getAttr( 'defaultResolution.width' )
	oHeight = mc.getAttr( 'defaultResolution.height' )
	
	# width = 450
	# height = 300

	frame = mc.currentTime( q=True )

	args = {
				'format' : 'iff' ,
				'filename' : tmpFilePath ,
				'frame' : frame ,
				'forceOverwrite' : True ,
				'clearCache' : True ,
				'viewer' : 0 ,
				'showOrnaments' : 0 ,
				'fp' : 4 ,
				'percent' : 100 ,
				'quality' : 100 ,
				'width' : width ,
				'height' : height ,
				'offScreen' : True ,
				'indexFromZero' : True
			}

	mc.setAttr( 'defaultResolution.aspectLock' , False )
	mc.setAttr( 'defaultResolution.width' , width )
	mc.setAttr( 'defaultResolution.height' , height )
	
	mc.setAttr( 'defaultRenderGlobals.imageFormat' , 32 )
	mc.playblast( **args )

	# mc.setAttr( 'defaultResolution.width' , oWidth )
	# mc.setAttr( 'defaultResolution.height' , oHeight )
	
	blastFilePath = '%s%splayblastTemp.0000.png' % ( currentUserPath , os.sep )
	return blastFilePath
Esempio n. 59
0
def custom_playblast():
	global cppercentage, cpname, cpincremental
	current_project = cmds.workspace(rd=True,q=True)
	cppercentage_value = cmds.floatSliderGrp(cppercentage,q=True,v=True)
	cpname_value = cmds.textFieldGrp(cpname,q=True,tx=True)
	cpincremental_value = cmds.checkBox(cpincremental,q=True,v=True)

	if(cpincremental_value):
		file_name = cpname_value+"_"
		files = os.listdir(current_project)
		file_inc = 0
		for f in files:
			if(re.match(cpname_value+"_\d",f)):
				file_inc += 1
		file_name = file_name + str(file_inc)
		cmds.playblast( p=cppercentage_value, f=current_project+file_name, v=False )
	else:
		cmds.playblast( p=cppercentage_value, f=current_project+cpname_value, v=False,fo=True)