예제 #1
0
    def _applyStartFrameOverride(self):
        """
		If a start frame override has been set, then adjust the sequence start frames
		for all audio and video clips so that the earliest shot/audio that we created
		is at the specified frame.
		"""
        if self.startFrameOverride is None or self.minFrameInFile is None:
            return

        offset = (self.minFrameInFile - self.startFrameOverride)

        for clip in self.clip_dict.itervalues():
            if clip is None:
                # TODO: raise warning here. We failed to create a matching
                # shot/audio node for some reason
                pass
            else:
                type = cmds.nodeType(clip)
                if type == "shot":
                    start = float(cmds.shot(clip, q=1,
                                            sequenceStartTime=1)) - offset
                    end = float(cmds.shot(clip, q=1,
                                          sequenceEndTime=1)) - offset
                    cmds.shot(clip,
                              e=1,
                              sequenceStartTime=start,
                              sequenceEndTime=end)
                elif type == "audio":
                    start = float(cmds.sound(clip, q=1, offset=1)) - offset
                    cmds.sound(clip, e=1, offset=start)
예제 #2
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)
예제 #3
0
    def setTimeSlider(*args):
        mode = cmds.radioButtonGrp(UI.widgets['timeSldrRadBtn'],
                                   q=True,
                                   select=True)

        if mode == 1:
            nModeStart = cmds.textField(UI.widgets['timeSldrNrmStartTxtFld'],
                                        q=True,
                                        text=True)
            nModeEnd = cmds.textField(UI.widgets['timeSldrNrmEndTxtFld'],
                                      q=True,
                                      text=True)
            cmds.playbackOptions(minTime=nModeStart)
            cmds.playbackOptions(maxTime=nModeEnd)
            cmds.currentTime(nModeStart)
        elif mode == 2:
            tModeDur = float(
                cmds.textField(UI.widgets['timeSldrTimeDurTxtFld'],
                               q=True,
                               text=True))
            tModeStart = float(
                cmds.textField(UI.widgets['timeSldrTimeStartTxtFld'],
                               q=True,
                               text=True))
            curTime = cmds.currentUnit(q=True, time=True)
            if curTime == 'film':
                fps = 24
            elif curTime == 'pal':
                fps = 25
            elif curTime == 'ntsc':
                fps = 30
            durFrameLen = tModeDur * fps
            tModeEnd = (tModeStart + durFrameLen) - 1
            cmds.playbackOptions(minTime=tModeStart)
            cmds.playbackOptions(maxTime=tModeEnd)
            cmds.currentTime(tModeStart)
        elif mode == 3:
            mel.eval('source "updateSoundMenu.mel";')
            sModeSndPath = cmds.textField(
                UI.widgets['timeSldrSoundPathTxtFld'], q=True, text=True)
            sModeStart = int(
                cmds.textField(UI.widgets['timeSldrSoundStartTxtFld'],
                               q=True,
                               text=True))
            sndNode = cmds.sound(offset=sModeStart, file=sModeSndPath)
            soundLength = round(cmds.sound(sndNode, q=True, length=True)) - 1
            sModeEnd = sModeStart + soundLength
            cmds.playbackOptions(minTime=sModeStart)
            cmds.playbackOptions(maxTime=sModeEnd)
            cmds.currentTime(sModeStart)
            gPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider')
            cmds.timeControl(gPlayBackSlider, edit=True, sound=sndNode)
            mel.eval('setSoundDisplay %s 1;' % (sndNode))
예제 #4
0
def openFile():
   """
   Function to open a new wav file into the scene. 
   
   Creates a new Maya sound node and changes the timeslider to use the audio for playback while scrubbing.
   
   Prepares the wav file for reading audio data.
   
   Adjusts the UI to display the current audio parameters and progress bar for the new track.
   """
   global wavFile, params, frames
   
   #open file dialog
   fileNameList = cmds.fileDialog2(cap="Choose Audio File...", ff="*.wav", fm=4, ds=2, okc="Open")
   
   #convert result from dialog box to a useable string
   fileName = str(fileNameList[0])   
   
   #load the file name into the info text area in the UI
   cmds.text('currentAudioPath', edit=True, label="Currently Loaded: "+fileName)
   
   #delete any existing audio nodes
   if(cmds.objExists('audio')):
      cmds.select('audio')
      cmds.delete()
   
   #create a new sound node
   cmds.sound(f=fileName, n="audio")
   
   #set the 'audio' node to be the audio for the timeline.
   #--------- code from documentation starts here ------------#
   gPlayBackSlider = mel.eval( '$tmpVar=$gPlayBackSlider' )
   cmds.timeControl( gPlayBackSlider, edit=True, sound='audio', displaySound=True)
   #--------- code from documentation ends here -------------#
   
   #set the playback range to the range of the audio
   cmds.playbackOptions(min=0, aet=(cmds.getAttr('audio.duration')), max=(cmds.getAttr('audio.duration')))
   
   #------- set up the stream -------#
   wavFile = wave.open(fileName)   
   params = wavFile.getparams()   
   frames = wavFile.readframes(params[3])
   
   #update the info text with the audio parameters.
   cmds.text('currentParams', edit=True, label=str(params))
   
   #set the max of the progress bar to the number of audio frames in the selected track
   cmds.progressBar('progress', edit=True, maxValue = params[3])
   
   print "Result: ",fileName, "has been loaded."
예제 #5
0
    def _writeTrack(self, seq_elem, isVideo, nodeList, trackNumber):
        """
		Write the video/audio track. nodeList is a list of all shot/audio nodes in
		the track.
		"""
        track_info = {"type": ("audio", "video")[isVideo]}

        numLocked = 0
        numEnabled = 0

        sortedNodeList = nodeList

        if isVideo:
            sortedNodeList.sort(videoClipCompare)
        else:
            sortedNodeList.sort(audioClipCompare)

        for clip in sortedNodeList:
            if isVideo:
                numLocked = numLocked + int(cmds.shot(clip, q=1, lock=1))
                numEnabled = numEnabled + int(not cmds.shot(clip, q=1, mute=1))
            else:
                numEnabled = numEnabled + int(
                    not cmds.sound(clip, q=1, mute=1))

        track_info["locked"] = (numLocked == len(nodeList))
        track_info["enabled"] = (numEnabled == len(nodeList))
        track_info["trackNumber"] = trackNumber

        track_elem = self.translator.writeTrack(seq_elem, track_info)

        for clip in sortedNodeList:
            self._writeClip(track_elem, isVideo, clip)
예제 #6
0
    def load(self, context, name, namespace, data):

        start_frame = cmds.playbackOptions(query=True, min=True)
        sound_node = cmds.sound(
            file=context["representation"]["data"]["path"], offset=start_frame
        )
        cmds.timeControl(
            mel.eval("$tmpVar=$gPlayBackSlider"),
            edit=True,
            sound=sound_node,
            displaySound=True
        )

        asset = context["asset"]["name"]
        namespace = namespace or lib.unique_namespace(
            asset + "_",
            prefix="_" if asset[0].isdigit() else "",
            suffix="_",
        )

        return containerise(
            name=name,
            namespace=namespace,
            nodes=[sound_node],
            context=context,
            loader=self.__class__.__name__
        )
예제 #7
0
def getSoundInfo():
    gPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider')  # seriously maya?
    sound = cmds.timeControl(gPlayBackSlider, q=True, sound=True)
    if sound:
        soundfile = cmds.sound(sound, q=True, file=True)
        soundOffset = cmds.getAttr('%s.offset' % sound)
        return str(soundfile), soundOffset
    else:
        return None, None
예제 #8
0
def get_current_sound():
    
    playback_slider = mel.eval('$tmpVar = $gPlayBackSlider')
    if not playback_slider:
        print '# Could not get gPlayBackSlider'
        return
    
    sound_node = cmds.timeControl(playback_slider, query=True, sound=True)
    if not sound_node:
        cmds.warning('No sound node.')
        return
    
    return cmds.sound(sound_node, query=True, file=True)
def FaceCapImportAudio(filePath):
    dirName, fileName = ntpath.split(filePath)
    name, extension = os.path.splitext(fileName)
    audioPath = ntpath.join(dirName, name + ".wav")
    print("AudioPath:" + audioPath)

    if os.path.exists(audioPath):
        cmds.currentTime('0sec', edit=True)
        audioNode = cmds.sound(offset=0, file=audioPath)
        gPlayBackSlider = maya.mel.eval('$tmpVar=$gPlayBackSlider')
        cmds.timeControl(gPlayBackSlider, edit=True, sound=audioNode)
    else:
        print("Audio not found, load it manually.")
예제 #10
0
    def load(self, context, name, namespace, data):
        start_frame = cmds.playbackOptions(query=True, min=True)
        sound_node = cmds.sound(
            file=context["representation"]["data"]["path"], offset=start_frame
        )
        cmds.timeControl(
            mel.eval("$tmpVar=$gPlayBackSlider"),
            edit=True,
            sound=sound_node,
            displaySound=True
        )

        return [sound_node]
예제 #11
0
    def _writeClip(self, track_elem, isVideo, clip):

        # Note: we'll make the clip name and id the same as the maya node-name
        # used for linking of audio and video
        clip_info = {"name": clip, "id": clip}

        if isVideo:
            seqStartTime = cmds.shot(clip, q=1, sequenceStartTime=1)
            clip_info["duration"] = cmds.shot(clip, q=1, sequenceDuration=1)
            clip_info["start"] = seqStartTime

            # Final frame in editorial is always exclusive (bug 342715), but it
            # is not in Maya, so we must add 1 at the end here when exporting
            seqEndTime = cmds.shot(clip, q=1, sequenceEndTime=1) + 1
            clip_info["end"] = seqEndTime
            clip_info["enabled"] = not cmds.shot(clip, q=1, mute=1)

            inTime = cmds.shot(clip, q=1, clipZeroOffset=1)
            clip_info["in"] = inTime
            clip_info["out"] = inTime + seqEndTime - seqStartTime

            # TODO: pre/post hold

        else:
            seqOffset = cmds.sound(clip, q=1, offset=1)
            silence = float(cmds.getAttr((clip + ".silence")))
            mediaIn = cmds.sound(clip, q=1, sourceStart=1)
            mediaOut = cmds.sound(clip, q=1, sourceEnd=1)
            clip_info["start"] = (seqOffset + silence)
            clip_info["end"] = seqOffset + silence + mediaOut - mediaIn
            clip_info["in"] = mediaIn
            clip_info["out"] = mediaOut
            clip_info["duration"] = mediaOut - mediaIn
            clip_info["enabled"] = not cmds.sound(clip, q=1, mute=1)

        clip_elem = self.translator.writeClip(track_elem, clip_info)

        # Note: we won't be able to open this up unless we have a file.
        # So even if there's no file, create a dummy one
        file_info = {"name": clip}

        if isVideo:
            imagePlane = cmds.shot(clip, q=1, clip=1)
            if imagePlane is not None:
                try:
                    # Using Maya API to get absolute path for the image plane media
                    node = _nameToNode(imagePlane)
                    file_info["pathurl"] = OpenMayaRender.MRenderUtil(
                    ).exactImagePlaneFileName(node)
                except:
                    file_info["pathurl"] = cmds.getAttr(imagePlane +
                                                        ".imageName")
                file_info["duration"] = cmds.shot(clip, q=1, clipDuration=1)
        else:
            file_info["pathurl"] = cmds.sound(clip, q=1, file=1)
            file_info["duration"] = cmds.sound(clip, q=1, length=1)

        file_elem = self.translator.writeFile(clip_elem, file_info)
예제 #12
0
 def getSndPath(*args):
     sndList = cmds.ls(type='audio')
     if sndList:
         sndPath = cmds.sound(sndList[0], q=True, file=True)
         startDir = os.path.dirname(sndPath)
     else:
         curScenePath = cmds.file(q=True, sceneName=True)
         startDir = os.path.dirname(curScenePath)
     sndPath = cmds.fileDialog2(fileMode=1,
                                caption='Import Sound',
                                startingDirectory=startDir)[0]
     cmds.textField(UI.widgets['timeSldrSoundPathTxtFld'],
                    e=True,
                    text=sndPath)
예제 #13
0
def sound(path=True):
    gPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider')
    node = cmds.timeControl(gPlayBackSlider, q=True, sound=True)
    if not path:
        return node
    else:
        if node:
            fileName = cmds.sound(node, q=True, f=True)
            if fileName:
                # print fileName
                return fileName
            else:
                return None
        else:
            return False
예제 #14
0
파일: key_ui.py 프로젝트: boochos/work
    def geoCacheCMD(self, *args):
        # get the selection list
        sel = cmds.ls(selection=True)
        passSel = True
        for each in sel:
            relatives = cmds.listRelatives(each)
            if relatives != None:
                if cmds.nodeType(relatives[0]) != 'mesh':
                    passSel = False
                    break
            else:
                passSel = False

        if self.pathTextField != None and passSel == True and len(sel) != 0:
            cacheList = []
            # get the path so write the cache to
            path = cmds.textField(self.pathTextField, query=True, text=True)

            # get the file name
            filename = cmds.text(self.nameTxt, query=True, label=True)
            # check to see if the current folder exists
            finalPath = os.path.join(path, filename)
            isDir = os.path.isdir(finalPath)
            if (isDir):
                key_sys_lib.printMayaWarning('Conflict!!!')
                key_sys_lib.printMayaWarning(finalPath + ' all ready exists')
                key_sys_lib.printMayaWarning('Geometry Cache aborted.....')
            else:
                import maya.mel as mm
                # create the output directory
                os.mkdir(finalPath, 0777)
                gPlayBackSlider = mm.eval('$tmpVar = $gPlayBackSlider')
                minRange = cmds.playbackOptions(query=True, minTime=True) - 1
                maxRange = cmds.playbackOptions(query=True, maxTime=True) + 1
                useAudio = cmds.checkBox(self.checkBox, query=True, v=True)
                if useAudio == 1:
                    soundNode = cmds.timeControl(gPlayBackSlider, query=True, sound=True)
                    if len(soundNode) > 0:
                        maxRange = str(cmds.sound(soundNode, query=True, length=True) + 1).split('.')[0]
                    else:
                        key_sys_lib.printMayaWarning('Use Audio Length is selected, but there is no audio in the timeline. Using Animation slider range.')
                for each in sel:
                    # extract the shape node
                    cacheList.append(cmds.listRelatives(each, shapes=True)[0])

                mm.eval('doCreateGeometryCache 4 { "0", "' + str(minRange) + '", "' + str(maxRange) + '", "OneFilePerFrame", "0", "' + finalPath + '","0","' + filename + '","0", "add", "1", "1", "1","0","1"}')
        else:
            print 'Select a valid mesh to Geometry Cache.'
예제 #15
0
def get_current_audio(start_frame=1):
    '''
    '''
    sound_file = 'audio.wav'
    if OpenMaya.MGlobal.mayaState() == OpenMaya.MGlobal.kInteractive:
        sound_node = mc.timeControl(
            mel.eval('string $temp = $gPlayBackSlider'), q=True, s=True)
        if sound_node:
            sound_file = mc.sound(sound_node, q=True, f=True)

    else:
        audios = mc.ls(typ='audio')
        for audio in audios:
            if mc.getAttr('{0}.offset'.format(audio)) == start_frame:
                sound_file = mc.getAttr('{0}.filename'.format(audio))
    return sound_file
예제 #16
0
    def importWav(self, *args):
        """
		function that is run when the 'import .wav file' button is pressed
		"""

        print self.widgets["wav_browser"].path
        try:
            self.widgets["audio"] = cmds.sound(
                f=self.widgets["wav_browser"].path, o=1)
        except IndexError:
            cmds.confirmDialog(
                t="No audio selected",
                m="Please open the file browser and select a .wav file")
        except RuntimeError:
            cmds.confirmDialog(t="No audio selected",
                               m="Please select a valid .wav file")
예제 #17
0
	def importWav(self, *args):
		"""
		function that is run when the 'import .wav file' button is pressed
		""" 

		print self.widgets["wav_browser"].path
		try:
			self.widgets["audio"] = cmds.sound(f = self.widgets["wav_browser"].path, o = 1)
		except IndexError:
			cmds.confirmDialog(
							t = "No audio selected",
							m = "Please open the file browser and select a .wav file")
		except RuntimeError:
			cmds.confirmDialog(
							t = "No audio selected",
							m = "Please select a valid .wav file")
예제 #18
0
	def SoundCheck(self):
		sSound = ''
		sOffset = ''

		#Get Current SoundTrack from timeslider
		aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
		sSoundTest = cmds.timeControl(aPlayBackSliderPython, q = True, sound = True)

		if sSoundTest:
			sSound = '"%s"'%cmds.sound( sSoundTest, q = True, f = True)


			iOffset = 0
			print sSound

			return [sSound, iOffset]
		else:
			return None
예제 #19
0
def importAudio(silent = False):
    mayaShot = ppc.MayaShot()
    if not mayaShot.validShot:
        msgWin("Error", "Invalid Shot or Project", silent)
        return False
    audioNodes = mc.ls(typ = "audio")
    if audioNodes:
        for aud in audioNodes:
            mc.delete(aud)
    audFilePath = os.path.join((mayaShot.projInfo.mapDrive + "/"), mayaShot.projInfo.soundFldr, mayaShot.epSqName, "sc-%s.wav"%mayaShot.shot)
    if os.path.exists(audFilePath):
        audnode = mc.sound(file = audFilePath, offset = 101, n = "%s%s_aud"%(mayaShot.epSqName, mayaShot.shName))
        setAudio = 'global string $gPlayBackSlider; timeControl -e -ds 1 -s "%s" $gPlayBackSlider;' % audnode
        mel.eval("%s" % setAudio)
        msgWin("Message", "Successfully imported audio : %s"%audFilePath, silent)
        return True
    else:
        msgWin("Error", "Audio file does not exist : %s"%audFilePath, silent)
        return False
예제 #20
0
    def SoundCheck(self):
        sSound = ''
        sOffset = ''

        #Get Current SoundTrack from timeslider
        aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
        sSoundTest = cmds.timeControl(aPlayBackSliderPython,
                                      q=True,
                                      sound=True)

        if sSoundTest:
            sSound = '"%s"' % cmds.sound(sSoundTest, q=True, f=True)
            sOffsetPath = '/'.join(aAllPath[1] + ['000.sound.rv'])
            sOffset = ''

            if os.path.exists(sOffsetPath):
                iOffset = None
                oRvFile = open(sOffsetPath, 'r')
                aLines = oRvFile.readlines()
                oRvFile.close()

                for line in aLines:
                    sLine = line.strip()
                    if 'float audioOffset = ' in sLine:
                        iOffset = float(sLine.split(' ')[-1])

                if iOffset:
                    sOffset = '''
					group
					{
						float audioOffset = %s
					}
					''' % iOffset

            else:
                cmds.warning(
                    '000.sound.rv not found! Better create NOW. (The offset value will be based on this file.)'
                )

        return [sSound, sOffset]
예제 #21
0
def get_current_sound():

    try:
        playback_slider = mel.eval('$tmpVar = $gPlayBackSlider')
    except RuntimeError:
        playback_slider = None
    if not playback_slider:
        print '# Could not get gPlayBackSlider'
        return

    sound_node = cmds.timeControl(playback_slider, query=True, sound=True)
    if not sound_node:
        cmds.warning('No sound node.')
        return

    sound_path = cmds.sound(sound_node, query=True, file=True)

    # Assert that it exists. It is a bit overkill to check it here, but all
    # we are doing is dumping it into the Maya log, so it isn't a big deal.
    if sound_path and os.path.exists(sound_path):
        return sound_path
    else:
        cmds.warning('Sound file (via node %s) at %s does not exist.' %
                     (sound_node, sound_path))
예제 #22
0
def add_audio(*_):
    cmds.sound(file=cmds.textField( mp3_input, query=True, text=True), name='sound_file')
    cmds.timeControl( 'timeControl1', edit=True, sound='sound_file' )
예제 #23
0
    def process(self, instance):
        shotAssetsDir = instance.data['shotAssetPath']

        versionDir = instance.data['vprefix'] + instance.data['version']

        cameraFile = os.path.join(shotAssetsDir, 'camera', 'renderCam.abc')

        publishDir = os.path.join(instance.data['publishDir'], versionDir)

        envFile = os.path.join(instance.data['publishDir'], 'env.mb')
        charFile = os.path.join(publishDir, 'char.mb')
        animFile = os.path.join(publishDir, 'animation_publish.mb')
        if 'image_planes' in instance.data:
            imagePlanes = instance.data['image_planes']
        else:
            imagePlanes = []

        metadata = instance.data['metadata']
        metadata['version'] = versionDir
        metadata['renderCam'] = cameraFile
        if os.path.exists(envFile):
            metadata['publish_env_file'] = envFile
        else:
            metadata['publish_env_file'] = ''
        if os.path.exists(charFile):
            metadata['publish_char_file'] = charFile
        else:
            metadata['publish_char_file'] = ''
        metadata['publish_anim_file'] = animFile
        instance.set_data('metadata', value=metadata)

        instance.context.set_data('nextTask', value='Animation')

        if os.path.exists(animFile):
            os.remove(animFile)

        mayaScript = "import maya.cmds as cmds;" \
                     "import maya.mel as mel;" \
                     "import maya.standalone; " \
                     "maya.standalone.initialize('Python'); " \
                     "cmds.loadPlugin('AbcImport');"
        if os.path.exists(charFile):
            copyfile(charFile, animFile)
            mayaScript += "cmds.file('%s', o=True, f=True);" % animFile
        else:
            mayaScript += "cmds.file(new=True, f=True);" \
                          "cmds.file(rename='%s');" % animFile

        audioNodes = cmds.ls(type='audio')
        if len(audioNodes) > 0:
            soundFile = cmds.sound(audioNodes[0], file=True, query=True)
            soundOffset = cmds.sound(audioNodes[0], offset=True, query=True)
            mayaScript += "cmds.file('%s', i=True, type='audio', options='o=%s');" % \
                          (soundFile, soundOffset)

        if os.path.exists(envFile):
            mayaScript += "cmds.file('%s', r=True);" % envFile

        if os.path.exists(cameraFile):
            mayaScript += "cmds.AbcImport('%s', mode='import');" % cameraFile

        if len(imagePlanes) > 0:
            for imagePlane in imagePlanes:
                imageName = imagePlane.split('->')[-1]
                imagePath = cmds.getAttr(imagePlane + '.imageName')
                imageSeq = cmds.getAttr(imagePlane + '.useFrameExtension')
                frameOffset = cmds.getAttr(imagePlane + '.frameOffset')
                imageSizeX = cmds.getAttr(imagePlane + '.sizeX')
                imageSizeY = cmds.getAttr(imagePlane + '.sizeY')
                imageOffsetX = cmds.getAttr(imagePlane + '.offsetX')
                imageOffsetY = cmds.getAttr(imagePlane + '.offsetY')
                camera = cmds.imagePlane(imagePlane, camera=True, query=True)[0]
                if imageName == 'imagePlane1':
                    mayaScript += "cmds.imagePlane(camera='%s');" % camera
                else:
                    mayaScript += "cmds.imagePlane(camera='%s', name='%s');" % (camera, imageName)
                mayaScript += "cmds.setAttr('%s.imageName', '%s', type='string');" % (imagePlane,
                                                                                      imagePath)
                mayaScript += "cmds.setAttr('%s.useFrameExtension', %s);" % (imagePlane, imageSeq)
                mayaScript += "cmds.setAttr('%s.frameOffset', %s);" % (imagePlane, frameOffset)
                mayaScript += "cmds.setAttr('%s.sizeX', %s);" % (imagePlane, imageSizeX)
                mayaScript += "cmds.setAttr('%s.sizeY', %s);" % (imagePlane, imageSizeY)
                mayaScript += "cmds.setAttr('%s.offsetX', %s);" % (imagePlane, imageOffsetX)
                mayaScript += "cmds.setAttr('%s.offsetY', %s);" % (imagePlane, imageOffsetY)

        mayaScript += "cmds.file(save=True, type='mayaBinary', force=True);" \
                      "cmds.quit();" \
                      "os._exit(0)"

        print mayaScript

        mayapyPath = instance.context.data['mayapy']
        if mayapyPath == '' or not os.path.exists(mayapyPath):
            self.log.error('mayapy not found. Unable to publish file.')
            raise pyblish.api.ExtractionError

        maya = subprocess.Popen(mayapyPath + ' -c "%s"' % mayaScript, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, shell=True)
        out, err = maya.communicate()
        exitcode = maya.returncode
        if str(exitcode) != '0':
            self.log.error('Unable to publish file.')
            raise pyblish.api.ExtractionError
        else:
            self.log.info('Anim Publish Successful.')
예제 #24
0
def audioClipCompare(a, b):
    startA = float(cmds.sound(a, q=1, offset=1))
    startB = float(cmds.sound(b, q=1, offset=1))

    return int(startA - startB)
예제 #25
0
    def _readClip(self, clip, isVideo, start, end, in_adjustment):
        # TODO: ensure that we don't already have a shot with
        # the same shot name in the scene
        # TODO: ensure that the rate associated with the clip
        # is the same as the rate of the whole sequence. Can
        # Maya support playback of different shots at different
        # rates? (I'm guessing no)
        # TODO: figure out how the naming should work. Should the
        # shot/audio node's name also match the "name" specified in
        # the EDL?

        if start == -1:
            self.logger.warning(
                "Importer._readClip, start parameter == -1, clip not loaded")
            return

        if end == -1:
            self.logger.warning(
                "Importer._readClip, end parameter == -1, clip not loaded")
            return

        clip_info = self.translator.getClip(clip)

        # Ensure that clip frame rate matches sequence frame rate
        self._checkFrameRates(clip, clip_info)

        clipIn = float(clip_info.get("in", 0))
        clipIn += in_adjustment

        clipNode = None

        clip_name = clip_info.get("name", "")
        # Note: The XML file could be utf-8, but Maya's nodes and attrs cannot be unicode.
        # So only use the name if it's valid
        try:
            clip_name = clip_name.encode("ascii")
        except:
            self.translator.logger.warning(
                "Clip name contains multi-byte characters, using default name")
            clip_name = ""

        clipObjectName = _getValidClipObjectName(clip_name, isVideo)

        if isVideo:
            clipNode = cmds.shot(clipObjectName)

            adjustedEnd = float(end)
            adjustedEnd -= 1  #Final frame in editorial is always exclusive bug 342715

            cmds.shot(
                clipNode,
                e=1,
                shotName=clip_name,
                sequenceStartTime=start,
                sequenceEndTime=adjustedEnd,
                clipZeroOffset=clipIn,
                startTime=start,  # Make Maya start/end the same as
                endTime=
                adjustedEnd,  # sequence start/end. Maya sequenceStart/end is not transoorted through EDL
                mute=(clip_info.get("enabled", True) == False))

            # create a custom camera
            # TODO: write out camera info as meta-data, perhaps??
            cameraNodes = cmds.camera(name=(clipNode + "Camera"))
            cmds.shot(clipNode, e=1, currentCamera=cameraNodes[0])

        else:
            clipNode = cmds.createNode("audio", name=clipObjectName)

            cmds.sequenceManager(attachSequencerAudio=clipNode)

            cmds.sound(clipNode,
                       e=1,
                       offset=start,
                       sourceStart=clipIn,
                       sourceEnd=float(clip_info.get("out", 1)),
                       endTime=end,
                       mute=(clip_info.get("enabled", True) == False))

        # Store the minimum frame of the sequence
        if self.minFrameInFile is None or start < self.minFrameInFile:
            self.minFrameInFile = start

        file_elem = clip_info.get("file", None)
        if file_elem is not None:
            file_info = self.translator.getFile(file_elem)

            # Ensure that file frame rate matches sequence frame rate
            self._checkFrameRates(file_elem, file_info)

            # TODO: convert from pathurl to an abs path that maya knows how to read
            # Or, just use the file-name and assume it's in the Maya project?
            if "pathurl" in file_info:
                if isVideo:
                    # query the frameCount. If this raises an error, it could be because
                    # the movie format is not supported on this platform
                    try:
                        frameCount = cmds.movieInfo(file_info["pathurl"],
                                                    frameCount=1)[0]
                    except:
                        self.translator.logger.warning(
                            "Could not open video file %s. File could be corrupt, or movie format is not supported on this platform"
                            % file_info["pathurl"])
                        frameCount = 0

                    video_height = file_info.get("height", None)
                    if video_height is not None:
                        cmds.setAttr((clipNode + ".hResolution"),
                                     int(video_height))
                    video_width = file_info.get("width", None)
                    if video_width is not None:
                        cmds.setAttr((clipNode + ".wResolution"),
                                     int(video_width))

                    cmds.shot(clipNode, e=1, clip=file_info["pathurl"])

                    cmds.setAttr((clipNode + ".clipDuration"), frameCount)
                    cmds.setAttr((clipNode + ".clipValid"), 1)
                    cmds.setAttr((clipNode + ".clipScale"),
                                 1)  #FCP Speed Effect not supported yet

                else:
                    try:
                        cmds.sound(clipNode, e=1, file=file_info["pathurl"])
                    except:
                        self.translator.logger.warning(
                            "Could not open audio file %s. File not found, or audio format not supported"
                            % file_info["pathurl"])
        self.clip_dict[clip] = clipNode
        return clipNode
예제 #26
0
파일: audioImport.py 프로젝트: boochos/work
def refMostRecent(*args):
    gotLength = '(Timeline is set to Shotgun length)'
    noLength = '(Timeline was not set)'
    timeline = gotLength
    ws = cmds.workspace(query=True, rd=True)
    print ws
    objPath = os.path.join(ws, 'Sound')
    print objPath
    # get current scene name
    currentF = cmds.file(q=True, sn=True)
    # get shot length from Shotgun
    shotLen = None  # int(shot_tools.get_sg_shot_length_from_path(currentF))
    if shotLen != None:
        mel.eval('warning \"' + '////... ---Getting shot length from Shotgun ...////' + '\";')
        cmds.playbackOptions(min=1.0, ast=1.0, max=(float(shotLen)), aet=(float(shotLen)))
        mel.eval('warning \"' + '////... ' + timeline + ' ---Importing Audio file...////' + '\";')
    else:
        mel.eval('warning \"' + '////... Shot length not found in Shotgun. Getting Audio ...////' + '\";')
        timeline = noLength
    # print objPath
    if os.path.exists(objPath):
        folderFiles = os.listdir(objPath)
        if len(folderFiles) > 0:
            folderFiles.sort()
            date_file_list = []
            import time
            # sort the files based on date
            # need to add a filter for specified file types
            for obj in folderFiles:
                # some files may be in the directory that have a . in front of them
                # these files will be passed
                srch = obj.find('.')
                if srch != 0:
                    path = os.path.join(objPath, obj)
                    # make sure only the most recent files are being referenced
                    if not os.path.isdir(path):
                        stats = os.stat(path)
                        lastmod_date = time.localtime(stats[8])
                        date_file_tuple = lastmod_date, path
                        date_file_list.append(date_file_tuple)
            # sort the list then reverse it
            date_file_list.sort()
            # the newest file is first in the list
            date_file_list.reverse()
            # get the file name
            path = date_file_list[0][1]
            fileName = os.path.split(date_file_list[0][1])[1].split('.')[0]
            # make sure audio is compatible with scene
            if fileName in currentF:
                path = os.path.join(objPath, fileName) + '.aif'
                if 'Audio_' not in fileName:
                    audioNodeName = fileName + '_Audio'
                    # print audioNodeName
                else:
                    audioNodeName = fileName
                audioNode = cmds.sound(name=audioNodeName, f=path, o=1)
                aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
                cmds.timeControl(aPlayBackSliderPython, e=True, sound=audioNode, displaySound=True)
                # mel.eval('setPlaybackRangeToSound;')
                soundLen = int(cmds.sound(audioNode, query=True, length=True))
                if soundLen != shotLen:
                    mel.eval('warning \"' + '////... ' + timeline + ' ---Mismatch:  --audio Length ' + str(soundLen) + ' - Shotgun Length ' + str(shotLen) + ' --  ////' + '\";')
                else:
                    mel.eval('warning \"' + '////... (Success!) ---Match:  --audio Length ' + str(soundLen) + ' - Shotgun Length ' + str(shotLen) + ' ...////' + '\";')
            else:
                mel.eval('warning \"' + '////...' + timeline + '  ---Mismatch:  --audio Name - scene Name--  Set project or get audio manually ...////' + '\";')
                cmds.Import()
        else:
            mel.eval('warning \"' + '////... ' + timeline + '  ---No audio files found. ---Ensure project was set ---or pick file from Browser window ...////' + '\";')
            cmds.Import()
    else:
        mel.eval('warning \"' + '////... Directory Not Found ...////' + '\";')
예제 #27
0
    def importAsset(self, iAObj=None):
        '''Import asset defined in *iAObj*'''
        if (iAObj.componentName == 'alembic'
                or iAObj.filePath.endswith('abc')):
            try:
                mc.loadPlugin('AbcImport.so', qt=1)
            except:
                return 'Failed to load alembic plugin'

            self.oldData = set(mc.ls())

            mc.createNode('transform', n=iAObj.assetName)
            mc.AbcImport(iAObj.filePath,
                         mode='import',
                         reparent=iAObj.assetName)

            self.newData = set(mc.ls())

            self.linkToFtrackNode(iAObj)
        elif any([
                iAObj.filePath.endswith(format)
                for format in SUPPORTED_SOUND_FORMATS
        ]):

            self.oldData = set(mc.ls())

            start_frame = mc.playbackOptions(q=True, min=True)
            mc.sound(file=iAObj.filePath, offset=start_frame)

            self.newData = set(mc.ls())

            self.linkToFtrackNode(iAObj)
        else:
            component = ftrack.Component(iAObj.componentId)
            self.importAssetBool = False
            preserveReferences = True
            self.referenceAssetBool = True
            groupReferenceBool = True

            # Determine namespace
            nameSpaceStr = ':'
            if iAObj.options['mayaAddNamespace']:
                if iAObj.options['mayaNamespace'] == 'File name':
                    nameSpaceStr = os.path.basename(iAObj.filePath)
                    nameSpaceStr = os.path.splitext(nameSpaceStr)[0]
                    # Remove the last bit, which usually is the version
                    nameSpaceStr = '_'.join(nameSpaceStr.split('_')[:-1])
                if iAObj.options['mayaNamespace'] == 'Component':
                    nameSpaceStr = iAObj.componentName
                if iAObj.options['mayaNamespace'] == 'Custom':
                    # Use custom namespace if any is specified.
                    if iAObj.options['nameSpaceStr']:
                        nameSpaceStr = iAObj.options['nameSpaceStr']

            # Determine import type
            mapping = {'.ma': 'mayaAscii', '.mb': 'mayaBinary'}
            importType = mapping.get(component.getFileType(), 'mayaBinary')

            if iAObj.componentName in [
                    'mayaBinary', 'main', 'mayaBinaryScene', 'mayaAscii',
                    'mayaAsciiScene'
            ]:
                if 'importMode' in iAObj.options:
                    if iAObj.options['importMode'] == 'Import':
                        self.importAssetBool = True
                        self.referenceAssetBool = False
                        # do not group when importing
                        groupReferenceBool = False

                if iAObj.componentName in ('mayaAscii', 'mayaAsciiScene'):
                    importType = 'mayaAscii'

            elif iAObj.componentName in ['audio']:
                importType = 'audio'
                self.importAssetBool = True
                self.referenceAssetBool = False

            if iAObj.componentName in ['mayaBinaryScene']:
                confirmDialog = mc.confirmDialog(
                    title='Confirm',
                    message='Replace current scene?',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')
                if confirmDialog == 'Yes':
                    mc.file(new=True, force=True)
                else:
                    return 'Canceled Import'

            if ('mayaReference' in iAObj.options
                    and iAObj.options['mayaReference']):
                preserveReferences = iAObj.options['mayaReference']

            self.oldData = set(mc.ls())

            nodes = mc.file(iAObj.filePath,
                            type=importType,
                            i=self.importAssetBool,
                            reference=self.referenceAssetBool,
                            groupLocator=False,
                            groupReference=groupReferenceBool,
                            groupName=iAObj.assetName,
                            loadReferenceDepth='all',
                            sharedNodes='renderLayersByName',
                            preserveReferences=preserveReferences,
                            mergeNamespacesOnClash=True,
                            namespace=nameSpaceStr,
                            returnNewNodes=True,
                            options='v=0')

            self.newData = set(mc.ls())

            # Find the actual groupName
            if iAObj.componentName in ['audio']:
                mc.rename(nodes[0], iAObj.assetName)
            else:
                iAObj.assetName = self.getGroupName(nodes, iAObj.assetName)

            try:
                self.linkToFtrackNode(iAObj)
            except Exception as error:
                print error

        # Restore timeline on asset import.
        mayacon.Connector.setTimeLine()
        return 'Imported ' + iAObj.assetType + ' asset'
예제 #28
0
def playblast(output,
              start_frame=None,
              end_frame=None,
              artist=None,
              view=True):
    '''
    '''
    # - make blast image dir  | Exp: C:/Users/zangchanglong/Documents/playblast
    if not os.path.isdir(blasterEnv.BLAST_IMAGE_DIR):
        os.makedirs(blasterEnv.BLAST_IMAGE_DIR)

    #- close all camera gate
    for cam in mc.ls(typ='camera'):
        mc.camera(cam,
                  e=True,
                  displayFilmGate=False,
                  displayResolution=False,
                  overscan=1.0)

    #- get time range
    if start_frame is None:
        start_frame = mc.playbackOptions(q=True, ast=True)

    if end_frame is None:
        end_frame = mc.playbackOptions(q=True, aet=True)

    #- playblast images
    BLAST_PREFIX = os.path.join(
        blasterEnv.BLAST_IMAGE_DIR,
        '{0}_{1}'.format(time.strftime("%b%d%H%M%S", time.localtime()),
                         uuid.uuid4().hex[::4].upper()))
    FRAME_PADDING = int(
        math.ceil(math.log(max(start_frame, end_frame) + 1, 10)))
    mc.playblast(filename=BLAST_PREFIX,
                 fmt='image',
                 compression=blasterEnv.BLAST_IMAGE_FMT,
                 width=mc.getAttr('defaultResolution.width'),
                 height=mc.getAttr('defaultResolution.height'),
                 startTime=start_frame,
                 endTime=end_frame,
                 framePadding=FRAME_PADDING,
                 percent=100,
                 quality=100,
                 viewer=False,
                 offScreen=True,
                 clearCache=True,
                 showOrnaments=False)

    #- getting infomation
    image_pattern = '{0}.{1}.{2}'.format(BLAST_PREFIX, '?' * FRAME_PADDING,
                                         blasterEnv.BLAST_IMAGE_FMT)
    camera = blasterUtil.get_current_camera()
    focal = mc.getAttr('{0}.focalLength'.format(camera))
    if not artist:
        artist = getpass.getuser()
    sound_node = mc.timeControl(mel.eval('string $temp = $gPlayBackSlider'),
                                q=True,
                                s=True)
    sound_file = 'audio.wav'
    if sound_node:
        sound_file = mc.sound(sound_node, q=True, f=True)

    #- create job-file
    info_data = {
        'ImagePattern': os.path.normpath(image_pattern),
        'Camera': str(camera),
        'Focal': str(focal),
        'Audio': os.path.normpath(sound_file),
        'Output': output,
        'Artist': artist
    }
    info_file = '{0}.json'.format(BLAST_PREFIX)
    with open(info_file, 'w') as f:
        json.dump(info_data, f, indent=4)

    #- call comp process
    comp_process_cmds = [blasterEnv.PROCESSOR, 'comp_blast_video', info_file]
    subprocess.check_call(' '.join(comp_process_cmds).encode('utf-8'))

    #- auto delete images
    if blasterEnv.AUTO_DELETE_IMAGE:
        images = glob.glob(image_pattern)
        for img in images:
            os.remove(img)

    #- delete job file
    if os.path.isfile(info_file):
        os.remove(info_file)

    #- view output
    if view:
        rv_view_cmds = [blasterEnv.RV_BIN, output.encode('utf-8')]
        subprocess.Popen(' '.join(rv_view_cmds))

    return True
예제 #29
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)
예제 #30
0
def Underscore(sString):
	if sString[0].isdigit():
    	sString = '_'+sString

	sNewString =''
	for s in sString:
    	if s.isalnum():
        	sNewString += s
    	else:
        	sNewString += '_'

	print sNewString
Underscore('a#$^fgg1')



### Current Frame
iFrame = int(cmds.currentTime(q = True))



### In/Out Range
iIn = int(cmds.playbackOptions(q = True, minTime = True))
iOut = int(cmds.playbackOptions(q = True, maxTime = True))


# Get List of Audios in the scene.
aAudio = [str(a) for a in cmds.ls(typ = 'audio')]

# Get Currently Active Sound
aPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider')
sAudio = cmds.timeControl(aPlayBackSlider, q = True, s = True)


### Date Examples
from datetime import datetime
from datetime import timedelta
# String to daytime
def MondayFinder(sYear, sMonth, sDate):
	#date_object = datetime.strptime('05 12 2015  1:33PM', '%b %d %Y %I:%M%p')
	oEntered = datetime.strptime('%s %s %s'%(sMonth, sD), '%m %d %Y')
	#print date_object.weekday()
	oMonday = date_object - timedelta(days = date_object.weekday())
	print newDate.weekday()


### Get Current SoundTrack
aPlayBackSliderPython = maya.mel.eval('$tmpVar=$gPlayBackSlider')
sSound = cmds.timeControl( aPlayBackSliderPython, q = True, sound = True)
print sSound
if sSound:
	iOffset = cmds.getAttr(sSound+'.offset')
	print cmds.sound( sSound, q = True, f = True )
	print iOffset


### Open Folder
cmd1 ='nautilus /net/homes/dyabu/Desktop/Shots/tu125250/Rv'
os.system(cmd1)



### User Define Enter Box
oClick = cmds.promptDialog(
   	 title='Rename Object',
   	 message='Enter Shot : ( ex.  fs150 )',
   	 button=['OK', 'Cancel'],
   	 defaultButton='OK',
   	 cancelButton='Cancel',
   	 dismissString='Cancel')

if oClick == 'OK':
    sShot = cmds.promptDialog(query=True, text=True)



### Get Current Camera ###
def getCamera():
	oCamera = ''
	oPanel = cmds.getPanel(wf = True)

	if 'modelPanel' in oPanel:
    	oCamera = cmds.modelEditor(oPanel, q = True, camera = True)

	return str(oCamera)


### Warning Message
cmds.warning( 'Enter something here' )




### Rename objects
cmds.rename(o, sName)

### Get User Name
import getpass
print getpass.getuser()


### Write File
oRvFile = open(sPath, 'w')
oRvFile.write(sContent)
oRvFile.close()

### Read File
oRvFile = open(sPath, 'r')
aLines = oRvFile.readlines()
oRvFile.close()
for line in aLines:
	sLine = line.strip()


### Get Active Panel
sCurrentPanel = cmds.getPanel(underPointer = True)
if sCurrentPanel == None:
	sCurrentPanel = cmds.getPanel(withFocus = True)

tCurrentPanel = cmds.getPanel(typeOf = sCurrentPanel)
if tCurrentPanel == 'modelPanel':
	print tCurrentPanel


# Execute Python File
#import sys
#sys.path.append('/home/ericb/GIT_DEV/ebLabs-workshop/whisKEY2')
import ebLabs_whisKEY
reload(ebLabs_whisKEY)
ebLabs_whisKEY.window.load()

# Execute External Python file
import sys
import  os

def ExecuteExternal(Mod):
	sFile  = os.path.basename( Mod )
	aFiles = sFile.split( '.' )

	sDir   = os.path.dirname( Mod )

	if( os.path.exists( sDir ) ):

    	aPaths = sys.path
    	iCheck = 0
    	for p in aPaths:
        	if(sDir == p):
            	iCheck = 1

    	if not iCheck:
        	print iCheck
        	sys.path.append( sDir )

	exec( 'import  ' + aFiles[0]    	) in globals()
	exec( 'reload( ' + aFiles[0] + ' )' ) in globals()


ExecuteExternal('/net/homes/dyabu/maya/2013.5-x64/scripts/HelloWorld.py')


### Linux Run Command
def Execute(cmd2):
	global aMainPath

	if cmd2:
    	if aMainPath[2] == 'homes':
        	MessageBox('Please open your scene first.')
    	else:
        	cmd1 ='go %s'%aMainPath[2]
        	os.system(cmd1)

        	os.system(cmd2)


### Partial Usage ###
from functools import partial

cmds.button( .... command = partial(defFunction, arg1, arg2) ...) # in a button
# and/or
oCMD = cmds.optionMenu( "CustomOptionMenu", label = "Version ", w = fWidth, cc = partial(self.defFunction))

def defFunction(arg1, arg2, *args):
	print 1


### Create Hotkey ###
def createHotkey(command, name, description=''):
	'''
	Open up the hotkey editor to create a hotkey from the specified command
	'''

	mel.eval('hotkeyEditor')
	cmds.textScrollList('HotkeyEditorCategoryTextScrollList', edit=True, selectItem='User')
	mel.eval('hotkeyEditorCategoryTextScrollListSelect')
	mel.eval('hotkeyEditorCreateCommand')

	cmds.textField('HotkeyEditorNameField', edit=True, text=name)
	cmds.textField('HotkeyEditorDescriptionField', edit=True, text=description)
	cmds.scrollField('HotkeyEditorCommandField', edit=True, text=command)
	mel.eval('hotkeyEditorAcceptCommand')
	mel.eval('hotkeyEditorSave')


### Create Shaders and assign to an object.
def Colour_The_Balls():
# Create Shaders
	aColourList = [
    	[0 ,[ 0.39 , 0.86 , 1.0 ]],
    	[1 ,[ 0.26 , 1.0 , 0.64 ]],
    	[2 ,[ 1.0 , 0.69 , 0.69 ]],
    	[3 ,[ 0.19 , 0.63 , 0.63 ]],
    	[4 ,[ 0.89 , 0.67 , 0.47 ]],
    	[5 ,[ 0.41 , 0.63 , 0.19 ]],
    	[6 ,[ 0 , 0.6 , 0.33 ]],
    	[7 ,[ 1.0 , 0 , 0 ]],
    	[8 ,[ 0 , 1.0 , 0 ]],
    	[9 ,[ 0 , 0 , 0 ]],   ]


	for colour in aColourList:
    	oMaterial = 'PivotColour_%s' % colour[0]

    	oShader = oMaterial+'_SDR'
    	if not cmds.objExists(oMaterial):
        	cmds.shadingNode('lambert', n = oMaterial, asShader = 1, )
        	cmds.sets(oMaterial, renderable = True, noSurfaceShader = True, empty = True, name = oShader)
        	cmds.connectAttr(oMaterial+'.outColor', oShader+'.surfaceShader', f = True)

        	cmds.setAttr( "%s.color"%oMaterial, type = 'double3', *colour[1])
        	cmds.setAttr( "%s.incandescence"%oMaterial, type = 'double3', *colour[1])
        	cmds.setAttr( "%s.ambientColor"%oMaterial, type = 'double3', *colour[1])


	# Change the color of the Spheres.

	for i in range(0,len(GetExistingPivots())):
    	sBall = 'PivotSphere_%s_Pivot' % i # Object Name
    	print sBall
    	cmds.sets( sBall, fe = 'PivotColour_%s_SDR' % i,  e = True)


### Copy files in Python
from shutil import copyfile

copyfile(src, dst)

### Bake Animation ###
import maya.mel as mel
def SpeedUpBake_1_Store(sName):
	# store a temporary panel configuration.
	layout = cmds.panelConfiguration(l=sName, sc=0)
	evalStr = 'updatePanelLayoutFromCurrent "'+name+'"'
	mel.eval(evalStr)

	# switch to fast "hidden" layout
	evalStr = 'setNamedPanelLayout "Single Perspective View"'
	mel.eval(evalStr)
	perspPane = cmds.getPanel(vis=1)
	cmds.scriptedPanel('graphEditor1',e=1,rp=perspPane[0])
	return sName

def SpeedUpBake_2_Restore(sName):
	# restore the layout returned from makeHiddenLayout.
	evalStr = 'setNamedPanelLayout "'+sName+'"'
	mel.eval(evalStr)
	# now delete the old layout.
	killMe = cmds.getPanel(cwl=sName)
	cmds.deleteUI(killMe,pc=1)

SpeedUpBake_1_Store('tempLayout')

try:
	print 'do something'

	cmds.bakeResults(aFirst, t = (aRange[0],aRange[1]), simulation = True )
finally:
	SpeedUpBake_2_Restore('tempLayout')

#ScriptJob example (ScriptJob : script must fishish executing completely in order for maya to respond.)
def CB(callback):
	trans = set(cmds.ls(sl = True, type = 'transform'))
	if trans:
		cb = cmds.channelBox('mainChannelBox', q = True, sma = True) or []
		if cb:
			callback([a+'.' +b for a in trans for b in cb])
		else:
			objs = set(cmds.ls(sl = True)) - trans
			if objs:
				cmds.select(list(objs))
				def temp():
					res = [a+'.'+b for a in objs for b in cmds.channelBox('mainChannelBox', q = True, sma = True)or[]]
					cmds.select(list(trans))
					callback(res)
				cmds.scriptJob(e = ('idle', temp), ro = True)

def main():
	def p(val):
		print val
	CB(p)
	print 'test'