def apply_viewport_preset(k): from . import viewport panel = cmds.getPanel(withFocus=True) if not cmds.modelPanel(panel, query=True, exists=True): return editor = cmds.modelPanel(panel, query=True, modelEditor=True) cmds.modelEditor(editor, edit=True, **viewport.presets[k])
def MyWindows_model_zwz(self, myWinName, myCamera): myPaneLayoutName = '%s_p' % myWinName myModelPanelName = '%s_m' % myWinName pattern1 = re.compile('^(\w+)([DU]{1})$') pattern2 = re.compile('^(\w+)([LR]{1})$') _width = self.myRenderwidth _Height = self.myRenderheight if self.Preset: if pattern1.match(myCamera): _width = self.myRenderwidth _Height = self.myRenderheight / 2 elif pattern2.match(myCamera): _width = self.myRenderwidth / 2 _Height = self.myRenderheight else: _width = self.myRenderwidth _Height = self.myRenderheight myCameraShortName = myCamera.split(":")[-1] myCameraShortName = myCameraShortName.replace('|', '') mc.window(myWinName, t=myCameraShortName, w=10, h=10, s=True, rtf=True) mc.paneLayout(myPaneLayoutName, w=int(_width) + 4, h=int(_Height) + 5, configuration='single', aft=0, st=1) mc.modelPanel(myModelPanelName, camera=myCamera, mbv=False) mc.showWindow(myWinName) # mc.paneLayout(myPaneLayoutName, e=True, w=self.myRenderwidth+4, h=self.myRenderheight+5) self.myAllWindows.append(myWinName) self.myAllModePlanes.append(myModelPanelName) return myWinName
def setUp(self): mayaSceneFile = '%s.ma' % self._testName mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile) cmds.file(mayaSceneFullPath, open=True, force=True) # Create a new custom viewport. self._window = cmds.window(widthHeight=(500, 400)) cmds.paneLayout() self._panel = cmds.modelPanel() cmds.modelPanel(self._panel, edit=True, camera='persp') cmds.modelEditor(cmds.modelPanel(self._panel, q=True, modelEditor=True), edit=True, displayAppearance='smoothShaded', rnm='vp2Renderer') cmds.showWindow(self._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. self._view = OMUI.M3dView() OMUI.M3dView.getM3dViewFromModelPanel(self._panel, self._view) self._viewWidget = wrapInstance(long(self._view.widget()), QWidget)
def HUDInterface(self): SelectedTab = cmds.tabLayout( "TabLayout", query = True, st = True) #Get the persp panel perspPanel = cmds.getPanel( withLabel='Persp View') #change the view to the camera cmds.modelPanel( perspPanel, edit = True, camera = "persp") #When the Project tab is clicked if SelectedTab == "CMProjectLayout": cmds.hudButton("SnapButton", edit = True , vis = False) self.TurntableHelper(False) #When Image tab is clicked elif SelectedTab == "SnapShotTabLayout": cmds.hudButton("SnapButton", edit = True, rc = self.functions[0] , label = "Snap Image", vis = True) self.TurntableHelper(False) #When the turntable tab is clicked elif SelectedTab == "TurntableCounterLayout": cmds.hudButton("SnapButton", edit = True , rc = self.functions[1], label = "Create Turntable", vis = True) self.TurntableHelper(True) #When the Renderer tab is clicked elif SelectedTab == "BatchRendererCounterLayout": cmds.hudButton("SnapButton", edit = True , vis = False) self.TurntableHelper(False) #cmds.text("BatchRendererCounter", edit = True, label = "Image to render = " + str(BatchRendererFile.BatchRendererClass.ChangeCounter()))
def mhSaveView(viewToSave='active'): if viewToSave == 'active': activePanel = cmds.getPanel(withFocus=True) if cmds.modelPanel(activePanel, exists=True): viewCam = cmds.modelPanel(activePanel, query=True, camera=True) else: cmds.error( 'Active panel %s is not a modelPanel: can not save view.' % activePanel) else: viewCam = viewToSave if cmds.objExists(viewCam) == False: cmds.error('Can not find camera %s to save view.' % viewCam) attrNames = [ 'translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ' ] camAttrs = {} for attr in attrNames: thisAttr = '%s.%s' % (activeCam, attr) camAttrs[thisAttr] = cmds.getAttr(thisAttr) try: with open(attrFile, 'w') as fp: json.dump(camAttrs, fp) fp.close() except IOError: cmds.error('Could not open file %s for writing.' % attrFile)
def _ingest_check_capture(self, force=False): """Make sure this file has a corresponding psyop capture. Args: force (bool): lose unsaved changes without confirmation """ _work = self.to_psy_work() # Build capture if not self.has_capture(): print 'CAPTURING', _work.path _work.load(lazy=True) _cam = self.scene_get_cam() print ' - CAM', _cam assert _cam cmds.modelPanel( ui.get_active_model_panel(), edit=True, camera=_cam) tk2.capture_scene(force=True) # Submit version assert self.has_capture() _cap = _work.find_output_file( output_type='capture', extension='jpg', format_='jpg') if ( not self.has_capture_sg_version() and not _cap.cache_read('submitted transgen')): _cap.submit_sg_version() assert _cap.cache_read('submitted transgen')
def modView(): MyLabel = 'My Panel' cmds.frameLayout( lv=0 ) mPanel = cmds.modelPanel() modelPanel = cmds.modelPanel( mPanel, l=MyLabel, rp=oPanel ) '''
def tearoff(self, cam): """지정한 카메라의 패널을 분리하여 주는 메소드""" win = self._get_window_name_by_cam(cam) modelpanel = self._get_panel_name_by_cam(cam) # 패널용 윈도우가 이미 있을 경우 삭제한다. if cmds.window(win, exists=True): cmds.deleteUI(win, window=True) # 지정한 카메라의 모든 모델패널을 삭제한다. if cmds.modelPanel(modelpanel, exists=True): moon.modelpanel.delete(modelpanel) # 새로운 패널용 윈도우 생성 cmds.window( win, sizeable=True, title='MV Camera View Manager (Separated) :: {0}'.format(cam)) cmds.paneLayout() # 새로운 모델 패널 생성 cmds.modelPanel(modelpanel, label=modelpanel, camera=cam, menuBarVisible=True) # 생성한 모델패널의 기본적인 패널 뷰 속성을 꾸며준다. self.set_modeleditor_nice(modelpanel) # 윈도우의 크기는 기본적으로 800, 600으로 한다. cmds.window(win, edit=True, width=800, height=600) cmds.showWindow(win)
def tearOffCam(): winWidth = 640 winHeight = 480 rubyCam = 'Environment:Cam' rubyPlane = 'imagePlaneShape1' if rubyPlane: winWidth = cmds.getAttr(rubyPlane + '.coverageX') winHeight = cmds.getAttr(rubyPlane + '.coverageY') winRatio = (winWidth*1.0)/winHeight if winHeight > 1300: print 'height condition winRatio: ', winRatio winHeight = 1300 winWidth = winHeight*winRatio elif winWidth > 2000: print 'width condition winRatio: ', winRatio winWidth = 2000 winHeight = winWidth/winRatio rubyWindow = cmds.window(title="Ruby Cam", widthHeight=[winWidth,winHeight]) cmds.paneLayout() rubyPanel = cmds.modelPanel(camera=rubyCam) rubyModelEditor = cmds.modelPanel(rubyPanel, q=True, modelEditor=True) cmds.modelEditor(rubyModelEditor, edit=True, displayAppearance='smoothShaded', displayTextures=True, nurbsCurves=False, joints=False, wireframeOnShaded=False, locators=False) cmds.showWindow(rubyWindow)
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 '
def create_tearoff_viewport(camera, title=None, size=None, model_editor_kwargs=None, position=None): tearoff_window = mc.window(title=title) _model_editor_kwargs = model_editor_kwargs or dict() model_editor_kwargs = DEFAULT_MODEL_EDITOR_KWARGS.copy() model_editor_kwargs.update(_model_editor_kwargs) model_editor_kwargs['camera'] = camera if size is None: try: w, h = get_screen_size() size = w * .6, h * .6 except BaseException: size = [1280, 720] mc.window(tearoff_window, edit=True, widthHeight=size) if position is None: position = [w / 10, h / 10] mc.window(tearoff_window, edit=True, topLeftCorner=position) mc.paneLayout() panel = mc.modelPanel() mc.timePort(height=30, snap=True) mc.showWindow(tearoff_window) editor = mc.modelPanel(panel, query=True, modelEditor=True) mc.modelEditor(editor, edit=True, **model_editor_kwargs) mc.refresh() mc.modelEditor(editor, edit=True, activeView=True) return editor, panel, tearoff_window
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) # 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)
def thumbnailFromPlayBlast(filepath, width, height, modelPanel=None): ''' Generate a ThumbNail of the screen Note: 'cf' flag is broken in 2012 :param filepath: path to Thumbnail :param width: width of capture :param height: height of capture :param modePanel: modelPanel to grab the image from, default=None, works it out internally ''' filepath = os.path.splitext(filepath)[0] filename = os.path.basename(filepath) filedir = os.path.dirname(filepath) # get modelPanel and camera if not modelPanel or not cmds.modelPanel(modelPanel, exists=True): modelPanel = cmds.playblast(activeEditor=True).split('|')[-1] cam = cmds.modelPanel(modelPanel, q=True, camera=True) if not cmds.nodeType(cam) == 'camera': cam = cmds.listRelatives(cam)[0] storedformat = cmds.getAttr('defaultRenderGlobals.imageFormat') storedResolutionGate = cmds.getAttr('%s.filmFit' % cam) cmds.setAttr('defaultRenderGlobals.imageFormat', 20) cmds.setAttr('%s.filmFit' % cam, 2) # set to Vertical so we don't get so much overscan cmds.playblast( frame=cmds.currentTime(q=True), # startTime=cmds.currentTime(q=True), # endTime=cmds.currentTime(q=True), format="image", filename=filepath, width=width, height=height, percent=100, quality=90, forceOverwrite=True, framePadding=0, showOrnaments=False, compression="BMP", viewer=False) cmds.setAttr('defaultRenderGlobals.imageFormat', storedformat) cmds.setAttr('%s.filmFit' % cam, storedResolutionGate) # Why do this rename? In Maya2012 the 'cf' flag fails which means you have to use # the 'f' flag and that adds framePadding, crap I know! So we strip it and rename # the file after it's made. try: newfile = [ f for f in os.listdir(filedir) if f.split('.bmp')[0].split('.')[0] == filename and '.pose' not in f ] log.debug('Original Playblast file : %s' % newfile) os.rename(os.path.join(filedir, newfile[0]), '%s.bmp' % filepath) log.debug('Thumbnail Renamed : %s' % ('%s.bmp' % filepath)) return '%s.bmp' % filepath except: pass
def mvgDeleteWindow(): import maya.cmds as cmds if cmds.window('mayaMVG', exists=True): cmds.deleteUI('mayaMVG', window=True) if cmds.modelPanel('mvgLPanel', q=True, ex=True): cmds.deleteUI('mvgLPanel', pnl=True) if cmds.modelPanel('mvgRPanel', q=True, ex=True): cmds.deleteUI('mvgRPanel', pnl=True)
def SetActiveCamera(Camera): print "Setting the active camera" #Get the persp panel perspPanel = cmds.getPanel( withLabel='Persp View') #Get the active camera in the panel cmds.modelPanel( perspPanel, edit = True, camera = Camera) print Camera + " is set as the active camera in the perspView"
def __camera__(cls): panel = cmds.playblast(activeEditor=True).split("|")[-1] camera = cmds.modelPanel(panel, q=True, camera=True) cameraShape = cmds.listRelatives(camera, shapes=True) if cameraShape: camera = cameraShape[0] focalLength = cmds.getAttr(camera + ".focalLength") return "%s/%.1f" % (cmds.modelPanel(panel, q=True, camera=True), focalLength)
def AddTwoGroup(self): tmpCam = self.findCamera('upCam') mc.modelPanel('U_panel', camera=tmpCam, mbv=False, l='U', p='pane1') self.DisplayPoly('U_panel') tmpCam = self.findCamera('downCam') mc.modelPanel('D_panel', camera=tmpCam, mbv=False, l='D', p='pane2') self.DisplayPoly('D_panel')
def guardaImagen(nombreDePose=""): global nombreDePoseGlobal nombreDePoseGlobal = nombreDePose mc.evalDeferred('resolucion=150') nombrePanel = mc.modelPanel(tearOff=True) nombreEditor = mc.modelPanel(nombrePanel, q=1, modelEditor=1) mc.modelEditor( nombreEditor, e=1, activeOnly=0, displayAppearance="smoothShaded", polymeshes=1, wos=0, nurbsSurfaces=1, planes=1, lights=0, cameras=0, controlVertices=0, grid=0, hulls=0, joints=0, ikHandles=0, nurbsCurves=0, deformers=0, dynamics=1, fluids=0, hairSystems=0, follicles=0, nCloths=1, nParticles=1, nRigids=1, dynamicConstraints=0, locators=0, manipulators=0, dimensions=0, handles=0, pivots=1, textures=0, strokes=0, pluginShapes=1, queryPluginObjects=1, ) mc.modelEditor(nombreEditor, e=1, activeView=1, p='lay_1', activeOnly=0, displayAppearance="smoothShaded", polymeshes=1, wos=0) mc.evalDeferred('view=apiUI.M3dView.active3dView()') mc.evalDeferred('imagen=api.MImage()') mc.evalDeferred('view.readColorBuffer (imagen,True)') mc.evalDeferred('imagen.resize (resolucion,resolucion,1)') mc.evalDeferred( 'imagen.writeToFile("D:/PH_SCRIPTS/ICONS/POSES/"+nombreDePoseGlobal+".png","png")' )
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) #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)[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']: self.dataStore['cameraTransforms'][cam] = [ cmds.getAttr('%s.translate' % cam), cmds.getAttr('%s.rotate' % cam), cmds.getAttr('%s.scale' % 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)
def AddSevenGroup_2(self): tmpCam = self.findCamera('test_CamL_D') if not tmpCam: tmpCam = self.findCamera('test_CamL_1_D') if not tmpCam: tmpCam = self.findCamera('CamL_D') if not tmpCam: tmpCam = self.findCamera('CamL_1_D') mc.modelPanel('L_panel', camera=tmpCam, mbv=False, l='L', p='pane4') self.DisplayPoly('L_panel')
def CreateSnap(): #Create a snapshot from the signature image SubdivisionTextClass.ImagePath = cmds.getAttr("CMSettings.ProjectPath") + "/temp/" + cmds.getAttr("CMSettings.ModelName") + "_Subdivision_Temp_0" + ".png" cmds.editRenderLayerGlobals( currentRenderLayer = "Subdivision_0") ScreenCapture.ScreenCapture(SubdivisionTextClass.ImagePath, [740,400]) cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer") #Return the camera to whatever it was cmds.modelPanel( perspPanel, edit = True, camera = oldCamera)
def get_camera(): sel = mc.ls(selection=True) cam_shot = mc.sequenceManager(currentShot=True, query=True) cam_list = [] cam_panel = [] if sel: for c in sel: if mc.listRelatives(c, type='camera'): cam_list.append(c) elif mc.listRelatives(c, type='nurbsCurve') and mc.listRelatives( c, allDescendents=True, type='camera'): cam_shape = mc.listRelatives(c, allDescendents=True, type='camera')[0] parent_node = mc.listRelatives(cam_shape, parent=True)[0] cam_list.append(parent_node) if cam_list: cam = cam_list[0] elif not cam_list and cam_shot: if not mc.listRelatives(mc.shot( cam_shot, currentCamera=True, query=True), shapes=True): cam = mc.listRelatives(mc.shot(cam_shot, currentCamera=True, query=True), parent=True)[0] else: cam = mc.shot(cam_shot, currentCamera=True, query=True) else: all_cam = mc.ls(type='camera') cam = mc.listRelatives(all_cam[1], parent=True)[0] for p in mc.getPanel(type="modelPanel"): if mc.modelPanel(p, query=True, camera=True) == cam: cam_panel = p elif mc.modelPanel(p, query=True, camera=True) == mc.listRelatives(cam, shapes=True)[0]: cam_panel = p else: continue if not cam_panel: mc.warning('No Panel with this camera. Put one and refresh') camera = Camera(cam, mc.getAttr(cam + '.focalLength'), mc.getAttr(cam + '.nearClipPlane'), cam_panel) return camera
def w09_playblast_cmd(self, *args): #Clamp resolution to view port import maya.OpenMayaUI as omui curView = omui.M3dView.active3dView() portWidth = curView.portWidth() portHeight = curView.portHeight() resWidth = cmds.getAttr('defaultResolution.width') resHeight = cmds.getAttr('defaultResolution.height') resAspect = float(resWidth) / resHeight if resWidth > portWidth or resHeight > portHeight: if portWidth < portHeight: resWidth, resHeight = portWdith, int(portWidth / resAspect) else: #protHeight<portWidth resWidth, resHeight = int(portHeight * resAspect), portHeight #Get model panel for mPanel in cmds.getPanel(vis=True): if cmds.modelPanel(mPanel, exists=True): break else: raise IOError('No found modelPanel!') sceneName = cmds.file(q=True, sn=True, shortName=True).split('.')[0] for ca in cmds.textScrollList('w09_uiCameras', q=True, si=True): camShortName = ca.split('|')[-1].replace(":", '_') #Set Model panel camera cameraShape = cmds.listRelatives(ca, shapes=True, typ='camera', f=True)[0] cmds.modelPanel(mPanel, e=True, camera=cameraShape) cmds.camera(cameraShape, e=True, displayResolution=False, displayGateMask=False, displayFilmGate=False) filenameV = 'playblast/%s/%s/%s' % (sceneName, camShortName, camShortName) cmds.playblast(format='iff', filename=filenameV, sequenceTime=False, viewer=False, clearCache=True, showOrnaments=True, fp=4, percent=100, compression="jpg", quality=100, wh=[resWidth, resHeight]) imDir = cmds.workspace(q=True, rd=True) imDir = os.path.join(imDir, 'images/playblast/%s' % (sceneName)) if os.path.exists(imDir): os.startfile(imDir)
def _MakeModelPanel(self): window = cmds.window(widthHeight=(400, 400)) cmds.paneLayout() panel = cmds.modelPanel() cmds.modelPanel(panel, edit=True, camera='top') cmds.modelEditor(cmds.modelPanel(panel, q=True, modelEditor=True), edit=True, displayAppearance='smoothShaded', rnm='vp2Renderer') cmds.showWindow(window) return panel
def _start_streaming_ui(self): self._orig_active_view = self._get_active_view() cmds.deleteUI(self._ui_view, control=True) self._ui_view = cmds.modelPanel(copy=self._orig_active_view, menuBarVisible=False, parent=self._ui_layout) bar_layout = cmds.modelPanel(self._ui_view, q=True, barLayout=True) cmds.frameLayout(bar_layout, edit=True, collapse=True) self._update_ui_layout() cmds.control(self._ui_view, edit=True, width=self._STREAM_WIDTH, height=self._STREAM_HEIGHT) cmds.text(self._ui_tx_help, edit=True, label='Client App connected | Streaming viewport...') cmds.modelEditor(self._ui_view, e=True, activeView=True) self._hide_inactive_views() self._look_through_current_camera()
def ChangeCamera(): cmds.modelPanel( perspPanel, edit = True, camera = "persp") SubdivisionTextClass.Camera = "persp" #change the view to the camera i = 0 while cmds.objExists("shot_" + str(i)): if cmds.getAttr("shot_" + str(i) + ".CMSignature"): SubdivisionTextClass.Camera = "shot_" + str(i) cmds.modelPanel( perspPanel, edit = True, camera = "shot_" + str(i)) i = i + 1
def testObjectPosition(self): """ Tests that an object created interactively is positioned correctly on the live surface. """ # 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_1') # Enter interactive creation context. cmds.setToolTo('CreatePolyTorusCtx') # Click in the center of the viewport widget. QTest.mouseClick(viewWidget, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, viewWidget.rect().center()) # Find the torus (it should be called pTorus1). self.assertTrue(cmds.ls('pTorus1')) # Check the torus's transform. # The Block_1 is originally 1 unit deep and centered at the origin, so # its original top plane is aligned at z=0.5. # It is scaled 5x, which makes the top plane aligned at z=2.5. # Then it is translated along z by 4.0, so its top plane is finally # aligned at z=6.5. translate = cmds.xform('pTorus1', q=True, t=True) self.assertAlmostEqual(translate[2], 6.5, places=3)
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) self.dataStore['playLoop'] = cmds.playbackOptions(query=True, loop=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)
def MyWindows_model_zwz(self, myWinName, myCamera): myPaneLayoutName = '%s_p' % myWinName myModelPanelName = '%s_m' % myWinName myCameraShortName = myCamera.split(":")[-1] myCameraShortName = myCameraShortName.replace('|','') mc.window(myWinName, t=myCameraShortName, w=10, h=10, s=True, rtf=True) mc.paneLayout(myPaneLayoutName, w=int(self.myRenderwidth)+4, h=int(self.myRenderheight)+5, configuration='single', aft=0, st=1) mc.modelPanel(myModelPanelName, camera=myCamera, mbv=False) mc.showWindow(myWinName) # mc.paneLayout(myPaneLayoutName, e=True, w=self.myRenderwidth+4, h=self.myRenderheight+5) self.myAllWindows.append(myWinName) self.myAllModePlanes.append(myModelPanelName) return myWinName
def __init__(self): global NEWNAMEtxtfld, CONTROLLERtxtscr, CACHEsrvr,IMAGEimg, SCRSHTPANELvar, SCRSHTPANEL2var if cmds.window('mncRigLibrary', exists=True):cmds.deleteUI('mncRigLibrary', wnd=True) cmds.window('mncRigLibrary',t='Controller Library',s=False) cmas=cmds.columnLayout(adj=True) tabs=cmds.tabLayout() child1=cmds.columnLayout(adj=True) f1=cmds.frameLayout(l='Export Controller',p=child1,w=300) cmds.columnLayout(adj=True) cmds.text(l='Controller New Name: ') NEWNAMEtxtfld=cmds.textField() cmds.separator() cmds.text(l='Screen Shot Frame:') cmds.paneLayout(w=300,h=300) SCRSHTPANELvar=cmds.modelPanel(cam='persp',mbv=False) cmds.columnLayout(adj=True,p=child1) cmds.separator() cmds.text(l='') cmds.separator() cmds.button(l='REGISTER CONTROLLER' ,h=40, bgc=[1.0,0.643835616566,0.0],c=self.REGISTERfn) cmds.setParent('..') cmds.setParent('..') child2=cmds.columnLayout(adj=True) f2=cmds.frameLayout(l='Import Update Controller',p=child2) cmds.columnLayout(adj=True) cmds.text(l='Select Controller: ') cmds.button(l='<<CONTROLLER PREVIEW>>',h=20, bgc=[1.0,0.643835616566,0.0],c=self.PREVIEWfn) CONTROLLERtxtscr=cmds.textScrollList(h=100) cmds.button(l='IMPORT CONTROLLER' , bgc=[1.0,0.643835616566,0.0],c=self.IMPORTCONTROLLERfn) cmds.separator() cmds.text(l='Screen Shot Frame: ') cmds.paneLayout(w=300,h=300) SCRSHTPANEL2var=cmds.modelPanel(cam='persp',mbv=False) cmds.button(l='UPDATE CONTROLLER' , bgc=[1.0,0.643835616566,0.0],c=self.UPDATECONTROLLERfn) cmds.separator(p=cmas) cmds.button(l='REFRESH',c=self.REFRESHfn,p=cmas) cmds.setParent('..') cmds.setParent('..') cmds.tabLayout( tabs, edit=True, tabLabel=((child1, 'REGISTER CONTROLLER'), (child2, 'IMPORT CONTROLLER')) ) cmds.showWindow() CTRLlis=os.listdir(CACHEsrvr+'library/') for chk in CTRLlis: if chk.endswith('.png')==False: cmds.textScrollList(CONTROLLERtxtscr,e=True,append=chk[:-3]) return
def _independent_panel(width, height, off_screen=False): """Create capture-window context without decorations Arguments: width (int): Width of panel height (int): Height of panel Example: >>> with _independent_panel(800, 600): ... cmds.capture() """ # center panel on screen screen_width, screen_height = _get_screen_size() topLeft = [ int((screen_height - height) / 2.0), int((screen_width - width) / 2.0) ] window = cmds.window(width=width, height=height, topLeftCorner=topLeft, menuBarVisible=False, titleBar=False, visible=not off_screen) cmds.paneLayout() panel = cmds.modelPanel(menuBarVisible=False, label='CapturePanel') # Hide icons under panel menus bar_layout = cmds.modelPanel(panel, q=True, barLayout=True) cmds.frameLayout(bar_layout, edit=True, collapse=True) if not off_screen: cmds.showWindow(window) # Set the modelEditor of the modelPanel as the active view so it takes # the playback focus. Does seem redundant with the `refresh` added in. editor = cmds.modelPanel(panel, query=True, modelEditor=True) cmds.modelEditor(editor, edit=True, activeView=True) # Force a draw refresh of Maya so it keeps focus on the new panel # This focus is required to force preview playback in the independent panel cmds.refresh(force=True) try: yield panel finally: # Delete the panel to fix memory leak (about 5 mb per capture) cmds.deleteUI(panel, panel=True) cmds.deleteUI(window)
def _GetViewportWidget(self, cameraName, rendererName): self._testWindow = cmds.window('SelectionTestWindow', widthHeight=(self._viewWindowWidth, self._viewWindowHeight)) cmds.paneLayout() testModelPanel = cmds.modelPanel(menuBarVisible=False) testModelEditor = cmds.modelPanel(testModelPanel, q=True, modelEditor=True) cmds.modelEditor(testModelEditor, edit=True, camera=cameraName, displayAppearance='smoothShaded', rendererName=rendererName) cmds.showWindow(self._testWindow) m3dView = OMUI.M3dView.getM3dViewFromModelPanel(testModelPanel) viewWidget = wrapInstance(long(m3dView.widget()), QWidget) return viewWidget
def _independent_panel(width, height, off_screen=False): """Create capture-window context without decorations Arguments: width (int): Width of panel height (int): Height of panel Example: >>> with _independent_panel(800, 600): ... cmds.capture() """ # center panel on screen screen_width, screen_height = _get_screen_size() topLeft = [int((screen_height-height)/2.0), int((screen_width-width)/2.0)] window = cmds.window(width=width, height=height, topLeftCorner=topLeft, menuBarVisible=False, titleBar=False, visible=not off_screen) cmds.paneLayout() panel = cmds.modelPanel(menuBarVisible=False, label='CapturePanel') # Hide icons under panel menus bar_layout = cmds.modelPanel(panel, q=True, barLayout=True) cmds.frameLayout(bar_layout, edit=True, collapse=True) if not off_screen: cmds.showWindow(window) # Set the modelEditor of the modelPanel as the active view so it takes # the playback focus. Does seem redundant with the `refresh` added in. editor = cmds.modelPanel(panel, query=True, modelEditor=True) cmds.modelEditor(editor, edit=True, activeView=True) # Force a draw refresh of Maya so it keeps focus on the new panel # This focus is required to force preview playback in the independent panel cmds.refresh(force=True) try: yield panel finally: # Delete the panel to fix memory leak (about 5 mb per capture) cmds.deleteUI(panel, panel=True) cmds.deleteUI(window)
def switchToCamerView(self, *args): iplContents = cmds.paneLayout(self.UIElements["imagePaneLayout"], q=True, ca=True) if iplContents != None: cmds.deleteUI(iplContents) """ Make a camera """ self.playblastCam() """ Create a new model panel layout """ cmds.setParent(self.UIElements["imagePaneLayout"]) self.UIElements['modelPanel'] = cmds.modelPanel(mbv=False, label="PlayblastWindow") """ Show the playblastCam in the model panel """ cmds.modelPanel(self.UIElements['modelPanel'], edit=True, cam=self.UIElements['playblastCam'][0]) cmds.setParent(self.UIElements["window"]) """ Edit the save animation button """ cmds.button(self.UIElements['saveAnimButton'], edit=True, label='Continue', c=self.exportCurrentAnimation )
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 '
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 getCurrentCamera(): ''' gets the current maya viewport camera ''' pan = mc.getPanel(wf=True) cam = mc.modelPanel(pan, q=True, camera=True) return mn.Node( cam )
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)
def getCurrentModelPanels(): pannels = cmds.getPanel( vis=1 ) modelPanels = [] for pannel in pannels: if cmds.modelPanel( pannel, ex=1 ): modelPanels.append( pannel ) return modelPanels
def setCaptureSettings(self): for i in self.mPanelList: mEditor = cmds.modelPanel(i['model_panel'], query=True, modelEditor=True) for setting in i: if setting != 'model_panel': execStr = 'cmds.modelEditor("' + str(mEditor) + '", edit=True, ' + setting + '=' + str(i[setting]) + ')' exec(execStr)
def resetPanZoom(): panel = cmds.getPanel(wf=True) cameraNode = cmds.modelPanel(panel, q=True, camera=True) cmds.setAttr(cameraNode+".zoom", 1) cmds.setAttr(cameraNode+".horizontalPan", 0) cmds.setAttr(cameraNode+".verticalPan", 0)
def parse_active_view(): """Parse active view for settings""" panel = cmds.getPanel(withFocus=True) assert "model" in panel, "No active viewport" camera = cmds.modelPanel(panel, query=True, camera=True) camera_shape = cmds.listRelatives(camera, shapes=True)[0] return { "camera": camera, "width": cmds.getAttr("defaultResolution.width"), "height": cmds.getAttr("defaultResolution.height"), "camera_options": type("CameraOptions", (object, CameraOptions,), { "displayFilmGate": cmds.getAttr(camera_shape + ".displayFilmGate"), "displayResolution": cmds.getAttr(camera_shape + ".displayResolution"), "displaySafeAction": cmds.getAttr(camera_shape + ".displaySafeAction"), }), "viewport_options": type("ViewportOptions", (object, ViewportOptions,), { "useDefaultMaterial": cmds.modelEditor(panel, query=True, useDefaultMaterial=True), "wireframeOnShaded": cmds.modelEditor(panel, query=True, wireframeOnShaded=True), "displayAppearance": cmds.modelEditor(panel, query=True, displayAppearance=True), "displayTextures": cmds.modelEditor(panel, query=True, displayTextures=True), "displayLights": cmds.modelEditor(panel, query=True, displayLights=True), "shadows": cmds.modelEditor(panel, query=True, shadows=True), "xray": cmds.modelEditor(panel, query=True, xray=True), }), "display_options": type("DisplayOptions", (object, DisplayOptions,), { "background": cmds.displayRGBColor('background', q=True), "backgroundTop": cmds.displayRGBColor('backgroundTop', q=True), "backgroundBottom": cmds.displayRGBColor('backgroundBottom', q=True), 'displayGradient': cmds.displayPref(dgr=True, q=True), }), }
def reset_camera (): print '_' * 80 print '=' * 80 # parameter defaults camParms = { 'displayFilmGate' : 1, 'displayResolution' : 1, 'panZoomEnabled' : 0, 'horizontalPan' : 0, 'verticalPan' : 0, 'zoom' : 1, 'horizontalFilmOffset' : 0, 'overscan' : 1, 'verticalFilmOffset' : 0 } panel = cmds.getPanel (withFocus = True) print '> panel:\t\t', panel camera = cmds.modelPanel (panel, query = True, camera = True) print '> camera:\t\t', camera cameraShape = cmds.listRelatives (camera, shapes = True)[0] print '> camera shape:\t', cameraShape # set default parameters for i in camParms: cmds.setAttr (cameraShape + '.' + i, camParms[i]) print '>', i, ':', ' ' * (25 - len(i)), camParms[i]
def __init__(self, assets_path, project, send_mode, render_position): self.assets_path = assets_path self.project = project self.send_mode = send_mode self.render_position = render_position self.accepted_renderers = ['vray', 'redshift', 'arnold'] self.image_path = cmds.renderSettings( firstImageName=True, fpt=True)[0].rsplit('.', 1)[0] + '.exr' self.render_geo = cmds.ls(sl=True, typ="transform") self.current_renderer = cmds.getAttr( 'defaultRenderGlobals.currentRenderer') self.render_camera = cmds.modelPanel("modelPanel4", query=True, camera=True) self.render_camera_xforms = cmds.xform(self.render_camera, q=True, ws=True, m=True) self.final_path = None self.hdri_render_main() self.finalise_render() self.prepare_image_path()
def main(): cam = cm.modelPanel(cm.getPanel(withFocus=True), q=True, cam=True) workDir = cm.workspace(rootDirectory=True, q=True) blastPath = workDir + "playblasts" filename = os.path.basename(cm.file(q=True, sceneName=True)) filename = os.path.splitext(filename)[0] currRenderLayer = cm.editRenderLayerGlobals(currentRenderLayer=True, q=True) folderName = filename + "__" + cam + "__" + currRenderLayer savingPath = blastPath + "\\" + folderName + "\\" + folderName print savingPath # if ":" in savingPath: # savingPath = savingPath.replace(":","_") imageWidth = cm.getAttr("defaultResolution.width") imageHeight = cm.getAttr("defaultResolution.height") cm.playblast(filename=savingPath, format="image", width=imageWidth, height=imageHeight, percent=100, offScreen=True, showOrnaments=False, compression="png") print "playblast done"
def UpdateSubSnap(): perspPanel = cmds.getPanel( withLabel='Persp View') oldCamera = cmds.modelPanel( perspPanel, query = True, camera = True) def ChangeCamera(): cmds.modelPanel( perspPanel, edit = True, camera = "persp") SubdivisionTextClass.Camera = "persp" #change the view to the camera i = 0 while cmds.objExists("shot_" + str(i)): if cmds.getAttr("shot_" + str(i) + ".CMSignature"): SubdivisionTextClass.Camera = "shot_" + str(i) cmds.modelPanel( perspPanel, edit = True, camera = "shot_" + str(i)) i = i + 1 def CreateSnap(): #Create a snapshot from the signature image SubdivisionTextClass.ImagePath = cmds.getAttr("CMSettings.ProjectPath") + "/temp/" + cmds.getAttr("CMSettings.ModelName") + "_Subdivision_Temp_0" + ".png" cmds.editRenderLayerGlobals( currentRenderLayer = "Subdivision_0") ScreenCapture.ScreenCapture(SubdivisionTextClass.ImagePath, [740,400]) cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer") #Return the camera to whatever it was cmds.modelPanel( perspPanel, edit = True, camera = oldCamera) ChangeCamera() CreateSnap() if cmds.picture("BasePicture", query = True, exists = True): cmds.picture( "BasePicture", edit = True, image = SubdivisionTextClass.ImagePath )
def reset_camera(): print "_" * 80 print "=" * 80 # parameter defaults camParms = { "displayFilmGate": 1, "displayResolution": 1, "panZoomEnabled": 0, "horizontalPan": 0, "verticalPan": 0, "zoom": 1, "horizontalFilmOffset": 0, "overscan": 1, "verticalFilmOffset": 0, } panel = cmds.getPanel(withFocus=True) print "> panel:\t\t", panel camera = cmds.modelPanel(panel, query=True, camera=True) print "> camera:\t\t", camera cameraShape = cmds.listRelatives(camera, shapes=True)[0] print "> camera shape:\t", cameraShape # set default parameters for i in camParms: cmds.setAttr(cameraShape + "." + i, camParms[i]) print ">", i, ":", " " * (25 - len(i)), camParms[i]
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"])
def getCamera(self): _selection = cmds.ls(selection=True) # check selection length if len(_selection) == 0: # check panel for camera if selection is empty _panel = cmds.getPanel(withFocus=True) _typeOfPanel = mm.eval("getPanel -typeOf " + _panel) # check if modelpanel with camera is active if _typeOfPanel == "modelPanel": # get camera from modelpanel _cameraname = cmds.modelPanel(_panel, query=True, camera=True) _camerashape = cmds.listRelatives(_cameraname, shapes=True)[0] else: # no selection, no modelpanel active _cameraname = "Nul" _camerashape = "Nul" else: # selection is not emtpy _cameraname = _selection[0] _camerashape = cmds.listRelatives(_cameraname, shapes=True)[0] # check if selected shape is camera if cmds.nodeType(_camerashape) != "camera": # selection is not camera _cameraname = "Nul" _camerashape = "Nul" self.name = _cameraname self.shape = _camerashape
def draw_PlayView(pWindowTitle, *args): ctrl_set = set() wInd = 0 WH = (-75, -125) # Window dimensions are 250*150, negated for addition for panel in cmds.getPanel(vis=True): try: ctrl = cmds.modelPanel(panel, q=True, control=True) ctrl_set.add(get_layout_control(ctrl)) log.debug("Panel: {}".format(ctrl)) log.debug("Control: {}".format(ctrl_set)) except: pass for parent in ctrl_set: for w in get_windows(): if parent.startswith(w): WC = get_window_center(w) TLC = [sum(x) for x in zip(WC, WH)] log.debug("Window center: {}".format(WC)) log.debug("Top-left corner: {}".format(TLC)) gui(parent, pWindowTitle, "{}{}".format(windowID, wInd), TLC) log.debug("Window: {}{}".format(windowID, wInd)) log.debug("Control: {}".format(parent)) wInd += 1
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()
def __init__(self): # define camera print "[define camera class]" _selection = cmds.ls(selection=True) _panel = cmds.getPanel(withFocus=True) _typeOfPanel = mm.eval("getPanel -typeOf " + _panel) _cameraSelected = False # check for selected camera print "[checking selection for camera]" if len(_selection) != 0: # selection not empty _camera = _selection[0] _cameraShape = cmds.pickWalk(direction="down")[0] if cmds.nodeType(_cameraShape) != "camera": # selection is not a camera print "[selecton or first leselcted object is not camera]" else: # selection is a camera if _camera == _cameraShape: # if cameraShape is selected get camera transform _camera = cmds.pickWalk(direction="up")[0] _cameraSelected = True else: # no selection print "[no selection. checking active panel for camera.]" if _typeOfPanel == "modelPanel": # panel is modeling panel with camera _camera = cmds.modelPanel(_panel, query=True, camera=True) cmds.select(_camera) _cameraShape = cmds.pickWalk(direction="down")[0] _cameraSelected = True else: # no modeling panel with camera is selected print "[active panel is not modeling panel with camera]" if _cameraSelected: # camera is extracted, get properties print "[camera OK]" print "-> camera: " + _camera print "-> cameraShape: " + _cameraShape self.camera = _camera self.cameraShape = _cameraShape self.aperture_h = cmds.camera(_camera, query=True, horizontalFilmAperture=True) self.aperture_v = cmds.camera(_camera, query=True, verticalFilmAperture=True) self.fieldOfView_h = cmds.camera(_camera, query=True, horizontalFieldOfView=True) self.fieldOfView_v = cmds.camera(_camera, query=True, verticalFieldOfView=True) self.filmOffset_h = cmds.camera(_camera, query=True, horizontalFilmOffset=True) self.filmOffset_v = cmds.camera(_camera, query=True, verticalFilmOffset=True) self.overscan = cmds.camera(_camera, query=True, overscan=True) else: # no camera print "[could not extract camera]"
def GetActiveCamera(): #Get the persp panel perspPanel = cmds.getPanel( withLabel='Persp View') #Get the active camera in the panel ActiveCamera = cmds.modelPanel( perspPanel, query = True, camera = True) return ActiveCamera
def __init__(self, parent=getMayaWindow()): super(MayaSubWindow, self).__init__(parent) self.modalPanel = cmds.modelPanel('modlPnl') #self.executer = cmds.cmdScrollFieldExecuter(sourceType="python") qtObj = toQtObject(self.modalPanel) #Fill the window, could use qtObj.setParent #and then add it to a layout. self.setCentralWidget(qtObj)
def __createUI(self): self.win = CurveToolUI.win_name if not cmds.uiTemplate('CurveToolsUITemplate', exists=True): cmds.uiTemplate('CurveToolsUITemplate') if cmds.window(self.win, exists=True): cmds.deleteUI(self.win) self.win = cmds.window(self.win, t=CurveToolUI.win_title, mb=True, w=656, h=385) self.main_menu = cmds.menu(label="Menu", parent=self.win) #cmds.menuItem(label="Refresh List", c=self.handleRefreshMenu) self.help_menu = cmds.menu(label="Help", parent=self.win) #cmds.menuItem(label="Help", c=self.handleHelpMenu) self.mainLayout = cmds.rowColumnLayout(nc=2, cw=[(1, 292), (2, 360)]) self.leftLayout = cmds.rowColumnLayout(nr=3, parent=self.mainLayout, rh=[(1, 48), (2, 256), (3, 48)]) self.topRow = cmds.rowColumnLayout(nc=3, parent=self.leftLayout) self.shapesList = cmds.textScrollList(parent=self.leftLayout, nr=24) self.btmRow = cmds.rowColumnLayout(nc=3, parent=self.leftLayout, w=128) self.createBtn = cmds.button(l="Create", w=96, h=48, parent=self.topRow) self.replaceBtn = cmds.button(l="Replace", w=96, h=48, parent=self.topRow) self.appendBtn = cmds.button(l="Append", w=96, h=48, parent=self.topRow) self.saveBtn = cmds.button(l="Save", w=96, h=48, parent=self.btmRow) self.overwriteBtn = cmds.button(l="Overwrite", w=96, h=48, parent=self.btmRow) self.deleteBtn = cmds.button(l="Delete", w=96, h=48, parent=self.btmRow) self.paneLayout = cmds.paneLayout(parent=self.mainLayout) self.viewport = cmds.modelPanel(mbv=False, parent=self.paneLayout) #------------------------------------------- install click handlers --- cmds.button(self.createBtn, e=True, c=self.__handleCreateClick) cmds.button(self.replaceBtn, e=True, c=self.__handleReplaceClick) cmds.button(self.appendBtn, e=True, c=self.__handleAppendClick) cmds.button(self.saveBtn, e=True, c=self.__handleSaveClick) cmds.button(self.overwriteBtn, e=True, c=self.__handleOverwriteClick) cmds.button(self.deleteBtn, e=True, c=self.__handleDeleteClick) cmds.textScrollList(self.shapesList, e=True, sc=self.__handleShapeListSelection) #----------------------------------------- setup UiDeleted callback --- self.__uiCallback = OpenMayaUI.MUiMessage.addUiDeletedCallback( self.win, self.__handleUIClosed ) cmds.showWindow(self.win)
def rigidbodyCam() : global rigidbody global camera global lastCam global currentPanel global selection selection = m.ls(sl=True) if len(selection) < 2 : m.error("Please select 2 or more items") return currentPanel = m.getPanel(wf=True) # get the current camera try : lastCam = m.modelPanel(currentPanel, cam=True, q=True) pos = m.xform(lastCam, q=True, t=True, ws=True) ori = m.xform(lastCam, q=True, ro=True, ws=True) except RuntimeError as e : print str(e) m.error("Do you have a viewport selected?") # create a camera camera = m.camera()[0] m.setAttr( camera + ".t", *pos) m.setAttr( camera + ".r", *ori) m.modelPanel( currentPanel, cam=camera, e=True) m.select(selection) rb = mel.eval("peelSolve2RigidBody();") rigidbody = m.listConnections(rb + ".OutputTranslation")[0] m.setAttr(rigidbody + ".v", 0) m.parent( camera, rigidbody ) p1 = m.xform(rigidbody, q=True, ws=True, t=True) p2 = m.xform(camera, q=True, ws=True, t=True) vec = [ a-b for a,b in zip(p1, p2) ] d = math.sqrt(sum( [ a*a for a in vec ] )) m.setAttr( camera + ".centerOfInterest", d)
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 }
def copy(self): '''Tear off a copy of the viewport. :returns: A new torn off copy of Viewport''' panel = cmds.modelPanel(tearOffCopy=self.panel) view = self.from_panel(panel) view.focus = True return view