Пример #1
0
def display_textures():
    current_panel = cmds.getPanel(withFocus=True)
    if not is_model_panel(current_panel):
        cmds.warning("Panel must be modelpanel.")

    is_texture = cmds.modelEditor(current_panel, q=True, displayTextures=True)
    cmds.modelEditor(current_panel, e=True, displayTextures=not (is_texture))
Пример #2
0
def cameraViewMode(panelName=None):
    if not panelName: panelName   = cmds.getPanel(withFocus=True)
    onlyShowObj(["polymeshes"], panelName)
    
    if (len(cmds.ls(type="light")) > 0): lights =  "all"
    else : lights = "default"
    cmds.modelEditor(panelName, edit=True, displayLights=lights, selectionHiliteDisplay=False)
    def create(self):
        
        if cmds.window( self.winName, ex=1 ):
            cmds.deleteUI( self.winName, wnd=1 )
        cmds.window( self.winName, title=self.title )
        
        form = cmds.formLayout()
        modelEditorForm = self.uiModelEditor1.create()
        modelPanelForm  = self.uiModelEditor2.create()
        button = cmds.button( l='S E L E C T    P L A N E', h=22, p=form, c= partial( WinA_Cmd.selectController, self.uiModelEditor1.modelEditor ),
                              bgc=[0.7, 0.9, 0.5] )
        cmds.setParent( '..' )
        
        cmds.modelEditor( self.uiModelEditor2.modelPanel, edit=1, displayAppearance='smoothShaded',
                          textures = False, hud=False, grid=False,
                          activeOnly = False )

        cmds.formLayout( form, e=1,
                         af=[ ( modelEditorForm, 'top', 15 ), ( modelEditorForm, 'left', 15 ), ( modelEditorForm, 'right', 15 ),
                              ( modelPanelForm, 'left', 15 ), ( modelPanelForm, 'right', 15 ), ( modelPanelForm, 'bottom', 15 ),
                              ( button, 'left', 15 ), ( button, 'right', 15 ) ],
                         ac=[ ( button, 'top', 5, modelEditorForm ), 
                              ( modelPanelForm, 'top', 5, button ) ] )
        
        cmds.window( self.winName, e=1, wh=[ self.width, self.height ], rtf=1 )
        cmds.showWindow( self.winName )
Пример #4
0
def apply_view(panel, **options):
    """Apply options to panel"""

    camera = cmds.modelPanel(panel, camera=True, query=True)

    # Display options
    display_options = options.get("display_options", {})
    for key, value in display_options.iteritems():
        if key in _DisplayOptionsRGB:
            cmds.displayRGBColor(key, *value)
        else:
            cmds.displayPref(**{key: value})

    # Camera options
    camera_options = options.get("camera_options", {})
    for key, value in camera_options.iteritems():
        cmds.setAttr("{0}.{1}".format(camera, key), value)

    # Viewport options
    viewport_options = options.get("viewport_options", {})
    for key, value in viewport_options.iteritems():
        cmds.modelEditor(panel, edit=True, **{key: value})

    viewport2_options = options.get("viewport2_options", {})
    for key, value in viewport2_options.iteritems():
        attr = "hardwareRenderingGlobals.{0}".format(key)
        cmds.setAttr(attr, value)
Пример #5
0
	def update_editor_view(self):
		cmds.viewFit()

		panels = cmds.getPanel(type='modelPanel')
		for panel in panels:
			modelEditor = cmds.modelPanel(panel, query=True, modelEditor=True)
			cmds.modelEditor(modelEditor, edit=True, displayAppearance='smoothShaded', displayTextures=True, textures=True, joints=False)
    def addCharacter(self, close, *args):
        project = cmds.optionMenu(self.widgets["project"], q=True, value=True)
        selectedCharacter = cmds.textScrollList(self.widgets["characterList"], q=True, si=True)[0]
        rigPath = os.path.join(
            self.mayaToolsDir, "General", "ART", "Projects", project, "AnimRigs", selectedCharacter + ".mb"
        )
        # find existing namespaces in scene
        namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
        # reference the rig file
        cmds.file(
            rigPath, r=True, type="mayaBinary", loadReferenceDepth="all", namespace=selectedCharacter, options="v=0"
        )
        # clear selection and fit view
        cmds.select(clear=True)
        cmds.viewFit()
        panels = cmds.getPanel(type="modelPanel")
        # turn on smooth shading
        for panel in panels:
            editor = cmds.modelPanel(panel, q=True, modelEditor=True)
            cmds.modelEditor(editor, edit=True, displayAppearance="smoothShaded", displayTextures=True, textures=True)
        # find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created)
        newCharacterName = selectedCharacter
        newNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
        for name in newNamespaces:
            if name not in namespaces:
                newCharacterName = name
        # launch UI
        import ART_animationUI

        reload(ART_animationUI)
        ART_animationUI.AnimationUI()
        if close:
            cmds.deleteUI(self.widgets["window"])
Пример #7
0
	def __init__(self, project, pose = None, parent  = uiH.getMayaWindow() ):
		if uiH.USEPYQT:
			super(base, self).__init__(parent)
		else:
			super(PoseThumbnailCreatorUi, self).__init__(parent)
		self.setupUi(self)
		self.project = project
		self.pose = pose
		layout = mui.MQtUtil.fullName(long(shiboken.getCppPointer(self.viewport_lay)[0]))
		self.cam = mn.Node( 'Capture_Pose' )
		if not self.cam.exists:
			self.camShape = mn.createNode( 'camera', ss = True )
			self.camShape.parent.name = 'Capture_Pose'
			mc.viewSet( self.cam.name, p = True )
			self.cam.shape.a.focalLength.v = 100
			self.cam.a.v.v = 0
		self.executer = mc.modelPanel( mbv = False, camera = self.cam.name, p = layout )
		mc.modelEditor(self.executer, e = True, grid = 0, da = "smoothShaded", allObjects = 0, nurbsSurfaces = 1, polymeshes = 1, subdivSurfaces = 1 )
		#self.viewport_lay.addWidget( uiH.toQtObject( self.executer ) )
		self.setObjectName( 'PoseThumbnailCreatorUi' )
		self._makeConnections()
		self.saveCameraPreset = 0 #READ, 1.. WRITE
		self.settings = sti.Settings()
		gen = self.settings.General
		skin = gen[ "skin" ]
		if skin:
			uiH.loadSkin( self, skin )
		if pose:
			self.poseName_le.setText( pose.name )
		self.fillSections()
Пример #8
0
    def __set__(self, instance, value):
        """
        This function set the value on the displayAppearance of the 
        modelpanel
        """
        #usual data check
        if not self.check_data_type(value):
            return

        #get the modelpanel
        model = get_model()
        if not model:
            return

        #check if the value we want to set is actually
        #supported
        if not value in self.SUPPORTED_ATTRS:
            types = ""
            for t in self.SUPPORTED_ATTRS:
                types += "- "
                types += t
                types += " \n"
            OpenMaya.MGlobal.displayWarning("value \"{v}\" ".format(v = value) + \
                    "is not supported \nsupported types : \n" + types)
            return

        #if everything goes well lets sett the value
        cmds.modelEditor(model, displayAppearance=value, e=1)
Пример #9
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 '
Пример #10
0
def currentCamera():
	if Sel.getType(0)[1] == 'LIGHT' or Sel.getType(0)[1] == 'CAMERA':
		print 'going through current camera section in camera shuffle'
		i = cmds.ls(selection=True)
		cmds.modelEditor(Cache.modelPanel, edit=True, cam = i[0] )
	else:
		print 'select a camera or light'
Пример #11
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)
Пример #12
0
def addCreatedToIsolateView():
    '''
    if the current model editor panels isolate view is
    enabled add the just created object to the view
    '''
    for p in getActiveModelPanel():
        if mc.modelEditor(p, q=1, viewSelected=1):
            mc.modelEditor(p, edit=1, addSelected=1)
Пример #13
0
def bufMoveRelease():
    """release the Buf move vertex mode"""
    activePanel = cmds.getPanel(withFocus=True)
    cmds.modelEditor(activePanel, e=True, manipulators=True)
    cmds.setToolTo('moveSuperContext')
    cmds.selectPref(clickDrag=False)
    cmds.selectMode(component=True)
    cmds.selectMode(object=True)
Пример #14
0
def toggle_lights(lights=None):
    current_panel = cmds.getPanel(withFocus=True)
    if lights:
        cmds.modelEditor(current_panel, e=True, displayLights=lights)
    else:
        state = cmds.modelEditor(current_panel, q=True, displayLights=True)
        result = "all" if not state == "all" else "default"
        cmds.modelEditor(current_panel, e=True, displayLights=result)
Пример #15
0
def toggleGeo():
    pnl = cmds.getPanel(withFocus=True)
    if cmds.getPanel(to=pnl) == 'modelPanel':
        state = cmds.modelEditor(pnl, q=True, polymeshes=True)
        if state:
            cmds.modelEditor(pnl, e=True, polymeshes=0)
            # cmds.modelEditor(pnl, e=True, nurbsSurfaces=0)
        else:
            cmds.modelEditor(pnl, e=True, polymeshes=1)
Пример #16
0
 def deleteIShatterCtx(self):
     '''
     Delete IShatter Context Tool
     '''
     cmds.deleteUI(self._mContext)
     cmds.modelEditor('modelPanel4', edit = True, grid = True)       
     
     cmds.scriptEditorInfo (clearHistory = True)
     cmds.flushUndo()   
Пример #17
0
def setAllPanelsToRenderer(renderer, reset=True):
    """Set all the models panels to the specified renderer. It will do a reset of everything regarding the Viewport 2.0 if no model panels use it.
    Possible values: base_OpenGL_Renderer, hwRender_OpenGL_Renderer, vp2Renderer
    """
    modelPanels = cmds.getPanel(type='modelPanel') or []
    for panel in modelPanels:
        cmds.modelEditor(panel, edit=True, rendererName=renderer)
    if reset or os.environ.get('MAYA_DISABLE_VP2_WHEN_POSSIBLE', False):
        cmds.ogs(reset=True)
Пример #18
0
def parse_view(panel):
    """Parse the scene, panel and camera for their current settings

    Example:
        >>> parse_view("modelPanel1")

    Arguments:
        panel (str): Name of modelPanel

    """

    camera = cmds.modelPanel(panel, query=True, camera=True)

    # Display options
    display_options = {}
    for key in DisplayOptions:
        if key in _DisplayOptionsRGB:
            display_options[key] = cmds.displayRGBColor(key, query=True)
        else:
            display_options[key] = cmds.displayPref(query=True, **{key: True})

    # Camera options
    camera_options = {}
    for key in CameraOptions:
        camera_options[key] = cmds.getAttr("{0}.{1}".format(camera, key))

    # Viewport options
    viewport_options = {}

    # capture plugin display filters first to ensure we never override
    # built-in arguments if ever possible a plugin has similarly named
    # plugin display filters (which it shouldn't!)
    plugins = cmds.pluginDisplayFilter(query=True, listFilters=True)
    for plugin in plugins:
        plugin = str(plugin)  # unicode->str for simplicity of the dict
        state = cmds.modelEditor(panel, query=True, queryPluginObjects=plugin)
        viewport_options[plugin] = state

    for key in ViewportOptions:
        viewport_options[key] = cmds.modelEditor(
            panel, query=True, **{key: True})

    viewport2_options = {}
    for key in Viewport2Options.keys():
        attr = "hardwareRenderingGlobals.{0}".format(key)
        try:
            viewport2_options[key] = cmds.getAttr(attr)
        except ValueError:
            continue

    return {
        "camera": camera,
        "display_options": display_options,
        "camera_options": camera_options,
        "viewport_options": viewport_options,
        "viewport2_options": viewport2_options
    }
Пример #19
0
def toggleSelectionHighlight():
	"""
	This definition toggles active modeling panel selection highlight.
	"""

	panel = cmds.getPanel(withFocus=True)
	try:
		cmds.modelEditor(panel, e=True, sel=not cmds.modelEditor(panel, q=True, sel=True))
	except:
		pass
 def takePicture(self,*args):
     global screenShotPanelVar
     cmds.formLayout()
     cmas=cmds.columnLayout(adj=True)
     cmds.paneLayout(w=150,h=150)
     screenShotPanelVar=cmds.modelPanel(cam='persp',mbv=False)
     cmds.modelEditor(screenShotPanelVar,e=True,da='smoothShaded',hud=False,jx=False,dtx=True,grid=False)
     cmds.separator(p=cmas)
     cmds.button(l='SET AS PREVIEW',p=cmas, c=self.takePictureProcess)
     return
Пример #21
0
def wireframe_on_bg_objects():
    """
    Toggles wireframe/shaded on background objects.
    """
    current_panel = cmds.getPanel(withFocus=True)
    if not is_model_panel(current_panel):
        return cmds.warning("Panel must be modelPanel")

    state = cmds.modelEditor(current_panel, q=True, activeOnly=True)
    cmds.modelEditor(current_panel, e=True, activeOnly=not (state))
Пример #22
0
def wireframe_on_shaded():
    """
    Toggles shaded on wireframe, will be visible on background objects.
    """
    current_panel = cmds.getPanel(withFocus=True)
    if not is_model_panel(current_panel):
        return logger.warn("Panel must be modelPanel.")

    is_wos = cmds.modelEditor(current_panel, q=True, wos=True)
    cmds.modelEditor(current_panel, e=True, wos=not (is_wos))
Пример #23
0
	def o (self):
		if self.getSelection() == 'None':
			cmds.playbackOptions( maxTime = cmds.currentTime( query=True ) )
		else:
			wireOn = cmds.modelEditor('modelPanel4', q=1, wos=1)
			if wireOn == True:
			    cmds.modelEditor('modelPanel4', edit = True, wos=0)
			else:
			    cmds.modelEditor('modelPanel4', edit = True, wos=1)
			cmds.select(deselect = 1)
Пример #24
0
 def _get_display_defaults(self):
     """
     collect current panel display details so that it can
         be reset back after processing
     """
     self.display_defaults = {
         "appearance": mc.modelEditor(self._current_panel, query=True, displayAppearance=True),
         "textures": mc.modelEditor(self._current_panel, query=True, displayTextures=True),
         "lights": mc.modelEditor(self._current_panel, query=True, displayLights=True),
     }
     print "display defaults:: %s" % str(self.display_defaults)
Пример #25
0
    def focus(self, value):
        '''Set focus to Viewport instance.'''

        if not value:
            try:
                Viewport.get(1).focus = True
            except:
                pass
            return

        cmds.modelEditor(self.panel, edit=True, activeView=True)
Пример #26
0
def assignDefaultShader():

    global switch
    activeModel = cmds.getPanel(wf=True)
    cmds.modelEditor(activeModel, e=True, udm=0)
    cmds.displayRGBColor( 'background', 0.61, 0.61, 0.61 )
    cmds.setAttr('lambert1.color', 0.5, 0.5, 0.5, type="double3")
    cmds.setAttr('lambert1.diffuse', 0.5)
    for node in cmds.ls(sl=True):
        cmds.color() # assign default wireframes
    switch = 1
Пример #27
0
def toggleIsolate():
    '''
    singleton to toggle isolateView in current model panel
    '''
    for p in getActiveModelPanel():
        if mc.modelEditor(p, q=1, viewSelected=1):
            # if on:simply turn of works
            mc.modelEditor(p, e=1, viewSelected=0)
        else:
            # TODO: If selection is empty, you probably don't want an empty isolated view
            # if off:we need the mel proc, it collects the objs to isolate
            melEval('enableIsolateSelect("' + p + '", 1)')
Пример #28
0
def toggleNurbsCurves():


    myPanel = cmds.getPanel(withFocus = True)

    
    if(cmds.modelEditor(myPanel, query = True, nurbsCurves = True)):
        cmds.modelEditor(myPanel, edit = True,nurbsCurves = False)
        print "nurbsCurves hidden"
    else:
        cmds.modelEditor(myPanel, edit = True, nurbsCurves=True)
        print "nurbsCurves visible"
Пример #29
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
Пример #30
0
    def __set__(self, inst, value):
        '''Sets a model editor property.'''

        try:
            cmds.modelEditor(
                inst.panel,
                **{'edit': True, self.name: value}
            )
        except TypeError:
            cmds.modelEditor(
                inst.panel,
                **{'edit': True, 'po': [self.name, value]}
            )
Пример #31
0
def wireframe():
    panel = cmds.getPanel(withFocus=True)
    cmds.modelEditor(panel,e=True,wos=(not cmds.modelEditor(panel,q=True,wos=True)))
Пример #32
0
def playblast(saveDir, width, height, renderCamera, modelPanel, renderSize=1):
    """
    Playblasts the timeslider
    Args:
        saveDir (str): save directory with *.mov extension
        width (int):  width in pixels
        height:  height in pixels
        renderCamera: camera to playblast from
        modelPanel: modelPanel to playblast from
        renderSize: render size (factor)
    """
    check()  # check that everything is in order
    renderSize = resolutionCheck(
        width, height, renderSize)  # make sure resolution is reasonable
    aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
    audioNode = cmds.timeControl(aPlayBackSliderPython, q=True,
                                 s=True)  # get audio node

    # get working values to be changed
    workingRenderSize = cmds.getAttr("{0}.renderScale".format(
        mnpr_info.configNode))
    workingColorDepth = cmds.getAttr("{0}.colorDepth".format(
        mnpr_info.configNode))
    workingCamera = cmds.modelEditor(modelPanel, cam=True, q=True)
    workingCameraShape = cmds.listRelatives(workingCamera, s=True)
    if workingCameraShape:
        workingCameraShape = workingCameraShape[0]
    else:
        # we already have the shape
        workingCameraShape = workingCamera

    # set desired attributes
    cmds.mnpr(g=True)
    mnprOperations = len(cmds.mnpr(lsO=True))
    cmds.mnpr(renderOperation=mnprOperations - 1, s=0)  # HUD
    cmds.mnpr(renderOperation=mnprOperations - 2, s=0)  # UI
    cmds.modelEditor(modelPanel, cam=renderCamera, e=True)  # change modelPanel
    lib.setAttr(mnpr_info.configNode, "renderScale", renderSize)
    lib.setAttr(mnpr_info.configNode, "colorDepth",
                2)  # needs to be 32bit to avoid artefacts
    cmds.refresh()

    # try playblasting
    try:
        cmds.playblast(f=saveDir,
                       format="qt",
                       w=width,
                       h=height,
                       percent=100,
                       qlt=100,
                       v=True,
                       fo=True,
                       os=True,
                       s=audioNode,
                       compression="PNG")
    except RuntimeError:
        try:
            cmds.playblast(f=saveDir,
                           format="avi",
                           w=width,
                           h=height,
                           percent=100,
                           qlt=100,
                           v=True,
                           fo=True,
                           os=True,
                           s=audioNode)
        except RuntimeError:
            cmds.error(
                "Video cannot be playblasted as qt or avi, please check the installed codecs."
            )

    # bring everything back to normal
    cmds.mnpr(renderOperation=mnprOperations - 1, s=1)  # HUD
    cmds.mnpr(renderOperation=mnprOperations - 2, s=1)  # UI
    cmds.modelEditor(modelPanel, cam=workingCameraShape, e=True)
    lib.setAttr(mnpr_info.configNode, "renderScale", workingRenderSize)
    lib.setAttr(mnpr_info.configNode, "colorDepth", workingColorDepth)
    cmds.mnpr(g=False)
    cmds.refresh()

    lib.printInfo(
        "Video has been successfully playblasted to: {0}".format(saveDir))
Пример #33
0
 def deformers(self):
     viz = cmds.modelEditor(self.panel, query=True, deformers=True)
     cmds.modelEditor(self.panel, deformers=True, edit=not viz)
Пример #34
0
def CreateGeometryCache_zwz():
    myStartFrameV = mc.playbackOptions(q=True, min=True)
    myEndFrameV = mc.playbackOptions(q=True, max=True)
    num_myGeoObject_zwz = len(myGeoObject_zwz)
    #获取激活视面
    if num_myGeoObject_zwz:
        mm.eval(
            'setNamedPanelLayout "Single Perspective View"; updateToolbox();')
        activePlane = ''
        i = 1
        while (i):
            try:
                tmp = mc.modelEditor('modelPanel%d' % i, q=True, av=True)
            except:
                pass
            else:
                if tmp:
                    activePlane = 'modelPanel%d' % i
                    break
            i += 1
        mc.modelEditor(activePlane,
                       e=True,
                       polymeshes=False,
                       nurbsSurfaces=False)
        myfileName = mc.file(q=True, sn=True, shortName=True).split('.')[0]
        mydataName = mc.workspace(en='data/%s/' % myfileName)
        ErrorObjects = []
        amount = 0
        mc.progressWindow(title=u'动画缓存创建,一共有%s个' % num_myGeoObject_zwz,
                          progress=amount,
                          status='chMyGeoCache',
                          min=0,
                          max=num_myGeoObject_zwz,
                          isInterruptable=True)
        allcacheNames = mc.textScrollList('selectObjects', q=True, ai=True)
        for i, each in enumerate(myGeoObject_zwz):
            if len(each):
                cacheName = allcacheNames[i]
                mc.progressWindow(e=True,
                                  status=u'第%s个: %s' % (i, cacheName),
                                  progress=i)
                mc.select(cl=True)
                mc.select(myGeoObject_zwz[i], r=True)
                mm.eval("SelectIsolate;")
                j = 1
                while (True):
                    if os.path.isdir(mydataName + cacheName):
                        if os.path.isdir(mydataName + cacheName + '_' +
                                         '%s' % j):
                            j = j + 1
                        else:
                            cacheName = cacheName + '_' + '%s' % j
                            break
                    else:
                        break
                cacheFiles = mc.cacheFile(r=True,
                                          sch=True,
                                          dtf=True,
                                          fm='OneFilePerFrame',
                                          spm=1,
                                          smr=1,
                                          directory=mydataName + cacheName,
                                          fileName=cacheName,
                                          st=myStartFrameV,
                                          et=myEndFrameV,
                                          points=each)
                if mc.progressWindow(
                        q=True, isCancelled=True) or mc.progressWindow(
                            q=True, progress=True) > num_myGeoObject_zwz:
                    mc.progressWindow(endProgress=True)
                    mc.confirmDialog(title=u'温馨提示',
                                     message=u'到第%s个: %s就停了' % (i, cacheName),
                                     button=['OK'],
                                     defaultButton='Yes',
                                     dismissString='No')
                    return
                mc.delete(each, ch=True)
                myswichNode = []
                myswichList = []
                myNewcacheObjects = []
                switchText = ''
                for peach in each:
                    try:
                        switch = mm.eval('createHistorySwitch("%s", false)' %
                                         peach)
                    except:
                        ErrorObjects.append(peach)
                        print peach
                    else:
                        myNewcacheObjects.append(peach)
                        myswichNode.append(switch)
                        switchText = '%s.inp[0]' % switch
                        myswichList.append(switchText)
                mc.cacheFile(f=cacheName,
                             directory=mydataName + cacheName,
                             cnm=myNewcacheObjects,
                             ia=myswichList,
                             attachFile=True)
                for seach in myswichNode:
                    mc.setAttr('%s.playFromCache' % seach, 1)
                mc.select(cl=True)
        mc.progressWindow(endProgress=True)
        mc.isolateSelect(activePlane, state=False)
        mc.modelEditor(activePlane,
                       e=True,
                       polymeshes=True,
                       nurbsSurfaces=True)
        if ErrorObjects:
            print(u'以下shapes不能创建缓存:\n %s' % ErrorObjects)
        print u'全部创建完成'
Пример #35
0
    def storeSettings(self):
        '''
        main work function, store all UI settings
        '''
        self.dataStore['autoKey'] = cmds.autoKeyframe(query=True, state=True)

        # timeline management
        self.dataStore['currentTime'] = cmds.currentTime(q=True)
        self.dataStore['minTime'] = cmds.playbackOptions(q=True, min=True)
        self.dataStore['maxTime'] = cmds.playbackOptions(q=True, max=True)
        self.dataStore['startTime'] = cmds.playbackOptions(q=True, ast=True)
        self.dataStore['endTime'] = cmds.playbackOptions(q=True, aet=True)
        self.dataStore['playSpeed'] = cmds.playbackOptions(query=True,
                                                           playbackSpeed=True)

        # unit management
        self.dataStore['timeUnit'] = cmds.currentUnit(q=True,
                                                      fullName=True,
                                                      time=True)
        self.dataStore['sceneUnits'] = cmds.currentUnit(q=True,
                                                        fullName=True,
                                                        linear=True)
        self.dataStore['upAxis'] = cmds.upAxis(q=True, axis=True)

        #viewport colors
        self.dataStore['displayGradient'] = cmds.displayPref(
            q=True, displayGradient=True)

        #objects colors
        self.dataStore['curvecolor'] = cmds.displayColor("curve",
                                                         q=True,
                                                         dormant=True)

        #panel management
        self.dataStore['panelStore'] = {}
        for panel in [
                'modelPanel1', 'modelPanel2', 'modelPanel3', 'modelPanel4'
        ]:
            if not cmds.modelPanel(panel, q=True, exists=True):
                continue
            self.dataStore['panelStore'][panel] = {}
            self.dataStore['panelStore'][panel]['settings'] = cmds.modelEditor(
                panel, q=True, sts=True)
            activeCam = cmds.modelPanel(panel, q=True, camera=True)
            if not cmds.nodeType(activeCam) == 'camera':
                activeCam = cmds.listRelatives(activeCam, f=True)[0]
            self.dataStore['panelStore'][panel]['activeCam'] = activeCam

        #camera management
        #TODO : store the camera field of view etc also
        self.dataStore['cameraTransforms'] = {}
        for cam in ['persp', 'top', 'side', 'front']:
            try:
                self.dataStore['cameraTransforms'][cam] = [
                    cmds.getAttr('%s.translate' % cam),
                    cmds.getAttr('%s.rotate' % cam),
                    cmds.getAttr('%s.scale' % cam)
                ]
            except:
                log.debug("Camera doesn't exists : %s" % cam)

        #sound management
        self.dataStore['activeSound'] = cmds.timeControl(self.gPlayBackSlider,
                                                         q=True,
                                                         s=1)
        self.dataStore['displaySound'] = cmds.timeControl(self.gPlayBackSlider,
                                                          q=True,
                                                          ds=1)
Пример #36
0
 def xRay(self):
     viz = cmds.modelEditor(self.panel, query=True, xray=True)
     cmds.modelEditor(self.panel, xray=True, edit=not viz)
Пример #37
0
 def changeSetting(self, flag, mode, *args):
     if flag == 'grid':
         cmds.modelEditor(self.panel, e=True, grid=mode)
     elif flag == 'nurbsSurfaces':
         cmds.modelEditor(self.panel, e=True, nurbsSurfaces=mode)
     elif flag == 'polymeshes':
         cmds.modelEditor(self.panel, e=True, polymeshes=mode)
     elif flag == 'nurbsCurves':
         cmds.modelEditor(self.panel, e=True, nurbsCurves=mode)
     elif flag == 'joints':
         cmds.modelEditor(self.panel, e=True, joints=mode)
     elif flag == 'HUD':
         cmds.modelEditor(self.panel, e=True, hud=mode)
     elif flag == 'rnm':
         cmds.modelEditor(self.panel, e=True, rnm=mode)
Пример #38
0
 def xRayJoints(self):
     viz = cmds.modelEditor(self.panel, query=True, jointXray=True)
     cmds.modelEditor(self.panel, jointXray=True, edit=not viz)
Пример #39
0
 def wireframeOnShaded(self):
     viz = cmds.modelEditor(self.panel, query=True, wireframeOnShaded=True)
     cmds.modelEditor(self.panel, wireframeOnShaded=True, edit=not viz)
Пример #40
0
def grid():
    panel =cmds.getPanel(withFocus=True)
    cmds.modelEditor(panel,e=True,grid=(not cmds.modelEditor(panel,q=True,grid=True)))
Пример #41
0
def changeCamera(item):
    cmds.modelEditor('editor', edit=True, camera=item)
Пример #42
0
 def polygons(self):
     viz = cmds.modelEditor(self.panel, query=True, polymeshes=True)
     cmds.modelEditor(self.panel, edit=True, polymeshes=not viz)
Пример #43
0
    def DisplayPoly(self, myPlane):
        mayaversions = mc.about(v=True)

        rendererName = mc.modelEditor(self.myactivePlane,
                                      q=True,
                                      rendererName=True)

        if mayaversions.find('2009') >= 0:
            mc.modelEditor(myPlane,
                           e=True,
                           polymeshs=True,
                           nurbsCurves=False,
                           nurbsSurfaces=False,
                           subdivSurfaces=False,
                           planes=True,
                           light=False,
                           cameras=False,
                           joints=False,
                           ikHandles=False,
                           deformers=False,
                           dynamics=False,
                           fluids=True,
                           hairSystems=False,
                           follicles=False,
                           nCloths=False,
                           nParticles=False,
                           nRigids=False,
                           dynamicConstraints=False,
                           locators=False,
                           dimension=False,
                           pivots=False,
                           handles=False,
                           textures=False,
                           strokes=False,
                           manipulators=False,
                           grid=False,
                           hud=False,
                           rendererName=rendererName)
        else:
            mc.modelEditor(myPlane,
                           e=True,
                           polymeshes=True,
                           nurbsCurves=False,
                           nurbsSurfaces=False,
                           subdivSurfaces=False,
                           planes=False,
                           lights=False,
                           cameras=False,
                           joints=False,
                           ikHandles=False,
                           deformers=False,
                           dynamics=False,
                           fluids=True,
                           hairSystems=False,
                           follicles=False,
                           nCloths=False,
                           nParticles=False,
                           nRigids=False,
                           dynamicConstraints=False,
                           locators=True,
                           dimensions=False,
                           pivots=False,
                           handles=False,
                           textures=False,
                           strokes=False,
                           motionTrails=False,
                           manipulators=False,
                           clipGhosts=False,
                           grid=False,
                           hud=False,
                           rendererName=rendererName)
Пример #44
0
def xray():
    panel = cmds.getPanel(withFocus=True)
    cmds.modelEditor(panel,e=True,xray=(not cmds.modelEditor(panel,q=True,xray=True)))
Пример #45
0
    def testObjectNormal(self):
        """
        Tests that an object created interactively by dragging in the viewport
        has the correct orientation based on the live surface normal.
        """
        from pxr import Gf

        # Load our reference assembly.
        UsdMaya.LoadReferenceAssemblies()

        # Create a new custom viewport.
        window = cmds.window(widthHeight=(500, 400))
        cmds.paneLayout()
        panel = cmds.modelPanel()
        cmds.modelPanel(panel, edit=True, camera='persp')
        cmds.modelEditor(cmds.modelPanel(panel, q=True, modelEditor=True),
                         edit=True,
                         displayAppearance='smoothShaded',
                         rnm='vp2Renderer')
        cmds.showWindow(window)

        # Force all views to re-draw. This causes us to block until the
        # geometry we're making live has actually been evaluated and is present
        # in the viewport. Otherwise execution of the test may continue and the
        # create tool may be invoked before there's any geometry there, in
        # which case the tool won't create anything.
        cmds.refresh()

        # Get the viewport widget.
        view = OMUI.M3dView()
        OMUI.M3dView.getM3dViewFromModelPanel(panel, view)
        viewWidget = wrapInstance(long(view.widget()), QWidget)

        # Make our assembly live.
        cmds.makeLive('Block_2')

        # Enter interactive creation context.
        cmds.setToolTo('CreatePolyConeCtx')

        # Click in the center of the viewport widget.
        QTest.mouseClick(viewWidget, QtCore.Qt.LeftButton,
                         QtCore.Qt.NoModifier,
                         viewWidget.rect().center())

        # Find the cone (it should be called pCone1).
        self.assertTrue(cmds.ls('pCone1'))

        # Check the cone's rotation.
        # Because our scene is Z-axis up, the cone's Z-axis should be aligned
        # with Block_2's surface normal (though it might not necessarily have
        # the same exact rotation).
        rotationAngles = cmds.xform('pCone1', q=True, ro=True)
        rotation = (Gf.Rotation(Gf.Vec3d.XAxis(), rotationAngles[0]) *
                    Gf.Rotation(Gf.Vec3d.YAxis(), rotationAngles[1]) *
                    Gf.Rotation(Gf.Vec3d.ZAxis(), rotationAngles[2]))
        actualZAxis = rotation.TransformDir(Gf.Vec3d.ZAxis())

        expectedRotation = (Gf.Rotation(Gf.Vec3d.XAxis(), 75.0) *
                            Gf.Rotation(Gf.Vec3d.YAxis(), 90.0))
        expectedZAxis = expectedRotation.TransformDir(Gf.Vec3d.ZAxis())

        # Verify that the error angle between the two axes is less than
        # 0.1 degrees (less than ~0.0003 of a revolution, so not bad). That's
        # about as close as we're going to get.
        errorRotation = Gf.Rotation(actualZAxis, expectedZAxis)
        self.assertLess(errorRotation.GetAngle(), 0.1)
Пример #46
0
 def locators(self):
     viz = cmds.modelEditor(self.panel, query=True, locators=True)
     cmds.modelEditor(self.panel, edit=True, locators=not viz)
Пример #47
0
    def buildUI(self):
        fileName = 'capture'
        adj = 10
        if cmds.objExists(self.camName):
            cmds.setAttr((self.camName + ".farClipPlane"), k=True)
            cmds.setAttr((self.camName + ".nearClipPlane"), k=True)
            cmds.select(clear=True)

        if cmds.window('User Viewer', query=True, exists=True):
            cmds.deleteUI('User Viewer')

        renderViewID = cmds.window('User Viewer',
                                   s=True,
                                   t='User Viewer' + ': ' +
                                   self.camName.split('Shape')[0])
        masterLayout = cmds.columnLayout(adj=True)
        viewer = cmds.paneLayout(w=self.W, h=self.H)
        self.panel = cmds.modelPanel(mbv=0,
                                     label="Custom Viewer",
                                     cam=self.camName)

        tempLayout = cmds.modelPanel(self.panel, q=1, bl=True)

        cmds.modelEditor(self.panel, e=True, grid=0, da="smoothShaded")
        cmds.modelEditor(self.panel,
                         e=True,
                         allObjects=1,
                         nurbsSurfaces=1,
                         polymeshes=1,
                         subdivSurfaces=1,
                         nurbsCurves=1,
                         cv=1,
                         hulls=1,
                         planes=1,
                         cameras=1,
                         imagePlane=1,
                         joints=0,
                         ikHandles=0,
                         deformers=1,
                         dynamics=0,
                         fluids=1,
                         hairSystems=1,
                         follicles=1,
                         nCloths=1,
                         nParticles=1,
                         nRigids=1,
                         dynamicConstraints=1,
                         locators=1,
                         dimensions=1,
                         pivots=1,
                         handles=1,
                         textures=1,
                         strokes=1,
                         motionTrails=1,
                         pluginShapes=1,
                         clipGhosts=1,
                         greasePencils=1,
                         manipulators=1,
                         hud=1)

        cmds.setParent(masterLayout)
        self.bts.makeSeparator(h=5, w=self.W)
        nc = 15
        cmds.rowColumnLayout(nc=nc,
                             cw=self.bts.cwE(nc=nc, w=self.W, adj=adj),
                             h=25)

        cmds.checkBox(label="Grid",
                      v=False,
                      onc=(partial(self.changeSetting, 'grid', 1)),
                      ofc=(partial(self.changeSetting, 'grid', 0)))
        cmds.checkBox(label="Nurbs",
                      align="left",
                      v=True,
                      onc=(partial(self.changeSetting, 'nurbsSurfaces', 1)),
                      ofc=(partial(self.changeSetting, 'nurbsSurfaces', 0)))
        cmds.checkBox(label="Polys",
                      align="left",
                      v=True,
                      onc=(partial(self.changeSetting, 'polymeshes', 1)),
                      ofc=(partial(self.changeSetting, 'polymeshes', 0)))
        cmds.checkBox(label="Curves",
                      align="left",
                      v=True,
                      onc=(partial(self.changeSetting, 'nurbsCurves', 1)),
                      ofc=(partial(self.changeSetting, 'nurbsCurves', 0)))
        cmds.checkBox(label="Joints",
                      align="left",
                      v=False,
                      onc=(partial(self.changeSetting, 'joints', 1)),
                      ofc=(partial(self.changeSetting, 'joints', 0)))
        cmds.checkBox(label="HUD",
                      align="left",
                      v=True,
                      onc=(partial(self.changeSetting, 'hud', 1)),
                      ofc=(partial(self.changeSetting, 'hud', 0)))
        cmds.checkBox(label="Viewport2",
                      align="left",
                      v=True,
                      onc=(partial(self.changeSetting, 'rnm', 'vp2Renderer')),
                      ofc=(partial(self.changeSetting, 'rnm',
                                   'base_OpenGL_Renderer')))

        focalLst = [12, 20, 27, 35, 45, 50, 80, 100, 125]

        cmds.optionMenu("RS_lensOpt", label="Lens", w=80)
        for i in focalLst:
            cmds.menuItem(l=str(i))
        cmds.optionMenu("RS_lensOpt", edit=True, v="35")
        cmds.setAttr((self.camName + ".focalLength"), 35)
        cmds.optionMenu("RS_lensOpt", edit=True, cc=self.setFocallength)
        cmds.setParent(masterLayout)

        self.bts.makeSeparator(h=5, w=self.W)
        nc = 4
        mainSetting = cmds.rowColumnLayout(nc=nc,
                                           cw=self.bts.cwE(nc=nc,
                                                           w=self.W,
                                                           adj=adj))

        cmds.columnLayout(adj=True)
        cmds.frameLayout(bv=True, lv=False)
        self.seqNumber = cmds.intFieldGrp(l='Sequence Number')
        self.shotNumber = cmds.intFieldGrp(l='Shot Number')
        self.stageCheck = cmds.textFieldGrp(l='Shot Stage', tx='')
        nc = 2
        cmds.rowColumnLayout(nc=nc,
                             cw=self.bts.cwE(nc=nc,
                                             w=(self.W - adj) / 4,
                                             adj=adj / 2))
        self.bts.makeAcoolButton('Create Shot Display', 'Create Shot Display',
                                 self.shotHUD)
        self.bts.makeAcoolButton('Delete Shot Display', 'Delete', self.delHUD)
        cmds.setParent(mainSetting)

        cmds.columnLayout(adj=True)
        cmds.frameLayout(bv=True, lv=False)
        cmds.optionMenu('ActiveCam', l='Camera', w=80)
        for cam in self.camLst:
            if cmds.objExists(cam):
                print cam

        for i in self.camLst:
            cmds.menuItem(l=str(i))
        cmds.optionMenu('ActiveCam', edit=True, cc=self.changeActiveCamera)
        cmds.setParent(mainSetting)

        cmds.setParent(masterLayout)
        self.bts.makeSeparator(h=5, w=self.W)
        self.bts.makeAcoolButton('Capture this frame', "Capture",
                                 partial(self.captureImage, fileName))
        cmds.control(tempLayout, e=1, visible=False)
        cmds.showWindow(renderViewID)

        logger.info(renderViewID)
Пример #48
0
select(cl=1)

## 全部显示/隐藏
modelEditor('modelPanel4', edit=True, allObjects=0)
# 只显示模型
modelEditor('modelPanel4', edit=True, polymeshes=1)

mel.eval('setAttr "defaultResolution.width" 2048;')
mel.eval('setAttr "defaultResolution.height" 858;')

# maya.mel.eval('setNamedPanelLayout("Four View")')
mel.eval('setNamedPanelLayout("Single Perspective View")')

perspPanel = cmds.getPanel(withLabel='Persp View')
# editor = cmds.modelEditor()
cmds.modelEditor(perspPanel, edit=True, displayAppearance='wireframe')

select(cam_name)
cam = selected()[0]
cam_name_shape = cam.getShape()
cam_name_shape.name()
cmds.lookThru('perspView', cam_name_shape.name(), nc=100, fc=200)

print '*' * 100
print u'文件检查完毕'
print u'检查项目:\n '
print u'时间条、相机安全框、相机锁定、70F_TPOSE、隐藏控制器'
# message = u'文件检查完毕 -- 检查项目:-- 时间条、Sound、相机安全框、相机锁定、70F_TPOSE、隐藏控制器'
message = u'<font size="15"><b>文件检查完毕 -- 检查项目:</b><br>时间条、Sound、相机安全框、相机锁定、隐藏控制器、摄像机视图、渲染尺寸</font>'
cmds.confirmDialog(title=u'提交检查',
                   message=message,
Пример #49
0
 def changeActiveCamera(self, *args):
     camera = cmds.optionMenu('ActiveCam', query=True, v=True) + 'Shape'
     cmds.modelEditor(self.panel, e=True, cam=camera)
Пример #50
0
    def addCharacter(self, close, *args):

        project = cmds.optionMenu(self.widgets["project"], q=True, value=True)

        selectedCharacter = cmds.textScrollList(self.widgets["characterList"],
                                                q=True,
                                                si=True)[0]

        rigPath = self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" + selectedCharacter + ".mb"

        #find existing namespaces in scene

        namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)

        #reference the rig file

        cmds.file(rigPath,
                  r=True,
                  type="mayaBinary",
                  loadReferenceDepth="all",
                  namespace=selectedCharacter,
                  options="v=0")

        #clear selection and fit view

        cmds.select(clear=True)

        #query autoKeyFrame state

        if not cmds.autoKeyframe(q=True, state=True):

            cmds.viewFit()

        #cmds.viewFit()

        panels = cmds.getPanel(type='modelPanel')

        #turn on smooth shading

        for panel in panels:

            editor = cmds.modelPanel(panel, q=True, modelEditor=True)

            cmds.modelEditor(editor,
                             edit=True,
                             displayAppearance="smoothShaded",
                             displayTextures=True,
                             textures=True)

        #find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created)

        newCharacterName = selectedCharacter

        newNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True)

        for name in newNamespaces:

            if name not in namespaces:

                newCharacterName = name

        #launch UI

        import ART_animationUI

        reload(ART_animationUI)

        ART_animationUI.AnimationUI()

        if close:

            cmds.deleteUI(self.widgets["window"])
Пример #51
0
def takePlayblast(silent = True, custom = False, customPath = None):
    renWidth = mc.getAttr("defaultResolution.width")
    renHeight = mc.getAttr("defaultResolution.height")
    aspRatio = renWidth/float(renHeight)
    width = renWidth/2 if renWidth > 960 else renWidth
    height = renHeight/2 if renWidth > 960 else renHeight
    mayaShot = ppc.MayaShot()
    if not mayaShot.validShot:
        msgWin("Warning", "Invalid Shot or Project", True)
        if not custom:
            return False
        else:
            viewport = getActiveViewport(silent)
            if not viewport: return False
            mc.setFocus(viewport)
            scCam = mc.modelPanel(viewport, q = True, cam = True)
            scCamSshp = mc.listRelatives(scCam, c = 1, s = 1, ni = 1)
            stereo = True if mc.nodeType(scCamSshp == "stereoRigCamera") else False
            soundName = "NoIdea"
    else:
        if round(aspRatio, 2) ==  1.78:
            width = 960
            height = 540
        else:
            width = mayaShot.projInfo.resWidth/2 if mayaShot.projInfo.resWidth > 1280 else mayaShot.projInfo.resWidth
            height = mayaShot.projInfo.resHeight/2 if mayaShot.projInfo.resWidth > 1280 else mayaShot.projInfo.resHeight
        soundName = "%s%s_aud"%(mayaShot.epSqName, mayaShot.shName)
        scCam = mayaShot.getSceneCamera(False)
        stereo = mayaShot.projInfo.stereo
        sceneCleanup(True)
    if not scCam or not mc.objExists(scCam):
        msgWin('Error', "Couldn't find a valid camera in the scene", silent)
        return False
    if stereo and custom:
        getCam = mc.confirmDialog(title = 'Select Camera', message = 'Which Stereo Camera do you want to take Playblast from?', button = ['Left','Center','Right','Cancel'], cb = 'Cancel', ds = 'Cancel')
        if getCam == 'Left':
            scCam = scCam.replace("_camCt", "_camLt")
        elif getCam == 'Right':
            scCam = scCam.replace("_camCt", "_camRt")
        elif getCam == 'Cancel':
            return False
    if mc.window('playBlastWindow', exists = 1): mc.deleteUI('playBlastWindow')
    if mc.windowPref ('playBlastWindow', exists = 1): mc.windowPref ('playBlastWindow', remove = 1)
    pbTmp = mc.window("playBlastWindow", wh = (1000, 700), te = 50, le = 50)
    mc.paneLayout()
    modPane = mc.modelPanel()
    mc.showWindow(pbTmp)
    mc.lookThru(scCam, modPane)
    mc.modelEditor(modPane, e=True, allObjects=0)
    mc.modelEditor(modPane, e=True, nurbsSurfaces=1, polymeshes=1,fluids=1,strokes=1)
    mc.modelEditor(modPane, e=True, da='smoothShaded')
    mc.modelEditor(modPane, e=True, av = True)
    sounds = mc.ls('%s*'%soundName, typ='audio')
    if not sounds:
        sounds = mc.ls(typ='audio')
    sound = sounds[0]  if sounds else ''
    st = mc.playbackOptions(q = True, ast = True)
    en = mc.playbackOptions(q = True, aet = True)
    blastPath = os.path.join(os.environ['TMP'], 'tempPlayblast.avi')
    if custom:
#        Find the highlighted range on timeSlider (if any)..
        aPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider')
        times = mc.timeControl(aPlayBackSlider, q=True, rng=1)
        times = times.replace('"', '').split(':')
        if int(times[1]) != int(times[0]) +1 :  # 'll be currentTime & currentTime+1 evenif no range selected ==> Exclude that case!
            st = int(times[0])
            en = int(times[1]) -1
        finalPath = None
    else:
        st = 101
        en = 100 + mayaShot.frames
        finalPath = customPath if customPath else mayaShot.shotPath.replace(".%s"%mayaShot.projInfo.mayaExt, ".avi")
        saveVersion(finalPath)
    width = width*2
    height = height*2
    mc.playblast(st = st, et = en, fmt = 'movie', f = blastPath, s = sound, c = 'Lagarith', fo = True, orn = True, p = 50, qlt = 100, w = width, h = height)
    if finalPath:
        try:
            shutil.copyfile(blastPath, finalPath)
        except:
            msgWin("Error", "Error copying %s to %s"%(blastPath, finalPath), False)
    mc.deleteUI(pbTmp)
    return True
Пример #52
0
def clear_panel():
    mc.modelEditor('modelPanel4', e=1, allObjects=0)
    mc.modelEditor('modelPanel4', e=1, lights=1)
    mc.modelEditor('modelPanel4', e=1, pm=1)
Пример #53
0
    def execute(self, tasks, work_template, comment, thumbnail_path, sg_task,
                primary_task, primary_publish_path, progress_cb, **kwargs):
        """
		Main hook entry point
		:param tasks:				   List of secondary tasks to be published.  Each task is a 
										dictionary containing the following keys:
										{
											item:   Dictionary
													This is the item returned by the scan hook 
													{   
														name:		   String
														description:	String
														type:		   String
														other_params:   Dictionary
													}
												   
											output: Dictionary
													This is the output as defined in the configuration - the 
													primary output will always be named 'primary' 
													{
														name:			 String
														publish_template: template
														tank_type:		String
													}
										}
						
		:param work_template:		   template
										This is the template defined in the config that
										represents the current work file
			   
		:param comment:				 String
										The comment provided for the publish
						
		:param thumbnail:			   Path string
										The default thumbnail provided for the publish
						
		:param sg_task:				 Dictionary (shotgun entity description)
										The shotgun task to use for the publish	
						
		:param primary_publish_path:	Path string
										This is the path of the primary published file as returned
										by the primary publish hook
						
		:param progress_cb:			 Function
										A progress callback to log progress during pre-publish.  Call:
										
											progress_cb(percentage, msg)
											 
										to report progress to the UI
						
		:param primary_task:			The primary task that was published by the primary publish hook.  Passed
										in here for reference.  This is a dictionary in the same format as the
										secondary tasks above.
		
		:returns:					   A list of any tasks that had problems that need to be reported 
										in the UI.  Each item in the list should be a dictionary containing 
										the following keys:
										{
											task:   Dictionary
													This is the task that was passed into the hook and
													should not be modified
													{
														item:...
														output:...
													}
													
											errors: List
													A list of error messages (strings) to report	
										}
		"""
        def FindFirstImageOfSequence(FolderPath):
            ImgsList = []
            for file in (os.listdir(FolderPath)):
                SeqImgName = str.split(str(file), ".")[1]
                ImgsList.append(SeqImgName)
            First_elmnt = ImgsList[0]
            return First_elmnt

        def FindFirstImageOfSequence(FolderPath):
            ImgsList = []
            for file in (os.listdir(FolderPath)):
                if file.endswith(".png"):
                    SeqImgName = str.split(str(file), ".")[1]
                    ImgsList.append(int(SeqImgName))
                First_elmnt = ImgsList[0]
            return First_elmnt

        def FindLastImageOfSequence(FolderPath):
            ImgsList = []
            for file in (os.listdir(FolderPath)):
                if file.endswith(".png"):
                    SeqImgName = str.split(str(file), ".")[1]
                    ImgsList.append(int(SeqImgName))
                Last_elmnt = ImgsList[-1]
            return Last_elmnt

        def FindLengthOfSequence(FolderPath):
            ImgsList = []
            for file in (os.listdir(FolderPath)):
                if file.endswith(".png"):
                    SeqImgName = str.split(str(file), ".")[1]
                    ImgsList.append(int(SeqImgName))
                Length_seq = len(ImgsList)
            return Length_seq

        def MakeListOfSequence(FolderPath):
            ImgsList = []
            for file in (os.listdir(FolderPath)):
                if file.endswith(".png"):
                    SeqImgName = str.split(str(file), ".")[1]
                    ImgsList.append(int(SeqImgName))
            return ImgsList

        def FindMissingFramesFromSequence(SequenceSet, inputStart, inputEnd):
            # my_list= list(range( int(FindFirstImageOfSequence(os.path.dirname(RenderPath)))	, int(FindLastImageOfSequence(os.path.dirname(RenderPath)))	 ))
            my_list = list(range(inputStart, inputEnd))
            MissingFrames = set(my_list) - set(SequenceSet)
            return sorted(MissingFrames)

        def combineMediaFiles(fileList,
                              output,
                              concatTxt=None,
                              ffmpeg_path="ffmpeg"):
            rootPath = str.split(str(fileList[0]), "/q")[0]
            mediaType = str.rsplit(str(fileList[0]), ".", 1)[1]
            mediaFilePresent = False
            mediaListFile = rootPath + '/tmp_' + mediaType + 'List.txt'
            if concatTxt != None:
                mediaListFile = concatTxt
            with open(mediaListFile, 'w') as mediaTxtFile:
                for mediaFile in fileList:
                    if os.path.exists(mediaFile):
                        mediaFilePresent = True
                        #print mediaFile
                        shotPath = str.split(str(mediaFile), "/")[-1]
                        if 'Sequences' in mediaFile:
                            shotPath = str.split(str(mediaFile),
                                                 "Sequences")[1][1:]
                        if concatTxt != None:
                            shotPath = str.split(
                                str(mediaFile),
                                os.path.dirname(concatTxt))[1][1:]
                        mediaTxtFile.write("file '" + shotPath + "'")
                        mediaTxtFile.write('\r\n')
                    else:
                        print("AUDIO FILE NOT FOUND :  " + str(mediaFile))
                        # results.append({"task":"audio stuff", "errors":("AUDIO FILE NOT FOUND :  " + str(mediaFile))})
            if mediaFilePresent:
                # command = os.path.normpath(ffmpeg_path + ' -f concat -i '+mediaListFile+' -c copy '+output + " -y")
                # command = os.path.normpath(ffmpeg_path + ' -f concat -r 24 -i '+mediaListFile+' -vcodec mjpeg -r 24 -qscale 1 -pix_fmt yuvj420p -acodec pcm_s16le -ar 48000 -ac 2 '+output + " -y")
                command = os.path.normpath(
                    ffmpeg_path + ' -f concat -r 24 -i ' + mediaListFile +
                    ' -vcodec mjpeg -r 24 -qscale 1 -pix_fmt yuvj420p ' +
                    output + " -y")
                command = str.replace(str(command), "\\", "/")
                #print command
                if sys.platform == "linux2":
                    value = subprocess.call(command, shell=True)
                elif sys.platform == "win32":
                    value = subprocess.call(command,
                                            creationflags=CREATE_NO_WINDOW,
                                            shell=False)
                elif sys.platform == "darwin":
                    value = subprocess.call(command, shell=True)

                return output
            else:
                return None

        def findLatestPublish(seq, step):
            pub_files = self.parent.shotgun.find(
                'PublishedFile', [['name', 'is', seq + "_" + step]],
                fields=['version_number', 'path'])
            highest = 0
            for pub in pub_files:
                print pub
                ver = int(pub["version_number"])
                if ver > highest:
                    highest = ver
            return highest

        def findLastVersion(FolderPath,
                            returnFile=False,
                            returnFilePath=False):
            if os.path.exists(FolderPath):
                fileList = os.listdir(FolderPath)
            else:
                return 0
            if fileList != []:
                fileList.sort()
                lastVersion = fileList[-1]
                version = int(re.findall('\d+', lastVersion)[-1])
                if returnFilePath:
                    return FolderPath + "/" + lastVersion
                if returnFile:
                    return lastVersion
                return version
                #return str(FolderPath+"/"+lastVersion)
            else:
                return 0

        def orderMovs(movList, orderList):
            tmp = ""

        def setAudioToCorrectPath():
            scenePath = cmds.file(q=True, sceneName=True)
            scene_template = tk.template_from_path(scenePath)
            flds = scene_template.get_fields(scenePath)
            audio_template = tk.templates["shot_published_audio"]

            tank = sgtk.tank_from_entity('Project', 66)

            allShots = cmds.ls(type="shot")
            allAudio = cmds.ls(type="audio")
            reportList = []
            returnList = []
            for seqShot in allShots:
                audio = cmds.shot(seqShot, q=True, audio=True)
                audioFile = cmds.getAttr(
                    audio + ".filename"
                )  # "W:/RTS/1_PREPROD/13_ANIMATIC/q340/splitshots/wav new 01/q340_s260_snd_v001.wav";
                #print audioFile
                flds['Shot'] = flds['Sequence'] + "_" + seqShot
                audioOutputFile = audio_template.apply_fields(flds)
                #audioOutputPath = str.replace(str(audioOutputPath),"\\","/")
                #print audioFile
                audioFile = str.replace(str(audioFile), "Z:/Richard The Stork",
                                        "W:/RTS")
                audioOutputPath = str.rsplit(str(audioOutputFile), "\\", 1)[0]
                print audioOutputPath
                if os.path.exists(audioOutputPath):
                    audioOutputFile = findLastVersion(audioOutputPath, True,
                                                      True)
                    if audioOutputFile != 0:
                        newAudio = str.rsplit(audioOutputFile, "/", 1)[-1]
                        newAudio = str.split(newAudio, ".")[0]
                        print newAudio
                        cmds.delete(audio)
                        ref = cmds.file(audioOutputFile,
                                        r=True,
                                        type="audio",
                                        mergeNamespacesOnClash=False,
                                        namespace="audio")
                        #
                        offset = cmds.getAttr(seqShot + ".sequenceStartFrame")
                        cmds.setAttr(newAudio + ".offset", offset)
                        cmds.connectAttr(newAudio + ".message",
                                         seqShot + ".audio")

                        shotEnd = cmds.getAttr(seqShot + ".sequenceEndFrame")
                        audioEnd = cmds.getAttr(newAudio + ".endFrame")
                        if audioEnd < shotEnd:
                            reportList += [
                                newAudio + "  is shorter than shot !!!"
                            ]
                        if audioEnd > shotEnd:
                            reportList += [
                                newAudio +
                                "  was longer than shot. now cut to match!!!"
                            ]
                            cmds.setAttr(newAudio + ".endFrame", shotEnd + 1)

                        returnList += [newAudio]
                else:
                    print "skipped ", audio
            for report in reportList:
                print report
            return returnList

        def getStereoCams(sht):
            leftCam = ""
            rightCam = ""
            prevCamShape = cmds.shot(sht, q=True, cc=True)
            prevCam = cmds.listRelatives(prevCamShape, p=True)
            prevCamParent = cmds.listRelatives(prevCam, p=True)
            for obj in cmds.listRelatives(prevCamParent):
                if cmds.objectType(obj) == 'stereoRigTransform':
                    leftCam = str(
                        cmds.listConnections(obj + ".leftCam", source=True)[0])
                    rightCam = str(
                        cmds.listConnections(obj + ".rightCam",
                                             source=True)[0])
            return [leftCam, rightCam]

        wtd_fw = self.load_framework("tk-framework-wtd_v0.x.x")
        ffmpeg = wtd_fw.import_module("pipeline.ffmpeg")

        # ffmpeg.test()

        def _register_publish(path,
                              name,
                              sg_task,
                              publish_version,
                              tank_type,
                              comment,
                              thumbnail_path,
                              context=None,
                              tagList=[]):
            """
			Helper method to register publish using the 
			specified publish info.
			"""
            ctx = self.parent.tank.context_from_path(str(path))
            # construct args:
            args = {
                "tk": self.parent.tank,
                "sg_status_list": "cmpt",
                "context": context,
                "comment": comment,
                "path": path,
                "name": name,
                "version_number": publish_version,
                "thumbnail_path": thumbnail_path,
                "sg_task": sg_task,
                "published_file_type": tank_type,
                "user": ctx.user,
                "created_by": ctx.user
            }
            print "-------------------"

            postPubArgs = {}

            if ctx.user != None:
                fields = ["sg_company"]
                company = self.parent.shotgun.find_one(
                    "HumanUser", [['id', 'is', ctx.user["id"]]],
                    fields)["sg_company"]
                studios = {
                    'Walking the Dog': 'wtd',
                    'Studio Rakete': 'rakete',
                    'Bug': 'bug',
                    'RiseFX': 'risefx',
                    'Studio 352': '352'
                }
                sync_field = "sg_sync_%s" % (studios[company])

                postPubArgs[sync_field] = "cmpt"

                sync_field_others = [
                    "sg_sync_wtd", "sg_sync_352", "sg_sync_rakete"
                ]
                for other_sync in sync_field_others:
                    if other_sync != sync_field:
                        postPubArgs[other_sync] = "wtg"

            for a in args:
                print a, args[a]
            # print args
            # register publish;
            sg_data = tank.util.register_publish(**args)
            print 'Register in shotgun done!'

            postPubArgs['tag_list'] = tagList
            tk.shotgun.update('PublishedFile', sg_data['id'], postPubArgs)

            return sg_data

        def orderShots(shotDictList):
            valueOrderList = []
            valueOrderListSecondary = []
            listIndex = 0
            for sht in shotDictList:
                orderNr = str("00000" + str(sht['sg_cut_order']))[-4:]
                addValue = str(listIndex)
                if sht['sg_status_list'] == 'omt':
                    addValue = 'omt'
                if sht['parent_shots'] == []:
                    valueOrderList += [orderNr + ">>" + addValue]
                else:
                    valueOrderListSecondary += [orderNr + ">>" + addValue]
                listIndex += 1
            valueOrderList = sorted(valueOrderList) + sorted(
                valueOrderListSecondary)
            orderedList = []
            for sht in valueOrderList:
                addValue = str.split(sht, '>>')[1]
                if addValue != "omt":
                    orderedList += [shotDictList[int(addValue)]]
            return orderedList

        def checkSoundCut():
            allShots = cmds.ls(type="shot")
            allAudio = cmds.ls(type="audio")
            sequenceList = []
            for seqShot in allShots:
                #print "---", seqShot
                shotStart = int(cmds.getAttr(seqShot + ".sequenceStartFrame"))
                shotEnd = int(cmds.getAttr(seqShot + ".sequenceEndFrame"))
                #print shotStart
                #print shotEnd
                sequenceList.append({"shot": seqShot})
                audioList = []
                audioIn = []
                audioOut = []
                for aud in allAudio:

                    add = False
                    aIn = 0
                    aOut = 0
                    audioStart = int(cmds.getAttr(aud + ".offset"))
                    audioEnd = int(cmds.getAttr(aud + ".endFrame")) - 1
                    audioOriginalDuration = int(cmds.getAttr(aud +
                                                             ".duration"))
                    audioDuration = audioEnd - audioStart

                    if shotStart < audioStart < shotEnd:
                        add = True
                        if audioEnd > shotEnd:
                            aOut = shotEnd - audioStart
                    if shotStart < audioEnd < shotEnd:
                        add = True
                        aIn = audioDuration - (audioEnd - shotStart)
                    if audioStart < shotStart < audioEnd:
                        add = True
                        aIn = shotStart - audioStart
                    if audioStart < shotEnd < audioEnd:
                        add = True
                        aOut = audioDuration - (audioEnd - shotEnd) + 1

                    if add:
                        audioList.append([aud, aIn, aOut])

                sequenceList[-1]["audioList"] = audioList

            scenePath = cmds.file(q=True, sceneName=True)
            scene_template = tk.template_from_path(scenePath)
            audio_template = tk.templates["shot_published_audio"]
            flds = scene_template.get_fields(scenePath)
            flds['Step'] = 'snd'
            soundCheckList = ["These audio cuts dont match the camera cuts."]
            for audio in sequenceList:
                if audio['audioList'] != []:
                    #print audio['shot']
                    flds['Shot'] = flds['Sequence'] + "_" + str(audio['shot'])
                    i = 0
                    newAudio = []
                    soundCheckList += [""]
                    soundCheckList += [
                        "audio files overlapping shot " + audio['shot']
                    ]
                    for aud in audio['audioList']:
                        inSec = float(aud[1]) / 24
                        outSec = float(aud[2]) / 24
                        print aud[0], inSec, outSec
                        # print "------>>>>>>>>>", aud
                        soundCheckList += [
                            aud[0] + "   cut in offset = " + str(aud[1]) +
                            "   cut out offset = " + str(aud[2])
                        ]

            return sequenceList

        def MakeSoundCuts(ffmpegPath, Input, Output, Position, Duration):
            time01 = Position
            time02 = Duration
            if os.path.isfile(Output):
                os.remove(Output)
            subprocess.call('%s -i "%s" -ss "%s" -t "%s" -acodec copy "%s"' %
                            (ffmpegPath, Input, time01, time02, Output))

        def fixSound(sequenceList):
            ## tempfile function supposed to work on linux/ drawin
            tmpFolder = tempfile.gettempdir()
            if not os.path.exists(tmpFolder):
                os.makedirs(tmpFolder)
            scenePath = cmds.file(q=True, sceneName=True)
            sceneName = str.split(str(scenePath), "/")[-1]
            scene_template = tk.template_from_path(scenePath)
            audio_template = tk.templates["shot_published_audio"]
            flds = scene_template.get_fields(scenePath)
            flds['Step'] = 'snd'
            for audio in sequenceList:
                if audio['audioList'] != []:
                    print audio['shot']
                    flds['Shot'] = flds['Sequence'] + "_" + str(audio['shot'])
                    i = 0
                    newAudio = []
                    for aud in audio['audioList']:
                        inSec = float(aud[1]) / 24
                        outSec = float(aud[2]) / 24
                        print aud[0], inSec, outSec
                        if outSec == 0.0:
                            outSec = 10000
                        input = cmds.getAttr(aud[0] + '.filename')
                        output = tmpFolder + "/" + audio[
                            'shot'] + "_part" + str(i) + str.split(
                                str(input), "/")[-1]
                        i += 1
                        MakeSoundCuts(ffmpegPath, input, output, inSec, outSec)
                        newAudio += [output]
                    audioOutput = audio_template.apply_fields(flds)

                    # version UP
                    latestVersion = findLastVersion(
                        os.path.dirname(audioOutput)) + 1
                    flds['version'] = latestVersion
                    audioOutput = audio_template.apply_fields(flds)
                    # combine
                    mergedAudio = combineMediaFiles(
                        newAudio, audioOutput, tmpFolder + "/tmp_wavList.txt",
                        ffmpegPath)

                    ver = str(
                        findLastVersion(os.path.dirname(audioOutput), True))
                    newAudioName = str.rsplit(ver, "_", 1)[0]
                    cmds.file(audioOutput,
                              i=True,
                              type="audio",
                              mergeNamespacesOnClash=False,
                              namespace=flds['Shot'] + "_audio",
                              resetError=True)
                    crappyAudioName = str.split(ver, ".")[0]
                    cmds.rename(crappyAudioName, newAudioName)
                    cutIn = cmds.getAttr(audio['shot'] + ".startFrame")
                    cutOut = cmds.getAttr(audio['shot'] + ".endFrame")
                    cutDuration = cutOut - cutIn
                    cmds.setAttr(newAudioName + ".offset", cutIn)
                    cmds.setAttr(newAudioName + ".sourceEnd", cutDuration + 1)
                    cmds.connectAttr(newAudioName + ".message",
                                     audio['shot'] + ".audio",
                                     f=True)
                    print "-----------------------------------------------------------------------------________________-------------------------------------------------------------------------"
                    # PUBLISH
                    file_template = tk.template_from_path(audioOutput)
                    flds = file_template.get_fields(audioOutput)
                    print audioOutput
                    ctx = tk.context_from_path(audioOutput)

                    print ctx

                    sg_task = tk.shotgun.find("Task",
                                              [['content', 'is', "Sound"],
                                               ["entity", 'is', ctx.entity]],
                                              ['id'])
                    try:
                        sg_task = sg_task[0]
                    except indexError:
                        print "SKIPPED - are the folders already created on shotgun?????"
                        errors.append(
                            "SKIPPED - are the folders already created on shotgun?????"
                        )
                    if sg_task != []:
                        _register_publish(audioOutput, newAudioName, sg_task,
                                          flds['version'], "Audio", "publish",
                                          "", ctx,
                                          ["from maya : " + sceneName])
                    else:
                        print "SKIPPED - are the folders already created on shotgun?????"
                        errors.append(
                            "SKIPPED - are the folders already created on shotgun?????"
                        )
                        #popup('error',"skipped creation of "+newAudioName+" - are the folders already created on shotgun??")

            for audio in sequenceList:
                if audio['audioList'] != []:
                    for aud in audio['audioList']:
                        if cmds.objExists(aud[0]):
                            print "------------------", aud[
                                0], "------------------------"
                            cmds.delete(aud[0])

        shots = cmds.ls(type="shot")
        shotCams = []
        unUsedCams = []

        sides = ["l", "r"]

        pbShots = []
        CutInList = []
        parentShotList = []

        # these booleans can be used for
        noOverscan = False
        resetCutIn = False

        # template stuff...
        # tk = tank.tank_from_path("W:/RTS/Tank/config")
        tk = self.parent.tank
        scenePath = cmds.file(q=True, sceneName=True)
        scene_template = tk.template_from_path(scenePath)
        flds = scene_template.get_fields(scenePath)
        flds['width'] = 1724
        flds['height'] = 936
        pb_template = tk.templates["maya_seq_playblast_publish"]
        pb_template_current = tk.templates["maya_seq_playblast_current"]
        pbArea_template = tk.templates["maya_seq_playblast_publish_area"]
        audio_template = tk.templates["shot_published_audio"]
        mov_template = tk.templates[
            "maya_seq_playblast_publish_currentshots_mov"]
        mov_shot_template = tk.templates[
            "maya_shot_playblast_publish_currentshots_mov"]
        mp4_shot_template = tk.templates[
            "maya_shot_playblast_publish_currentshots_mp4"]

        concatMovTxt = tk.templates["maya_seq_playblast_publish_concatlist"]
        pbMov = tk.templates["maya_seq_playblast_publish_mov"]
        pbMp4 = tk.templates["maya_seq_playblast_review_mp4"]

        # get extra shot info through shotgun
        fields = ['id']
        sequence_id = self.parent.shotgun.find(
            'Sequence', [['code', 'is', flds['Sequence']]], fields)[0]['id']
        fields = [
            'id', 'code', 'sg_asset_type', 'sg_cut_order', 'sg_cut_in',
            'sg_cut_out', 'sg_cut_duration', 'sg_status_list', 'parent_shots'
        ]
        filters = [[
            'sg_sequence', 'is', {
                'type': 'Sequence',
                'id': sequence_id
            }
        ]]
        assets = self.parent.shotgun.find("Shot", filters, fields)
        results = []
        errors = []
        if sys.platform == "linux2":
            ffmpegPath = r'%s' % (os.getenv(
                'FFMPEG', '/rakete/tools/rakete/ffmpeg/lx64/ffmpeg'))
        elif sys.platform == "win32":
            ffmpegPath = '"' + os.environ.get('FFMPEG_PATH')
            if "ffmpeg.exe" not in ffmpegPath:
                ffmpegPath += "\\ffmpeg.exe"
            ffmpegPath += '"'
        elif sys.platform == "darwin":
            ffmpegPath = r'%s' % (os.getenv(
                'FFMPEG', '/rakete/tools/rakete/ffmpeg/lx64/ffmpeg'))
        soundFixList = checkSoundCut()
        print soundFixList
        fixSound(soundFixList)

        for task in tasks:
            item = task["item"]
            output = task["output"]
            errors = []

            #get shots from scan scene
            if item["type"] == "shot":
                shotTask = [item["name"]][0]
                pbShots += [shotTask]
                # get corresponding cut values from shotgun
                for sht in assets:
                    shot_from_shotgun = str.split(sht['code'], "_")[1]
                    if shot_from_shotgun == shotTask:
                        CutInList += [sht['sg_cut_in']]
                        parentShotList += [sht['parent_shots']]

            # set extra settings
            if item["type"] == "setting":
                if item["name"] == "overscan":
                    noOverscan = True
                if item["name"] == "set Cut in":
                    resetCutIn = True

            # if there is anything to report then add to result
            if len(errors) > 0:
                # add result:
                results.append({"task": task, "errors": errors})

        # temporarily hide cams and curves
        modPan = cmds.getPanel(type="modelPanel")
        for pan in modPan:
            cmds.modelEditor(pan, e=True, alo=False, polymeshes=True)
            cmds.modelEditor(pan, e=True, displayAppearance="smoothShaded")
            cmds.modelEditor(pan, e=True, displayTextures=True)
            allobjs = cmds.ls(type="transform")
            boundingboxObjsList = []

            for i in allobjs:
                if cmds.getAttr(i + ".overrideEnabled"):
                    if cmds.getAttr(i + ".overrideLevelOfDetail") == 1:
                        boundingboxObjsList.append(i)
                        cmds.setAttr(i + ".overrideLevelOfDetail", 0)

        currentselection = cmds.ls(sl=True)
        cmds.select(cl=True)

        cmds.headsUpDisplay(lv=False)

        CamsList = cmds.listCameras()
        for Cam in CamsList:
            cmds.camera(Cam, e=True, dr=True, dgm=True, ovr=1.3)

        #Get USER
        USER = sgtk.util.get_current_user(tk)
        if USER == None:
            USER = {
                'email': '*****@*****.**',
                'id': 63,
                'image':
                'https://sg-media-usor-01.s3.amazonaws.com/7df0575d53fc3b61c36343837da18effb72bb6ff/86f714413d0a2c68382b706e8e45991d41a0ffed/thumb_t.jpg?AWSAccessKeyId=AKIAIFHY52V77FIVWKLQ&Expires=1415784134&Signature=%2Ff4qeNQMq4oHscIKePb1IrtRPZQ%3D',
                'login': '******',
                'name': 'WTD RND',
                'type': 'HumanUser'
            }

        # audio stuff
        '''
		stepVersion = flds['version']
		step = flds['Step']
		audioList = []
		for sht in shots:
			#print sht
			flds['Shot'] = (flds['Sequence']+"_"+sht)
			flds['version'] = findLastVersion(os.path.dirname(audio_template.apply_fields(flds)))
			flds['Step'] = 'snd'
			print flds['version']
			if flds['version'] > 0:
				audioList += [str.replace(str(audio_template.apply_fields(flds)),"\\","/")]
		flds['Shot'] = flds['Sequence']
		flds['version'] = stepVersion #set version back
		flds['Step'] = step
		
		audioOutput = pbArea_template.apply_fields(flds)+"/"+flds['Sequence']+"_"+flds['Step']+".wav"
		if audioList != []:
			combinedAudio = combineMediaFiles(audioList,audioOutput, ffmpeg_path = ffmpegPath)
		print ("combined audio at  " + audioOutput)
		'''

        # replacedAudio = setAudioToCorrectPath()
        # for aud in replacedAudio:
        # 	results.append({"task":{'item': aud , 'output': 'replaced' }})

        Test = True
        #Test = False;
        if Test:
            j = 0
            RenderPath = ""
            for pbShot in pbShots:
                CutIn = CutInList[j]
                parentShot = ""
                if parentShotList[j] != []:
                    parentShot = str.split(parentShotList[j][0]['name'],
                                           "_")[-1]
                j += 1

                sequenceName = flds['Sequence']
                shotName = pbShot

                # ... correct this in the templates?
                flds['Shot'] = flds['Sequence'] + "_" + pbShot

                #get camera name from sequence shot
                shotCam = cmds.shot(pbShot, q=True, currentCamera=True)

                # overscanValue = cmds.getAttr(shotCam+".overscan")
                cmds.setAttr(shotCam + ".overscan", 1.3)
                if noOverscan:
                    cmds.setAttr(shotCam + ".overscan", 1)

                shotCams = [shotCam]
                previewCam = shotCam
                if flds['Step'] == 's3d':
                    shotCams = getStereoCams(pbShot)
                s = 0
                for shotCam in shotCams:
                    side = sides[s]
                    s += 1
                    if flds['Step'] == 's3d':
                        flds['eye'] = side.lower()

                    cmds.shot(pbShot, e=True, currentCamera=shotCam)
                    focal = cmds.getAttr(shotCam + '.focalLength')
                    # make outputPaths from templates
                    RenderPath = pb_template.apply_fields(flds)
                    pbPath = str.split(str(RenderPath), ".")[0]
                    renderPathCurrent = pb_template_current.apply_fields(flds)
                    pbPathCurrent = str.split(str(renderPathCurrent), ".")[0]
                    pbPathCurrentMov = mov_template.apply_fields(flds)
                    pbPathCurrentMovShot = mov_shot_template.apply_fields(flds)
                    pbPathCurrentMp4Shot = mp4_shot_template.apply_fields(flds)
                    for pathToMake in [
                            pbPathCurrent, pbPathCurrentMov,
                            pbPathCurrentMovShot, pbPathCurrentMp4Shot
                    ]:
                        if not os.path.exists(os.path.dirname(pathToMake)):
                            #os.makedirs(os.path.dirname(pathToMake))
                            self.parent.ensure_folder_exists(
                                os.path.dirname(pathToMake))

                    # report progress:
                    progress_cb(0, "Publishing", task)

                    shotStart = cmds.shot(pbShot,
                                          q=True,
                                          sequenceStartTime=True)
                    shotEnd = cmds.shot(pbShot, q=True, sequenceEndTime=True)
                    progress_cb(25, "Making playblast %s" % pbShot)
                    cmds.playblast(indexFromZero=False,
                                   filename=(pbPath),
                                   fmt="iff",
                                   compression="png",
                                   wh=(flds['width'], flds['height']),
                                   startTime=shotStart,
                                   endTime=shotEnd,
                                   sequenceTime=1,
                                   forceOverwrite=True,
                                   clearCache=1,
                                   showOrnaments=1,
                                   percent=100,
                                   offScreen=True,
                                   viewer=False,
                                   useTraxSounds=True)
                    progress_cb(50, "Placing Slates %s" % pbShot)

                    Film = "Richard the Stork"
                    #GET CURRENT DATE
                    today = datetime.date.today()
                    todaystr = today.isoformat()
                    """
						Adding Slates to playblast files
					"""
                    for i in range(int(shotStart), int(shotEnd) + 1):
                        FirstPartName = RenderPath.split('%04d')[0]
                        EndPartName = '%04d' % i + RenderPath.split('%04d')[-1]
                        ImageFullName = FirstPartName + EndPartName
                        pbFileCurrent = pbPathCurrent + "." + EndPartName
                        print 'fld ===>', flds
                        print 'USER===>', USER
                        ffmpeg.ffmpegMakingSlates(
                            inputFilePath=ImageFullName,
                            outputFilePath=ImageFullName,
                            topleft=flds['Sequence'] + "_" + flds['Step'] +
                            "_v" + str('%03d' % (flds['version'])),
                            topmiddle=Film,
                            topright=str(int(CutIn)) + "-" +
                            str('%04d' % (i - int(shotStart) + CutIn)) + "-" +
                            str('%04d' %
                                (int(shotEnd) - int(shotStart) + CutIn)) +
                            "  " + str('%04d' % (i - int(shotStart) + 1)) +
                            "-" + str('%04d' %
                                      (int(shotEnd) - int(shotStart) + 1)),
                            bottomleft=shotName + " - focal_Length " +
                            str(focal),
                            bottommiddle=USER['name'],
                            bottomright=todaystr,
                            ffmpegPath=ffmpegPath,
                            font="C:/Windows/Fonts/arial.ttf")
                        print("COPYING PNG " + ImageFullName + "  TO  " +
                              pbFileCurrent + "  FOR SHOT  " + shotName)
                        shutil.copy2(ImageFullName, pbFileCurrent)

                    shotAudio = audio_template.apply_fields(flds)
                    shotAudio = findLastVersion(os.path.dirname(shotAudio),
                                                True, True)
                    if shotAudio == 0:
                        print " NO PUBLISHED AUDIO FOUND"
                        for aud in [parentShot, pbShot]:
                            try:
                                audio = cmds.shot(aud, q=True, audio=True)
                                shotAudio = '"' + cmds.getAttr(
                                    audio + ".filename") + '"'
                                shotAudio = str.replace(
                                    str(shotAudio), "Z:/Richard The Stork/",
                                    'W:/RTS/')
                                print "used audio from maya :  ", shotAudio
                                break
                            except:
                                shotAudio = ''
                    print ffmpeg.ffmpegMakingMovie(
                        inputFilePath=renderPathCurrent,
                        outputFilePath=pbPathCurrentMov,
                        audioPath=shotAudio,
                        start_frame=int(shotStart),
                        end_frame=int(shotEnd),
                        framerate=24,
                        encodeOptions='libx264',
                        ffmpegPath=ffmpegPath)
                    shutil.copy2(pbPathCurrentMov, pbPathCurrentMovShot)
                    ffmpeg.ffmpegMakingMovie(pbPathCurrentMov,
                                             pbPathCurrentMp4Shot,
                                             encodeOptions="libx264",
                                             ffmpegPath=ffmpegPath)
                # end_frame=shotEnd
                cmds.shot(pbShot, e=True, currentCamera=previewCam)

            if currentselection != []:
                cmds.select(currentselection)

            if flds['Step'] == 'lay':
                sides = ['']
            for side in sides:
                if flds['Step'] == 's3d':
                    flds['eye'] = side.lower()

                RenderPath = pb_template.apply_fields(flds)
                print RenderPath

                for i in boundingboxObjsList:
                    cmds.setAttr(i + ".overrideEnabled", True)
                    cmds.setAttr(i + ".overrideLevelOfDetail", 1)
                sequenceTest = MakeListOfSequence(os.path.dirname(RenderPath))
                FistImg = int(
                    FindFirstImageOfSequence(os.path.dirname(RenderPath)))
                LastImg = int(
                    FindLastImageOfSequence(os.path.dirname(RenderPath)))

                FramesMissingList = FindMissingFramesFromSequence(
                    sequenceTest, FistImg, LastImg)
                """
					Copy empty frames
				"""
                # blackFrame = False
                # blackFrameName = ""
                # for n in FramesMissingList:
                # if blackFrame == False:
                # blackFrameName = FirstPartName+str('%04d' % n)+".png"
                # value = subprocess.call('%s -f lavfi -i color=c=black:s="%s" -vframes 1 "%s"' %(ffmpegPath,(str(flds['width'])+"x"+ str(flds['height'])),FirstPartName+str('%04d' % n)+".png"))
                # print '%s -f lavfi -i color=c=black:s="%s" -vframes 1 "%s"' %(ffmpegPath,(str(flds['width'])+"x"+ str(flds['height'])),FirstPartName+str('%04d' % n)+".png")
                # blackFrame = True

                # newFrameName = FirstPartName+str('%04d' % n)+".png"
                # if blackFrameName != newFrameName:
                # shutil.copy2(blackFrameName, newFrameName)

                FirstImageNumber = FindFirstImageOfSequence(
                    os.path.dirname(RenderPath))
                FirstImageNumberSecond = FirstImageNumber / 24
                '''
				makeSeqMov
				'''
                concatTxt = concatMovTxt.apply_fields(flds)
                pbMovPath = pbMov.apply_fields(flds)
                pbMp4Path = pbMp4.apply_fields(flds)
                pbMp4Path = str.replace(str(pbMp4Path), '\\', '/')

                pbMovFile = str.split(str(pbMovPath),
                                      os.path.dirname(pbMovPath))[1][1:]

                # movList = []
                # for mov in os.listdir(os.path.dirname(pbPathCurrentMov)):
                # 	movList += [os.path.dirname(pbPathCurrentMov)+"/"+mov]
                # print movList

                assetsOrdered = orderShots(assets)
                movList = []
                for ass in assetsOrdered:
                    for mov in os.listdir(os.path.dirname(pbPathCurrentMov)):
                        movName = str.split(str(mov), ".")[0]
                        if ass['code'] == movName:
                            movList += [
                                os.path.dirname(pbPathCurrentMov) + "/" + mov
                            ]
                ## need to keep that for s3d layout
                if flds['Step'] == 's3d':
                    for ass in assetsOrdered:
                        for mov in os.listdir(
                                os.path.dirname(pbPathCurrentMov)):
                            movName = str.split(str(mov), ".")[0]
                            if "%s_%s" % (ass['code'], flds['eye']) == movName:
                                movList += [
                                    os.path.dirname(pbPathCurrentMov) + "/" +
                                    mov
                                ]

                makeSeqMov = True
                if makeSeqMov:
                    if not os.path.exists(os.path.dirname(pbMovPath)):
                        self.parent.ensure_folder_exists(
                            os.path.dirname(pbMovPath))
                        # os.makedirs(os.path.dirname(pbMovPath))

                    if not os.path.exists(os.path.dirname(pbMp4Path)):
                        print "creating", pbMp4Path
                        self.parent.ensure_folder_exists(
                            os.path.dirname(pbMp4Path))
                        print "created", pbMp4Path
                        # os.makedirs(os.path.dirname(pbMp4Path))
                    """
						SEQUENCE MOV and MP4 Creation
					"""
                    print "Making mov and mp4: \n", pbMovPath, ' --- ', pbMp4Path
                    print movList
                    print combineMediaFiles(movList, pbMovPath, concatTxt,
                                            ffmpegPath)

                    amount = 0
                    while not os.path.exists(pbMovPath) and amount < 10:
                        time.sleep(1)
                        amount += 1

                    print ffmpeg.ffmpegMakingMovie(pbMovPath,
                                                   pbMp4Path,
                                                   encodeOptions="libx264",
                                                   ffmpegPath=ffmpegPath)

                    # ----------------------------------------------
                    # UPLOAD MP4
                    # ----------------------------------------------

            upload = True
            if upload:
                user = self.parent.context.user
                scenePath = cmds.file(q=True, sceneName=True)
                ctx = self.parent.tank.context_from_path(scenePath)
                fields = ['id']
                sg_task = self.parent.shotgun.find(
                    "Task", [['content', 'is', ctx.step['name']],
                             ["entity", 'is', ctx.entity]], fields)
                RenderPath = re.sub('\_(l|r)\.', '_%v.', RenderPath)

                data = {
                    'project': {
                        'type': 'Project',
                        'id': 66
                    },
                    'entity': {
                        'type': 'Sequence',
                        'id': int(sequence_id)
                    },
                    'code':
                    flds['Sequence'] + "_" + flds['Step'] + "_v" +
                    str('%03d' % (flds['version'])),
                    'sg_path_to_frames':
                    re.sub('\.[0-9]{4}\.', '.%04d.', (RenderPath)),
                    'sg_path_to_movie':
                    re.sub('\_(l|r)\.', '_%v.', pbMovPath),
                    'sg_version_type':
                    'publish',
                    'user':
                    user,
                    'created_by':
                    user,
                    'updated_by':
                    user,
                    'sg_task':
                    sg_task[0]
                }

                if not os.path.exists(os.path.dirname(pbMp4Path)):
                    os.makedirs(os.path.dirname(pbMp4Path))

                findVersion = self.parent.shotgun.find_one(
                    'Version', [[
                        'code', 'is', flds['Sequence'] + "_" + flds['Step'] +
                        "_v" + str('%03d' % (flds['version']))
                    ], ['sg_version_type', 'is', 'publish'],
                                ['sg_task', 'is', sg_task]],
                    ['sg_path_to_movie', 'sg_path_to_frames', 'id'])

                if not findVersion:
                    result = tk.shotgun.create('Version', data)
                else:
                    result = tk.update('Version', findVersion.get('id'), data)
                print "---> UPLOADING ", pbMp4Path
                executed = tk.shotgun.upload("Version", result['id'],
                                             pbMp4Path, 'sg_uploaded_movie')
                print executed

            # PUBLISH
            if sg_task != []:
                # version = tank.util.find_publish(tk,[primary_publish_path],fields=['version'])
                # version = version.get(primary_publish_path).get('version')
                #version = findLastVersion(os.path.dirname(pbMovPath))
                version = findLatestPublish(flds['Sequence'], flds['Step'])
                #sg_task = sg_task[0]
                print sg_task
                _register_publish(re.sub('\_(l|r)\.', '_%v.', pbMovPath),
                                  re.sub('\_(l|r)\.', '_%v.',
                                         pbMovFile), sg_task, version, "Movie",
                                  "published playblast mov", "", ctx)
                print "PUBLISHED"
            else:
                print "SKIPPED PUBLISH"

                # print "TODO : make mov of whole sequence with audio"
        return results
Пример #54
0
def FYXBModifyCameras_zwz():
    mm.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();')
    for i in range(1, 20):
        try:
            tmp = mc.modelEditor('modelPanel%d' % i, q=True, av=True)
        except:
            pass
        else:
            if tmp:
                activePlane = 'modelPanel%d' % i
    myStartFrameV = mc.getAttr("defaultRenderGlobals.startFrame")
    myEndFrameV = mc.getAttr("defaultRenderGlobals.endFrame")
    myCurves = mc.ls(type="nurbsCurve")
    myYeyaShapes = []
    myYeyaTras = []
    tmp = ''
    for each in myCurves:
        if each.find("yeyaShape") >= 0:
            myYeyaShapes.append(each)
    if myYeyaShapes:
        for each in myYeyaShapes:
            try:
                tmp = mc.listRelatives(each, p=True)
            except:
                continue
            if tmp[0].find("yeya") >= 0:
                try:
                    temp = mc.listRelatives(tmp[0], p=True)
                except:
                    continue
                else:
                    if temp[0].find('Master') >= 0:
                        myYeyaTras.append(tmp[0])
    if len(myYeyaTras) == 1:
        MyObject = myYeyaTras[0]
        myYeyaFName = mc.ls(MyObject, ap=True, l=True)[0]
        myYeyaG = myYeyaFName.split('|')[1]
        mc.select(myYeyaG)
        mm.eval("SelectIsolate;")
        myCamG = mc.ls(myYeyaG, dag=True, tr=True)
        flag = 0
        rightSemG = ''
        for each in myCamG:
            if mc.nodeType(each) == 'transform':
                if each.find('semiRing_Cam_Grp') >= 0:
                    if each.find('|') < 0:
                        flag = flag + 1
                        rightSemG = each
        if flag == 1:
            mc.select(cl=True)
            mc.select(rightSemG)
            SetUnlockCameras_zwz(rightSemG, False)
            mc.bakeResults(rightSemG, t=(myStartFrameV, myEndFrameV), sm=True, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'], sb=True, dic=True, pok=True, sac=False, ral=False, bol=False, mr=True, cp=False, s=True)
            SetUnlockCameras_zwz(rightSemG, True)
            mysemRingC = mc.listRelatives(rightSemG, c=True, f=True)
            for peach in mysemRingC:
                try:
                    tmp = mc.nodeType(peach)
                except:
                    pass
                else:
                    if tmp:
                        if tmp == 'pointConstraint' or tmp == 'orientConstraint':
                            mc.delete(peach)

            mc.select(cl=True)
            mc.select(MyObject)
            SetUnlockCameras_zwz(MyObject, False)
            mc.bakeResults(MyObject, t=(myStartFrameV, myEndFrameV), sm=True, at=['rx', 'ry', 'rz'], sb=True, dic=True, pok=True, sac=False, ral=False, bol=False, mr=True, cp=False, s=True)
            SetUnlockCameras_zwz(MyObject, True)
            mc.rename(myYeyaG, '%s_baked' % myYeyaG)
            mc.isolateSelect(activePlane, state=False)
            mc.confirmDialog(title=u'温馨提示:', message=u'摄像机backed成功!\n摄像机大组名字改为%s_baked' % myYeyaG, button=['OK'], defaultButton='Yes', dismissString='No')
        elif flag > 1:
            mc.confirmDialog(title=u'温馨提示:', message=u'创建失败!\n相应的“semiRing_Cam_Grp”个数太多!', button=['OK'], defaultButton='Yes', dismissString='No')
            return
        else:
            mc.confirmDialog(title=u'温馨提示:', message=u'创建失败!\n相应的“semiRing_Cam_Grp”找不到!\n请确认该场是否要Baked摄像机', button=['OK'], defaultButton='Yes', dismissString='No')
            return
    elif len(myYeyaTras) >= 2:
        mc.confirmDialog(title=u'温馨提示:', message=u'创建失败!\n文件中有多个摄像组!', button=['OK'], defaultButton='Yes', dismissString='No')
    else:
        mc.confirmDialog(title=u'温馨提示:', message=u'创建失败!\n文件中没有相应的摄像机组,请导入个正确的!', button=['OK'], defaultButton='Yes', dismissString='No')
Пример #55
0
def traceArc(space='camera'):
    '''
    The main function for creating the arc.
    '''
    
    if space != 'world' and space != 'camera':
        OpenMaya.MGlobal.displayWarning('Improper space argument.')
        return
    
    global ML_TRACE_ARC_PREVIOUS_SELECTION
    global ML_TRACE_ARC_PREVIOUS_SPACE
    
    #save for reset:
    origTime = mc.currentTime(query=True)
    
    #frame range
    frameRange = utl.frameRange()
    start = frameRange[0]
    end = frameRange[1]
    
    #get neccesary nodes
    objs = mc.ls(sl=True, type='transform')
    if not objs:
        OpenMaya.MGlobal.displayWarning('Select objects to trace')
        return
    
    ML_TRACE_ARC_PREVIOUS_SELECTION = objs
    ML_TRACE_ARC_PREVIOUS_SPACE = space
    
    cam = None
    nearClipPlane = None
    shortCam = ''
    if space=='camera':
        cam = utl.getCurrentCamera()
    
        #the arc will be placed just past the clip plane distance, but no closer than 1 unit.
        nearClipPlane = max(mc.getAttr(cam+'.nearClipPlane'),1)
        
        shortCam = mc.ls(cam, shortNames=True)[0]
    
    topGroup = 'ml_arcGroup'
    worldGrp = 'ml_arcWorldGrp'
    localGrp = 'ml_localGrp_'+shortCam
    
    #create nodes
    if not mc.objExists(topGroup):
        topGroup = mc.group(empty=True, name=topGroup)
    
    parentGrp = topGroup
    if space=='world' and not mc.objExists(worldGrp):
        worldGrp = mc.group(empty=True, name=worldGrp)
        mc.setAttr(worldGrp+'.overrideEnabled',1)
        mc.setAttr(worldGrp+'.overrideDisplayType',2)
        mc.parent(worldGrp, topGroup)
        parentGrp = mc.ls(worldGrp)[0]
    
    if space == 'camera':
        camConnections = mc.listConnections(cam+'.message', plugs=True, source=False, destination=True)
        if camConnections:
            for cc in camConnections:
                if '.ml_parentCam' in cc:
                    localGrp = mc.ls(cc, o=True)[0]
        
        if not mc.objExists(localGrp):
            localGrp = mc.group(empty=True, name=localGrp)
            mc.parentConstraint(cam, localGrp)
            mc.setAttr(localGrp+'.overrideEnabled',1)
            mc.setAttr(localGrp+'.overrideDisplayType',2)
            mc.parent(localGrp, topGroup)
            
            mc.addAttr(localGrp, at='message', longName='ml_parentCam')
            mc.connectAttr(cam+'.message', localGrp+'.ml_parentCam')
            
        parentGrp = mc.ls(localGrp)[0]
    
    #group per object:
    group = list()
    points = list()
    
    for i,obj in enumerate(objs):
        sn = mc.ls(obj,shortNames=True)[0]
        name = sn.replace(':','_')
    
        points.append(list())
        groupName = 'ml_%s_arcGrp' % name
        if mc.objExists(groupName):
            mc.delete(groupName)
        
        group.append(mc.group(empty=True, name=groupName))
        
        group[i] = mc.parent(group[i],parentGrp)[0]
        mc.setAttr(group[i]+'.translate', 0,0,0)
        mc.setAttr(group[i]+'.rotate', 0,0,0)
    
    with utl.UndoChunk():
        with utl.IsolateViews():

            #helper locator
            loc = mc.spaceLocator()[0]
            mc.parent(loc,parentGrp)

            #frame loop:
            time = range(int(start),int(end+1))
            for t in time:
                mc.currentTime(t, edit=True)

                #object loop
                for i,obj in enumerate(objs):

                    objPnt = mc.xform(obj, query=True, worldSpace=True, rotatePivot=True)

                    if space=='camera':
                        camPnt = mc.xform(cam, query=True, worldSpace=True, rotatePivot=True)

                        objVec = euclid.Vector3(objPnt[0],objPnt[1],objPnt[2])
                        camVec = euclid.Vector3(camPnt[0],camPnt[1],camPnt[2])

                        vec = objVec-camVec
                        vec.normalize()
                        #multiply here to offset from camera
                        vec=vec*nearClipPlane*1.2
                        vec+=camVec

                        mc.xform(loc, worldSpace=True, translation=vec[:])

                        trans = mc.getAttr(loc+'.translate')
                        points[i].append(trans[0]) 

                    elif space=='world':
                        points[i].append(objPnt)

            mc.delete(loc)

            #create the curves and do paint effects
            mc.ResetTemplateBrush()
            brush = mc.getDefaultBrush()
            mc.setAttr(brush+'.screenspaceWidth',1)
            mc.setAttr(brush+'.distanceScaling',0)
            mc.setAttr(brush+'.brushWidth',0.005)

            for i,obj in enumerate(objs):

                #setup brush for path
                mc.setAttr(brush+'.screenspaceWidth',1)
                mc.setAttr(brush+'.distanceScaling',0)
                mc.setAttr(brush+'.brushWidth',0.003)

                #color
                for c in ('R','G','B'):
                    color = random.uniform(0.3,0.7)
                    mc.setAttr(brush+'.color1'+c,color)
                
                baseCurve = mc.curve(d=3,p=points[i])
                #fitBspline makes a curve that goes THROUGH the points, a more accurate path
                curve = mc.fitBspline(baseCurve, constructionHistory=False, tolerance=0.001)
                mc.delete(baseCurve)

                #paint fx
                mc.AttachBrushToCurves(curve)
                stroke = mc.ls(sl=True)[0]
                stroke = mc.parent(stroke,group[i])[0]

                mc.setAttr(stroke+'.overrideEnabled',1)
                mc.setAttr(stroke+'.overrideDisplayType',2)

                mc.setAttr(stroke+'.displayPercent',92)
                mc.setAttr(stroke+'.sampleDensity',0.5)
                mc.setAttr(stroke+'.inheritsTransform',0)
                mc.setAttr(stroke+'.translate',0,0,0)
                mc.setAttr(stroke+'.rotate',0,0,0)

                curve = mc.parent(curve,group[i])[0]
                mc.setAttr(curve+'.translate',0,0,0)
                mc.setAttr(curve+'.rotate',0,0,0)

                mc.hide(curve)

                #setup brush for tics
                if space=='camera':
                    mc.setAttr(brush+'.brushWidth',0.008)
                if space=='world':
                    mc.setAttr(brush+'.brushWidth',0.005)
                mc.setAttr(brush+'.color1G',0)
                mc.setAttr(brush+'.color1B',0)

                for t in range(len(points[i])):
                    frameCurve = None
                    if space=='camera':
                        vec = euclid.Vector3(points[i][t][0],points[i][t][1],points[i][t][2])
                        vec*=0.98
                        frameCurve = mc.curve(d=1,p=[points[i][t],vec[:]])

                    elif space=='world':
                        frameCurve = mc.circle(constructionHistory=False, radius=0.0001, sections=4)[0]
                        mc.setAttr(frameCurve+'.translate', points[i][t][0], points[i][t][1] ,points[i][t][2])
                        constraint = mc.tangentConstraint(curve, frameCurve, aimVector=(0,0,1), worldUpType='scene')
                        #mc.delete(constraint)

                    #check for keyframe
                    colorAttribute='color1G'
                    if mc.keyframe(obj, time=((t+start-0.5),(t+start+0.5)), query=True):
                        mc.setAttr(brush+'.color1R',1)
                    else:
                        mc.setAttr(brush+'.color1R',0)

                    mc.AttachBrushToCurves(curve)

                    stroke = mc.ls(sl=True)[0]
                    thisBrush = mc.listConnections(stroke+'.brush', destination=False)[0]

                    #setup keyframes for frame highlighting
                    mc.setKeyframe(thisBrush, attribute='color1G', value=0, time=(start+t-1, start+t+1))
                    mc.setKeyframe(thisBrush, attribute='color1G', value=1, time=(start+t,))

                    stroke = mc.parent(stroke,group[i])[0]

                    mc.hide(frameCurve)

                    mc.setAttr(stroke+'.displayPercent',92)
                    mc.setAttr(stroke+'.sampleDensity',0.5)

                    frameCurve = mc.parent(frameCurve,group[i])[0]

                    if space=='camera':
                        mc.setAttr(stroke+'.inheritsTransform',0)
                        mc.setAttr(stroke+'.pressureScale[1].pressureScale_Position', 1)
                        mc.setAttr(stroke+'.pressureScale[1].pressureScale_FloatValue', 0)
                        mc.setAttr(stroke+'.translate',0,0,0)
                        mc.setAttr(stroke+'.rotate',0,0,0)
                        mc.setAttr(frameCurve+'.translate',0,0,0)
                        mc.setAttr(frameCurve+'.rotate',0,0,0)

            mc.currentTime(origTime, edit=True)
            panel = mc.getPanel(withFocus=True)
            mc.modelEditor(panel, edit=True, strokes=True)
    
    mc.select(objs,replace=True)
Пример #56
0
def simpleBlast(startFrame, endFrame):
	
	src_dir = os.path.dirname(mc.file(q=True, sceneName=True))
	project = Project()
	playblast_element = project.get_checkout_element(src_dir)
	playblast_dept = None
	playblast_body_name = None
	playblast_dir = src_dir
	playblast_filename = "playblast.mov"
	if playblast_element is not None:
		playblast_dir = playblast_element.get_render_dir()
		playblast_filename = playblast_element.get_name()+".mov"
		playblast_dept = playblast_element.get_department()
		playblast_body_name = playblast_element.get_parent()
	name = os.path.join(playblast_dir, playblast_filename)
	
	currentPanel = mc.getPanel(wf=True)
	currentCamera = mc.modelEditor(currentPanel, q=True, camera=True)

	panelSwitch = []
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, nc=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, ns=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, pm=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, sds=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, pl=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, lt=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, ca=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, j=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, ikh=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, df=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, dy=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, fl=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, hs=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, fo=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, lc=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, dim=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, ha=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, pv=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, tx=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, str=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, gr=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, cv=True))
	panelSwitch.append(mc.modelEditor(currentPanel, q=True, hu=True))

	mel.eval("lookThroughModelPanel "+currentCamera+" "+currentPanel)
	mc.modelEditor(currentPanel, e=True, allObjects=0)
	mc.modelEditor(currentPanel, e=True, polymeshes=1)
	mc.modelEditor(currentPanel, e=True, nurbsSurfaces=0)
	mc.modelEditor(currentPanel, e=True, strokes=1)
	mc.modelEditor(currentPanel, e=True, cameras=0)

	playback_slider = mel.eval('$tmpVar=$gPlayBackSlider')
	soundfile = mc.timeControl(playback_slider, q=True, sound=True)
	print soundfile

	mc.playblast(st=startFrame, et=endFrame, sound=soundfile, fmt="qt", compression="jpeg", qlt=100, forceOverwrite=True, filename=name,
	width=1920, height=817, offScreen=True, percent=100, v=False)

	mel.eval("lookThroughModelPanel "+currentCamera+" "+currentPanel)
	mc.modelEditor(currentPanel, e=True, nc=panelSwitch[0])
	mc.modelEditor(currentPanel, e=True, ns=panelSwitch[1])
	mc.modelEditor(currentPanel, e=True, pm=panelSwitch[2])
	mc.modelEditor(currentPanel, e=True, sds=panelSwitch[3])
	mc.modelEditor(currentPanel, e=True, pl=panelSwitch[4])
	mc.modelEditor(currentPanel, e=True, lt=panelSwitch[5])
	mc.modelEditor(currentPanel, e=True, ca=panelSwitch[6])
	mc.modelEditor(currentPanel, e=True, j=panelSwitch[7])
	mc.modelEditor(currentPanel, e=True, ikh=panelSwitch[8])
	mc.modelEditor(currentPanel, e=True, df=panelSwitch[9])
	mc.modelEditor(currentPanel, e=True, dy=panelSwitch[10])
	mc.modelEditor(currentPanel, e=True, fl=panelSwitch[11])
	mc.modelEditor(currentPanel, e=True, hs=panelSwitch[12])
	mc.modelEditor(currentPanel, e=True, fo=panelSwitch[13])
	mc.modelEditor(currentPanel, e=True, lc=panelSwitch[14])
	mc.modelEditor(currentPanel, e=True, dim=panelSwitch[15])
	mc.modelEditor(currentPanel, e=True, ha=panelSwitch[16])
	mc.modelEditor(currentPanel, e=True, pv=panelSwitch[17])
	mc.modelEditor(currentPanel, e=True, tx=panelSwitch[18])
	mc.modelEditor(currentPanel, e=True, str=panelSwitch[19])
	mc.modelEditor(currentPanel, e=True, gr=panelSwitch[20])
	mc.modelEditor(currentPanel, e=True, cv=panelSwitch[21])
	mc.modelEditor(currentPanel, e=True, hu=panelSwitch[22])
    def showPanoramaWindow(self, argCamera):
        #tool`s second UI,this window uesed to be snaped
        #~ if cmds.window('MayaPanoramaPlayBlast', q=1, exists=1):
        #~ cmds.deleteUI('MayaPanoramaPlayBlast')

        if cmds.window('showPanoramaWindow', q=1, exists=1):
            cmds.deleteUI('showPanoramaWindow')
        self.window = cmds.window('showPanoramaWindow',
                                  widthHeight=(1536, 1024),
                                  sizeable=False,
                                  topLeftCorner=(0, 0),
                                  titleBar=False)

        form = cmds.formLayout(width=1536, height=1024)
        editor1 = cmds.modelEditor()
        editor2 = cmds.modelEditor()
        editor3 = cmds.modelEditor()
        editor4 = cmds.modelEditor()
        editor5 = cmds.modelEditor()
        editor6 = cmds.modelEditor()
        self.modelEditor(editor1)
        self.modelEditor(editor2)
        self.modelEditor(editor3)
        self.modelEditor(editor4)
        self.modelEditor(editor5)
        self.modelEditor(editor6)

        #change backgoundcolor
        cmds.displayPref(displayGradient=0)

        cmds.formLayout(form,
                        edit=True,
                        attachForm=[(editor1, 'top', 0),
                                    (editor1, 'bottom', 512),
                                    (editor1, 'left', 0),
                                    (editor1, 'right', 1024),
                                    (editor2, 'top', 0),
                                    (editor2, 'bottom', 512),
                                    (editor2, 'right', 512),
                                    (editor2, 'left', 512),
                                    (editor3, 'top', 0),
                                    (editor3, 'bottom', 512),
                                    (editor3, 'right', 0),
                                    (editor3, 'left', 1024),
                                    (editor4, 'top', 512),
                                    (editor4, 'bottom', 0),
                                    (editor4, 'left', 0),
                                    (editor4, 'right', 1024),
                                    (editor5, 'top', 512),
                                    (editor5, 'bottom', 0),
                                    (editor5, 'right', 512),
                                    (editor5, 'left', 512),
                                    (editor6, 'top', 512),
                                    (editor6, 'bottom', 0),
                                    (editor6, 'right', 0),
                                    (editor6, 'left', 1024)],
                        attachControl=[(editor1, 'right', 0, editor2),
                                       (editor2, 'right', 0, editor3),
                                       (editor4, 'right', 0, editor5),
                                       (editor5, 'right', 0, editor6),
                                       (editor1, 'bottom', 0, editor4),
                                       (editor2, 'bottom', 0, editor5),
                                       (editor3, 'bottom', 0, editor6)])

        cameraShape = self.camera
        if cmds.objectType(self.camera, isType='transform'):
            cameraShape = cmds.listRelatives(self.camera, children=True)[0]
        nearClipPlane = cmds.getAttr(cameraShape + '.nearClipPlane')
        farClipPlane = cmds.getAttr(cameraShape + '.farClipPlane')
        cameraFront = cmds.camera(centerOfInterest=2.450351)
        cmds.setAttr(cameraFront[0] + '.nearClipPlane', nearClipPlane)
        cmds.setAttr(cameraFront[0] + '.farClipPlane', farClipPlane)
        cmds.hide(cameraFront)
        cameraLeft = cmds.camera(centerOfInterest=2.450351,
                                 rotation=(0, 90, 0))
        cmds.setAttr(cameraLeft[0] + '.nearClipPlane', nearClipPlane)
        cmds.setAttr(cameraLeft[0] + '.farClipPlane', farClipPlane)
        cmds.hide(cameraLeft)
        cameraBack = cmds.camera(centerOfInterest=2.450351,
                                 rotation=(0, 180, 0))
        cmds.setAttr(cameraBack[0] + '.nearClipPlane', nearClipPlane)
        cmds.setAttr(cameraBack[0] + '.farClipPlane', farClipPlane)
        cmds.hide(cameraBack)
        cameraRight = cmds.camera(centerOfInterest=2.450351,
                                  rotation=(0, 270, 0))
        cmds.setAttr(cameraRight[0] + '.nearClipPlane', nearClipPlane)
        cmds.setAttr(cameraRight[0] + '.farClipPlane', farClipPlane)
        cmds.hide(cameraRight)
        cameraUp = cmds.camera(centerOfInterest=2.450351, rotation=(90, 0, 0))
        cmds.setAttr(cameraUp[0] + '.nearClipPlane', nearClipPlane)
        cmds.setAttr(cameraUp[0] + '.farClipPlane', farClipPlane)
        cmds.hide(cameraUp)
        cameraDown = cmds.camera(centerOfInterest=2.450351,
                                 rotation=(270, 0, 0))
        cmds.setAttr(cameraDown[0] + '.nearClipPlane', nearClipPlane)
        cmds.setAttr(cameraDown[0] + '.farClipPlane', farClipPlane)
        cmds.hide(cameraDown)

        #group = cmds.group(camera2,camera3,camera4,camera5,camera6,name='cameraFull')
        #cmds.parentConstraint(camera1,group,maintainOffset=False)
        cmds.parent(cameraFront[0], argCamera, relative=True)
        cmds.parent(cameraLeft[0], argCamera, relative=True)
        cmds.parent(cameraBack[0], argCamera, relative=True)
        cmds.parent(cameraRight[0], argCamera, relative=True)
        cmds.parent(cameraUp[0], argCamera, relative=True)
        cmds.parent(cameraDown[0], argCamera, relative=True)

        cameraList = [
            cameraFront[1], cameraRight[1], cameraBack[1], cameraLeft[1],
            cameraUp[1], cameraDown[1]
        ]
        self.tmpCameraList = cameraList
        self.argCamera = argCamera
        for item in cameraList:
            cmds.setAttr('%s.horizontalFilmAperture' % item, 1)
            cmds.setAttr('%s.verticalFilmAperture' % item, 1)
            cmds.setAttr('%s.filmFit' % item, 3)
            cmds.setAttr('%s.focalLength' % item, 12.700)

        #~ cmds.modelEditor( editor1, edit=True, camera=cameraFront[0] )
        #~ cmds.modelEditor( editor2, edit=True, camera=cameraLeft[0] )
        #~ cmds.modelEditor( editor3, edit=True, camera=cameraBack[0] )
        #~ cmds.modelEditor( editor4, edit=True, camera=cameraRight[0] )
        #~ cmds.modelEditor( editor5, edit=True, camera=cameraUp[0] )
        #~ cmds.modelEditor( editor6, edit=True, camera=cameraDown[0] )
        cmds.modelEditor(editor1, edit=True, camera=cameraBack[0])
        cmds.modelEditor(editor2, edit=True, camera=cameraUp[0])
        cmds.modelEditor(editor3, edit=True, camera=cameraDown[0])
        cmds.modelEditor(editor4, edit=True, camera=cameraLeft[0])
        cmds.modelEditor(editor5, edit=True, camera=cameraFront[0])
        cmds.modelEditor(editor6, edit=True, camera=cameraRight[0])

        cmds.showWindow(self.window)
        cmds.window('showPanoramaWindow', topLeftCorner=(0, 0), edit=True)
    def screenSnap(self):
        self.garbages = []
        minTime = cmds.playbackOptions(q=True, min=True)
        maxTime = cmds.playbackOptions(q=True, max=True)
        self.minTime = minTime
        self.maxTime = maxTime
        #~ cmds.select(cl=1)
        cmds.select(cmds.ls(self.lightsGrp, dag=1, leaf=1))
        mayaWindowParent = shiboken.wrapInstance(
            long(omui.MQtUtil.findWindow(self.window)), QtGui.QWidget)
        mayaWindowParent.setWindowFlags(mayaWindowParent.windowFlags()
                                        | QtCore.Qt.WindowStaysOnTopHint)
        for i in range(int(minTime), int(maxTime) + 1):
            print 'frame:', i
            cmds.currentTime(i, edit=True)
            x1 = 7
            y1 = 7
            x2 = mayaWindowParent.width()
            y2 = mayaWindowParent.height()
            cmds.showWindow(self.window)
            self.originalPixmap = QtGui.QPixmap.grabWindow(
                QtGui.QApplication.desktop().winId(), x1, y1, x2, y2)
            if os.path.isdir(self.imagePath + '/tmp/'):
                pass
            else:
                os.makedirs(self.imagePath + '/tmp/')
            self.filePath = self.imagePath + '/tmp/' + self.imageName + '_%0.4d' % (
                i - int(minTime) + 1) + '.png'
            self.originalPixmap.save(self.filePath, 'png')
            latLongImgPath = os.path.dirname(
                self.filePath) + '/latlong_' + os.path.basename(self.filePath)
            command = 'start "" "D:/Projects/_mili_common_push/pyUpload/panoViewer.exe" -cubeToLatlong "%s" "%s"' % (
                latLongImgPath, self.filePath)
            os.popen(command)
            self.garbages += [self.filePath, latLongImgPath]

        cmds.delete(self.lightsGrp)
        cmds.delete(self.tmpCameraList)

        #remove this window to show recording window
        if cmds.window('showPanoramaWindow', q=1, exists=1):
            cmds.deleteUI('showPanoramaWindow')

        self.soundCmdStr = ''
        sound = mel.eval(
            'global string $gPlayBackSlider; $hgPlayBlastTmp =`timeControl -q -s $gPlayBackSlider`;'
        )
        if sound != '':
            tmpWindow = cmds.window('PanormaPlayBlastRecordingWindow',
                                    w=300,
                                    h=5,
                                    title='Recording Sound')
            cmds.rowColumnLayout(nc=1)
            cmds.select(cl=1)
            cmds.modelEditor(viewSelected=1)
            cmds.showWindow(tmpWindow)

            soundVideo = cmds.playblast(
                format='avi',
                clearCache=1,
                viewer=0,
                showOrnaments=1,
                startTime=self.minTime,
                endTime=self.maxTime,
                filename=self.imagePath + '/tmp/sound_' + self.imageName +
                '%i.avi' % time.time(),
                percent=100,
                widthHeight=[2, 2],
                quality=100,
                #~ compression=codec,
                sound=sound,
            )
            self.garbages += [soundVideo]

            cmds.deleteUI(tmpWindow)
            self.soundCmdStr += '-i "%s" -c:a mp3' % soundVideo
Пример #59
0
 def grid(self):
     viz = cmds.modelEditor(self.panel, query=True, grid=True)
     cmds.modelEditor(self.panel, grid=True, edit=not viz)
Пример #60
0
 def nurbsSurfaces(self):
     viz = cmds.modelEditor(self.panel, query=True, nurbsSurfaces=True)
     cmds.modelEditor(self.panel, edit=True, nurbsSurfaces=not viz)