Пример #1
0
def create_render_cam(name="RENDER_CAM", exposure=True):
    """
    Creates a camera and renames it 
    
    str name: name of the camera
    bool exposure: connect a mia_exposure_photographic node to the camera     
    """
    if not pm.objExists(name):
        cam = pm.camera()[0]
        pm.rename(cam, name)
        [cam.renderable.set(cam.name().startswith(name)) for cam in pm.ls(cameras=True)]
    cam = pm.PyNode(name)
    
    if exposure:
        if not cam.miLensShader.isConnected():
            node = pm.createNode("mia_exposure_photographic")
            node.film_iso.set(800)
            node.f_number.set(1.2)
            node.gamma.set(1)
            pm.connectAttr(node.message, cam.miLensShader, force=True)
    
    cam.getShape().setDisplayResolution(True)
    pm.lookThru(name)
    
    pm.select(cam)
Пример #2
0
 def create_temp_panel(self):
     # create panel for playblast
     self.viewport = pm.modelPanel(tearOff=True)
     pm.setFocus(self.viewport)
     pm.control(self.viewport, edit=True, w=self.output_dimentions[0])
     pm.control(self.viewport, edit=True, h=self.output_dimentions[1])
     pm.lookThru(self.current_camera)
Пример #3
0
 def toggleCam(self):
     currentCam = pm.lookThru(q=1)
     allCam = self.sel_cams
     for pos in range(0, len(allCam)):
         if currentCam == allCam[pos]:
             nextCam = int(pos + 1)
     if nextCam >= len(allCam):
         nextCam = 0
     pm.lookThru(allCam[nextCam])
    def addCam(self,
               text,
               rx=-45,
               ry=45,
               ortho=False,
               json=True,
               t_r_list=None):
        """addCam 添加摄像机
        
        Arguments:
            text {str} -- 摄像机名称
        
        Keyword Arguments:
            rx {int} -- x轴旋转角度 (default: {-45})
            ry {int} -- y轴旋转角度 (default: {45})
            ortho {bool} -- 正交属性 (default: {False})
            json {bool} -- 是否存储当前设置的属性 (default: {True})
            t_r_list {tuple} -- 位移和旋转的组合元组 (default: {None})
        
        Returns:
            [camera] -- Maya 的 Camera 对象
        """
        fit = self.manager.setting.Fit_SP.value()

        cam, cam_shape = pm.camera(n=text)
        text = cam.name()

        pm.parent(cam, self.grp)

        # Note 隐藏摄像机
        cam.visibility.set(0)

        # Note 如果传入这个变量说明是读取数据 安装数据设置摄像机
        pm.select(self.sel_list)
        if t_r_list:
            t, r = t_r_list
            cam.t.set(t)
            cam.r.set(r)
        else:
            cam.rx.set(rx)
            cam.ry.set(ry)
            pm.lookThru(cam)
            pm.viewFit(f=fit, all=0)

        if ortho:
            cam_shape.orthographic.set(ortho)
            pm.lookThru(cam)
            pm.viewFit(f=fit / 2, all=0)

        # NOTE 是否将数组输出到到字典上
        if json:
            self.camera_setting[text] = {}
            self.camera_setting[text]["translate"] = cam.t.get().tolist()
            self.camera_setting[text]["rotate"] = cam.r.get().tolist()
            self.camera_setting[text]["orthographic"] = ortho

        return cam
Пример #5
0
def cleanPlayblastWindow(ui, renderers):
    print 'Remove playblasting windows and restore settings...'
    # display stereo layers if any
    try:
        scf.showLayer2()
    except:
        print traceback.format_exc()

    # recover transparent sorting
    try:
        pm.modelEditor(ui['editor'], e=True, sortTransparent=True)
    except:
        print traceback.format_exc()

    # delete hud expression
    if pm.objExists('stereoUpdateHUD'):
        pm.delete('stereoUpdateHUD')

    # delete custom hud, restore previous hud
    try:
        if pm.headsUpDisplay(ui['hud_stereo'], query=True, ex=True):
            pm.headsUpDisplay(ui['hud_stereo'], rem=True)

        for huds in ui['huds_current']:
            if pm.headsUpDisplay(huds, query=True, ex=True):
                pm.headsUpDisplay(huds, edit=True, vis=True)
    except:
        print traceback.format_exc()

    # delete safe area
    try:
        safeareaShapes = pm.ls(type='spReticleLoc')
        for safe in safeareaShapes:
            try:
                pm.delete(safe.getParent())
            except:
                pass
    except:
        print traceback.format_exc()

    # restore background color
    if ui['bgColor']:
        makeBluescreen( ui['bgColor'], renderers )

    # delete preview window
    try:
        pm.deleteUI(ui['window'].name(), window=True)
    except:
        print traceback.format_exc()

    try:
        pm.lookThru('persp')
    except:
        print traceback.format_exc()
Пример #6
0
    def bdSetCamera(self, referenceCam):
        pm.mel.eval(
            'setNamedPanelLayout "Single Perspective View"; updateToolbox();')
        sceneReferences = pm.getReferences()
        print sceneReferences
        camera = ''
        for item in sceneReferences:
            if sceneReferences[item].isLoaded():
                if referenceCam.lower() in sceneReferences[item].path.lower():
                    print 'cam loaded already'
                    camera = pm.ls(item + ':*', type='camera')[0]
                    break

        print referenceCam
        stageCam = pm.ls(referenceCam + '*', type='camera')[0]
        print stageCam

        if stageCam:
            camera = stageCam
        if camera == '':
            if os.path.isfile(referenceCam):
                pm.createReference(referenceCam, namespace="CAM")
                camera = pm.ls('CAM:*', type='camera')[0]
            else:
                print 'No cam file, creating a default one'
                cameraList = pm.camera(n='playblastCam')
                camera = cameraList[1]
                cameraList[0].setTranslation([0, 10, 60])
        '''
        perspModel = "".join(pm.getPanel(withLabel = 'Persp View'))
        if perspModel == '':
            perspModel = "".join(pm.getPanel(withLabel = 'Side View'))
        print camera, perspModel

        pm.setFocus(perspModel)
        '''

        perspView = pm.getPanel(wf=1)

        pm.modelEditor(perspView, e=1, alo=0, activeView=True)
        pm.modelEditor(perspView, e=1, polymeshes=1, wos=0, grid=0)
        pm.modelEditor(perspView,
                       e=1,
                       displayAppearance='smoothShaded',
                       displayTextures=1)

        try:
            pm.lookThru(perspView, camera)
        except:
            print 'Failed to look through playblast camera'
Пример #7
0
def bdSetCamera(camera,referenceCam):
	if referenceCam:
		pm.createReference(referenceCam,namespace="CAM")
		camera = pm.ls('CAM:*',type='camera')[0]
		
	perspModel = "".join(pm.getPanel(withLabel = 'Persp View'))
	pm.setFocus(perspModel)
	perspView = pm.getPanel(wf=1)
	pm.lookThru(perspView,camera)
	#pm.modelPanel (perspView, query=1,label=1)
	pm.modelEditor(perspView,e=1,alo=0)
	pm.modelEditor(perspView,e=1,polymeshes=1,grid=0)
	pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1)	
	perspCam = pm.ls('persp',type='transform')[0]
Пример #8
0
def bdSetCameraVP2(cam):
	pm.createReference("P:/smurfs/working_project/cameras/worldcup_cam.ma",ns='cam')
	
	pm.mel.eval('setNamedPanelLayout \"Single Perspective View\"');
	perspModel = "".join(pm.getPanel(withLabel = 'Persp View'))
	pm.setFocus(perspModel)
	perspView = pm.getPanel(wf=1)
	pm.lookThru(perspView,cam)
	#pm.modelPanel (perspView, query=1,label=1)
	pm.modelEditor(perspView,e=1,alo=0)
	pm.modelEditor(perspView,e=1,polymeshes=1,imagePlane=1,grid=0)
	pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1,wireframeOnShaded=0)
	consolidate = pm.mel.eval('checkMemoryForConsolidatedWorld()')
	if consolidate:
		pm.modelEditor(perspView,e=1,rnm="vp2Renderer",rom='')
Пример #9
0
	def bdSetCamera(self,referenceCam):
		pm.mel.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();')
		sceneReferences = pm.getReferences()
		print sceneReferences
		camera = ''
		for item in sceneReferences :
			if sceneReferences[item].isLoaded():
				if referenceCam.lower() in sceneReferences[item].path.lower():
					print 'cam loaded already'
					camera = pm.ls(item + ':*',type='camera')[0]
					break
		
		print referenceCam
		stageCam = pm.ls(referenceCam + '*',type='camera')[0]
		print stageCam
		
		if stageCam:
			camera = stageCam
		if camera == '':
			if os.path.isfile(referenceCam):
				pm.createReference(referenceCam,namespace="CAM")
				camera = pm.ls('CAM:*',type='camera')[0]
			else:
				print 'No cam file, creating a default one'
				cameraList = pm.camera(n='playblastCam')
				camera = cameraList[1]
				cameraList[0].setTranslation([0,10,60])

		'''
		perspModel = "".join(pm.getPanel(withLabel = 'Persp View'))
		if perspModel == '':
			perspModel = "".join(pm.getPanel(withLabel = 'Side View'))
		print camera, perspModel

		pm.setFocus(perspModel)
		'''

		perspView = pm.getPanel(wf=1)

		pm.modelEditor(perspView,e=1,alo=0,activeView = True)
		pm.modelEditor(perspView,e=1,polymeshes=1,wos=0,grid=0)
		pm.modelEditor(perspView,e=1,displayAppearance='smoothShaded',displayTextures=1)	


		try:
			pm.lookThru(perspView,camera)
		except:
			print 'Failed to look through playblast camera'
    def __init__(self, cam, widget):
        super(ViewportCaptureCameraSettingItem, self).__init__()
        ui_file = os.path.join(DIR, "ui", "item.ui")
        loadUi(ui_file, self)

        self.widget = widget
        self.cam = cam
        self.loadCamData()

        self.setting = cam.setting[self.cam.name()]

        # NOTE 添加属性调整触发修改
        self.TX_SP.valueChanged.connect(self.txValueChange)
        self.TY_SP.valueChanged.connect(self.tyValueChange)
        self.TZ_SP.valueChanged.connect(self.tzValueChange)
        self.RX_SP.valueChanged.connect(self.rxValueChange)
        self.RY_SP.valueChanged.connect(self.ryValueChange)
        self.RZ_SP.valueChanged.connect(self.rzValueChange)
        self.Orthographic_CB.stateChanged.connect(self.orthographicState)

        # NOTE 添加按钮点击事件
        self.Cam_BTN.clicked.connect(lambda: pm.select(cam))
        self.Preview_BTN.clicked.connect(lambda: pm.lookThru(cam))
        self.Delete_BTN.clicked.connect(self.deleteLater)
        self.Save_BTN.clicked.connect(self.loadCamData)
Пример #11
0
    def renderScreen(self):
        '''
        Render function to make the screenshot. Playblast a single frame.
        '''

        # return camera / viewport
        currentCamera = self.checkCamera()
        originalCam = self.getViewport()
        resScreen = self.getScreenRes()

        if resScreen:

            # temp disable undo
            pm.undoInfo(openChunk=True, stateWithoutFlush=False)

            # switch current view to camera
            pm.lookThru(currentCamera)

            # file path info from UI inputs
            completeFile = UI.saveLocation + self.getFileNameStyle(
                includeFormat=True)

            # playblast without scale settings, to prevent visual glitches
            pm.playblast(frame=pm.currentTime(),
                         widthHeight=(resScreen[0], resScreen[1]),
                         offScreen=True,
                         clearCache=True,
                         fp=4,
                         p=100,
                         fo=True,
                         cf=completeFile,
                         format="image",
                         viewer=False,
                         c=str(UI.fileExt_dropdwn.currentText()))

            # reset camera back to original viewport
            pm.lookThru(originalCam)

            pm.undoInfo(openChunk=False,
                        closeChunk=True,
                        stateWithoutFlush=True)

            # log info to the user
            if not self.errorMsg:
                api.MGlobal.displayInfo('[#] Log successful  ' +
                                        str(datetime.datetime.now().time()))
Пример #12
0
    def create_render_cam(name="RENDER_CAM"):
        """
        Creates a camera and renames it

        str name: name of the camera
        bool exposure: connect a mia_exposure_photographic node to the camera
        """
        if not pm.objExists(name):
            cam = pm.camera()[0]
            pm.rename(cam, name)
        BasicCamera.set_default_render_cam(name)
        cam = pm.PyNode(name)

        cam.getShape().setDisplayResolution(True)
        pm.lookThru(name)

        pm.select(cam)
Пример #13
0
    def __init__(self, **kwargs):

        self.version = "1.0.0"
        self.title = "adbrower - Cameras Tool"
        self.name = "CamTool_win"

        self.currentCam = pm.lookThru(q=1)
        self.allCam = pm.listCameras(o=False, p=True)

        self.ui()
Пример #14
0
    def perform(self, readconf=True, **kwargs):
        if self.enabled:
            for layer in PlayListUtils.getDisplayLayers():
                if layer.name() in self.getLayers():
                    layer.visibility.set(1)
                else:
                    layer.visibility.set(0)

            item = self.__item__
            try:
                if readconf:
                    self.read_conf()
            except IOError:
                self._conf = PlayblastExport.initConf()

            pc.select(item.camera)
            pc.lookThru(item.camera)
            hidePolyCount()
            showDate()
            exportutils.turnResolutionGateOn(item.camera)
            exportutils.showFrameInfo(item)
            exportutils.setDefaultResolution(
                (1280, 720), default=kwargs.get('defaultResolution'))
            exportutils.turn2dPanZoomOff(item.camera)
            if not kwargs.get('hdOnly'):
                self.makePlayblast(sound=kwargs.get('sound'),
                                   local=kwargs.get('local'))
            exportutils.turnResolutionGateOff(item.camera)
            if kwargs.get('hd'):
                exportutils.turnResolutionGateOffPer(item.camera)
                exportutils.setDefaultResolution((1920, 1080))
                self.makePlayblast(sound=kwargs.get('sound'),
                                   hd=True,
                                   local=kwargs.get('local'))
                showNameLabel()
            exportutils.removeFrameInfo(all=True)
            removeDate()
            removeNameLabel()
            showPolyCount()
            exportutils.restoreDefaultResolution()
            exportutils.restore2dPanZoom(item.camera)
        exportutils.restoreFrameInfo()
Пример #15
0
    def __init__(self, parent=None):
        super(cfxToolbox, self).__init__(parent=parent)

        self.currentCam = pm.lookThru(q=1)
        self.allCam = pm.listCameras(o=False, p=True)
        self.Original_startTime_value = 1001
        self.Original_endTime = self.getCurrentTimeSlider()
        self.playbast_path = None

        self.setObjectName(self.UI_NAME)
        self.setWindowTitle('CFX Toolbox  v{}'.format(VERSION))
        self.setWindowFlags(QtCore.Qt.Tool)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.resize(290, 900)
        # self.setFixedWidth(250)

        # -----------------------------
        # ---  Create scrollArea

        self.mainBox = QtWidgets.QVBoxLayout()
        self.mainBox.setContentsMargins(0, 0, 0, 0)
        self.scroll_layout = QtWidgets.QScrollArea()

        self.mainBox.addWidget(self.scroll_layout)
        self.setLayout(self.mainBox)
        self.scroll_layout.setContentsMargins(0, 0, 0, 0)
        self.scroll_layout.setWidgetResizable(True)
        self.scroll_layout.setFrameStyle(QtWidgets.QFrame.NoFrame)
        self.scroll_layout.setFrameShadow(QtWidgets.QFrame.Plain)

        self.scroll_widget = QtWidgets.QWidget()
        self.scroll_layout.setWidget(self.scroll_widget)

        # -----------------------------
        # ---  Main Layout

        self.main_layout = QtWidgets.QVBoxLayout()
        self.main_layout.setContentsMargins(2, 2, 4, 4)
        self.main_layout.setSpacing(2)
        self.setLayout(self.main_layout)

        self.widgetsAndLayouts()
        self.getOsDatas()
        self.getRootsData()

        self.create_Button()
        self.populate()
        self.buildMainLayout()

        self.scroll_widget.setLayout(self.main_layout)
Пример #16
0
def playblast(self, path, namespace, cam, whichpb, overwrite, subfolder, model):

    model = model
    
    try:
        pane = pm.getPanel( withFocus=True ) # Get panel on focus
        userOldCam = pm.listRelatives(pm.modelEditor(pane, query = True, camera=True))[0] # Get active camera on that panel
    except:
        model.warn("Active pane is not right for playblast. Click on any viewport pane (front, top, side, any camera) and retry.", 1)
        return False

    sizeOpt = pm.getAttr("cycleAnimationListNode.pbSize")
    size = []

    if sizeOpt == "HD 1080":
        size = [1920,1080]
    elif sizeOpt == "HD 720":
        size = [1280,720]
    elif sizeOpt == "HD 540":
        size = [960,540]

    f = pm.getAttr("cycleAnimationListNode.format")
    c = pm.getAttr("cycleAnimationListNode.compression")


    if (cam != "Active"):
        pm.lookThru(cam)

    cycles = model.rowCount(1)

    savePath = path 

    for row in range(cycles):
        model.index(row, 0).data()
        if model.index(row, 0).data() or whichpb:
            
            name = model.index(row, 1).data()
            start = int(model.index(row, 2).data())
            end = int(model.index(row, 3).data())
            info = model.index(row, 4).data()
            version = int(model.index(row, 5).data())
            
            index = model.index(row, 5)

            if subfolder:
                savePath += "/" + name

            if (namespace != ''):
                savePath += "/" + namespace +"_"+ name
            else:
                savePath += "/" + name

            if  overwrite:
                a = str(version)
                while len(a) < 3:
                    a = "0" + a
                model.setData(index, a, role = Qt.EditRole)
                savePath += "_" + a
            else:
                version += 1
                a = str(version)
                while len(a) < 3:
                    a = "0" + a
                model.setData(index, a, role = Qt.EditRole)
                savePath += "_" + a

            sufix = pm.getAttr("cycleAnimationListNode.sufix")
            if not sufix == '':
                savePath += "_" + sufix


            setHUD(name, info, version)

            print "aqui"
            print name, info, version, f , c

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

                pm.playblast(startTime = start, 
                            endTime = end,
                            format = f, 
                            filename = savePath, 
                            forceOverwrite = overwrite, 
                            compression = c, 
                            offScreen = True, 
                            percent = 100, 
                            quality = 100,
                            widthHeight = size,
                            clearCache = 1,
                            sequenceTime= False,
                            showOrnaments = True)
            else:
                model.warn('The specified path does not exist. Choose a valid path', 1)
                removeHUD()
                return False
            
            removeHUD()
                
    pm.lookThru(userOldCam)

    model.warn("Playblast sucessfully executed", 0)
Пример #17
0
def restoreOriginalCamera():
    global __original_camera__
    pc.lookThru(__original_camera__)
    __original_camera__ = None
    return
Пример #18
0
 def switch_view(self):
     self.update_camera()
     self.apply_camera_setting()
     pm.setFocus(self.viewport)
     pm.lookThru(self.current_camera)
Пример #19
0
 def doubleClickedCamLeft(self):
     _sel_cams = self.presetListLeft.currentItem().text()
     pm.lookThru(_sel_cams)
file_node.outSize.outSizeX >> ocio_node.width
file_node.outSize.outSizeY >> ocio_node.height
pm.select(cl = True)

#connect ocio node to shader
ocio_node.output_color >> shader_node.outColor
pm.select(cl = True)

#set texture file
file_node.fileTextureName.set(texture_dir +'/' +texture_name)

#polyplane_transform_node, polyplane_shape_node
polyplane_transform_node, polyplane_shape_node = pm.polyPlane(n = 'ocio_test_polyplane', sx = 10, sy = 10, axis = (0,1,0), width = 12.8, height = 7.8)
pm.select(cl = True)
#connect plane to shader
pm.sets(shading_group_node, forceElement = polyplane_transform_node.name())
pm.select(cl = True)


#render_cam
render_cam_transform, render_cam_shape = pm.camera()
pm.select(cl = True)
pm.rename(render_cam_transform, 'render_cam')
render_cam_transform.translate.set(0,13,7)
render_cam_transform.rotate.set(-65,0,0)
pm.setKeyframe(render_cam_transform, s = False)
pm.lookThru(render_cam_transform)


#select ocio node at end
pm.select(ocio_node, r = True)
Пример #21
0
    def capture(self):
        """
        capture 截取图片输出
        """
        file_path, _ = QFileDialog.getSaveFileName(
            self, caption=u"获取输出图片路径", filter=u"png (*.png);;jpg (*.jpg)")

        # NOTE 判断是否是空路径
        if not file_path:
            return

        # NOTE 获取当前激活的面板 (modelPanel4)
        for panel in pm.getPanel(type="modelPanel"):
            if pm.modelEditor(panel, q=1, av=1):
                active_cam = pm.modelEditor(panel, q=1, camera=1)
                active_panel = panel
                break

        # NOTE 获取当前 HUD 相关的显示状态
        display_1 = pm.modelEditor(active_panel, q=1, hud=1)
        display_2 = pm.modelEditor(active_panel, q=1, grid=1)
        display_3 = pm.modelEditor(active_panel, q=1, m=1)
        display_4 = pm.modelEditor(active_panel, q=1, hos=1)
        display_5 = pm.modelEditor(active_panel, q=1, sel=1)

        # NOTE 隐藏界面显示
        pm.modelEditor(active_panel, e=1, hud=0)
        pm.modelEditor(active_panel, e=1, grid=0)
        pm.modelEditor(active_panel, e=1, m=0)
        pm.modelEditor(active_panel, e=1, hos=0)
        pm.modelEditor(active_panel, e=1, sel=0)

        # NOTE 触发截屏处理
        self.cam_setting = self.manager.cam_setting
        self.setting = self.manager.setting
        # NOTE 根据设置窗口的选项 获取图片处理的API
        API = self.setting.Maya_RB.isChecked()
        if API:
            self.util = MayaImageUtil()
        else:
            self.util = QtImageUtil()

        # NOTE 创建临时摄像机组
        self.cam_setting.showProcess()

        # NOTE 获取摄像机截取的画面
        img_list = []
        for cam in self.cam_setting.camera_setting:
            pm.lookThru(cam)
            img = self.captureImage()
            if img: img_list.append(img)

        # Note 合并图片
        img = self.util.mergeImage(
            img_list, horizontal=self.setting.Horizontal_RB.isChecked())

        ext = os.path.splitext(file_path)[-1][1:]
        # Note 不同API的输出指令不一样进行区分
        if API:
            img.writeToFile(file_path, ext)
        else:
            img.save(file_path, format=ext)

        # NOTE 恢复HUD显示
        pm.modelEditor(active_panel, e=1, hud=display_1)
        pm.modelEditor(active_panel, e=1, grid=display_2)
        pm.modelEditor(active_panel, e=1, m=display_3)
        pm.modelEditor(active_panel, e=1, hos=display_4)
        pm.modelEditor(active_panel, e=1, sel=display_5)

        # NOTE 恢复之前的摄像机视角并删除临时的摄像机组
        pm.lookThru(active_cam)
        pm.delete(self.cam_setting.grp)

        # NOTE 输出成功信息
        QtWidgets.QMessageBox.information(self, u"输出完成",
                                          u"图片输出成功\n输出路径:%s" % file_path)
Пример #22
0
 def lookThruCamera(self, item):
     camera = str(item.text(0))
     if pm.objExists(camera):
         pm.lookThru(camera)
Пример #23
0
def getCameraName():
    return qutil.getNiceName(pc.lookThru(q=True))
Пример #24
0
def setOriginalCamera():
    global __original_camera__
    __original_camera__ = pc.lookThru(q=True)
    def showProcess(self):
        """
        showProcess 继承自 General 类 切换界面的时候触发
        """
        self.sel_list = pm.ls(sl=1)
        if not self.sel_list:
            self.sel_list = [mesh.getParent() for mesh in pm.ls(type="mesh")]

        # NOTE 获取当前使用的摄像机视角
        for panel in pm.getPanel(type="modelPanel"):
            if pm.modelEditor(panel, q=1, av=1):
                self.active_cam = pm.modelEditor(panel, q=1, camera=1)
                break

        self.cam_list = []
        if pm.objExists("temp_capture_grp"):
            pm.delete("temp_capture_grp")
        self.grp = pm.group(n="temp_capture_grp", em=1)

        # NOTE 默认添加五个位置的视角 初始化输出默认摄像机视角
        if self.initialzie_cam:
            self.initialzie_cam = False
            self.camera_setting = OrderedDict()
            self.cam_list.append(self.addCam("front_cam", 0, 0, ortho=1))
            self.cam_list.append(self.addCam("side_cam", 0, -90, ortho=1))
            self.cam_list.append(self.addCam("top_cam", -90, 0, ortho=1))
            self.cam_list.append(self.addCam("fs45_cam", -45, 45))
            self.cam_list.append(self.addCam("bs45_cam", -45, -135))
        else:
            # NOTE 已经经过初始化则读取 setting 数据
            for cam in self.camera_setting:
                r_list = self.camera_setting[cam]["rotate"]
                t_list = self.camera_setting[cam]["translate"]
                ortho = self.camera_setting[cam]["orthographic"]
                self.cam_list.append(
                    self.addCam(cam,
                                ortho=ortho,
                                json=0,
                                t_r_list=(t_list, r_list)))

        # NOTE 清空当前列表中的内容 除了弹簧
        count = self.Cam_Item_Scroll.layout().count() - 1
        for i in reversed(range(self.Cam_Item_Scroll.layout().count())):
            if i != count:
                widgetToRemove = self.Cam_Item_Scroll.layout().itemAt(
                    i).widget()
                self.Cam_Item_Scroll.layout().removeWidget(widgetToRemove)
                if widgetToRemove: widgetToRemove.setParent(None)

        # NOTE 根据设置逐个添加摄像机 item
        for cam in self.cam_list:
            cam.setting = self.camera_setting
            item = ViewportCaptureCameraSettingItem(cam, self)

            count = self.Cam_Item_Scroll.layout().count()
            self.Cam_Item_Scroll.layout().insertWidget(count - 1, item)

        # NOTE 还原当前使用的摄像机视角
        pm.lookThru(self.active_cam)

        # NOTE 是否禁用添加按钮
        self.manager.setting.limitCam()
Пример #26
0
 def getSelected2(self):
     self.viewCam = pm.textScrollList(self.all_cams,
                                      q=True,
                                      selectItem=True)
     pm.lookThru(self.viewCam)
Пример #27
0
 def _updateCamera(self, lightName):
     pmc.lookThru('lcModelPanel', lightName)
Пример #28
0
 def lookThruCamera(self, item):
     camera = str(item.text(0))
     if pm.objExists(camera):
         pm.lookThru(camera)
Пример #29
0
 def deleteTempData():
     if pm.objExists("temp_capture_grp"):
         pm.delete("temp_capture_grp")
     if hasattr(self.cam_setting, "active_cam") and pm.objExists(
             self.cam_setting.active_cam):
         pm.lookThru(self.cam_setting.active_cam)
Пример #30
0
 def on_camlookthrough_btn(self, *args):
     pm.lookThru(pm.imagePlane(self.currentImgPlane, q=1, camera=1))
Пример #31
0
#connect ocio node to shader
ocio_node.output_color >> shader_node.outColor
pm.select(cl=True)

#set texture file
file_node.fileTextureName.set(texture_dir + '/' + texture_name)

#polyplane_transform_node, polyplane_shape_node
polyplane_transform_node, polyplane_shape_node = pm.polyPlane(
    n='ocio_test_polyplane',
    sx=10,
    sy=10,
    axis=(0, 1, 0),
    width=12.8,
    height=7.8)
pm.select(cl=True)
#connect plane to shader
pm.sets(shading_group_node, forceElement=polyplane_transform_node.name())
pm.select(cl=True)

#render_cam
render_cam_transform, render_cam_shape = pm.camera()
pm.select(cl=True)
pm.rename(render_cam_transform, 'render_cam')
render_cam_transform.translate.set(0, 13, 7)
render_cam_transform.rotate.set(-65, 0, 0)
pm.setKeyframe(render_cam_transform, s=False)
pm.lookThru(render_cam_transform)

#select ocio node at end
pm.select(ocio_node, r=True)
Пример #32
0
def fn_playblast(stereocam, file_name, layer_number, cut_in, cut_out, is_rear_layer=True, pb_offscreen=True, \
                 renderers='base_OpenGL_Renderer', display_elements={}, \
                ext='png', widthHeight=[2048,858], enable_anim_floating_window=False):
    center = stereocam
    try:
        left = center.attr('leftCamera').get()
        right = center.attr('rightCamera').get()
    except:
        print 'Failed to get left and right camera from '+str(center)
        return []

    # disable resolution
    try:
        center.attr('displayResolution').set(0)
        center.attr('displayGateMask').set(0)
        center.attr('displayFilmGate').set(0)
    except:
        pass

    # make sure that we play frames in every frame
    try:
        pm.playbackOptions(edit=True, by=1.0)
    except:
        pass

    #get user option before building model editor
    #opt_path = pm.internalVar(usd=True).replace('\\', '/')
    #if os.path.isfile(opt_path+'updatePreviewXmlUserOption.txt'):

    # initial vars before building model editor
    if renderers=='vp2Renderer':
        # if we use viewport2(vp2) render, the images contain alpha channel, 
        # then we simply use imconvert to composite images instead of chrome keying in nuke
        # but imconvert can not recognize tif image, so we change the default tif to png
        ext = 'png'

    layer = 'main'
    if file_name.endswith('.near'):
        layer = 'near'
    elif file_name.endswith('.far'):
        layer = 'far'

    # floating window value
    fwv = scf.getFloatingWindowValues(center, cut_in, cut_out)

    add_float_window = True
    if not fwv['ll'] and not fwv['lr'] and not fwv['rl'] and not fwv['rr']:
        add_float_window = False

    cameras = {'center':center, 'left':left, 'right':right}

    deleteUselessHudExpression()

    # build the model editor
    global stereo_pb_window
    stereo_pb_window_exists = False
    for w in pm.lsUI(type='window'):
        try:
            if pm.window(w, ex=True) and w.getTitle()=='stereo_pb_window':
                stereo_pb_window_exists = True
                break
        except:
            pass
    if stereo_pb_window and stereo_pb_window['window'] and pm.window(stereo_pb_window['window'], ex=True):
        stereo_pb_window_exists = True

    ratio = float(widthHeight[0])/widthHeight[1]

    ui = {}
    if stereo_pb_window_exists:
        ui = stereo_pb_window
    else:
        ui = buildPlayblastWindow(cameras, layer, layer_number, add_float_window, renderers, is_rear_layer, ratio, display_elements)
    p_window = ui['window']
    p_editor = ui['editor']
    safearea = ui['safearea']
    hud_stereo = ui['hud_stereo']
    huds_current = ui['huds_current']
    bgColor = ui['bgColor']

    #global stereo_pb_continue
    #if enable_anim_floating_window and fwv['animated'] and not stereo_pb_continue:
    #    stereo_pb_continue = True
    #    return []

    # playblast left eye first
    try:
        try:
            if safearea:
                safearea.attr('panScanRatio').set(ratio)
                safearea.attr('panScanOffset').set(0)
        except:
            pass
        if safearea and (fwv['ll'] or fwv['lr']):
            try:
                setPanScanValues(fwv, safearea, cut_in, cut_out, ratio, eye='left')
            except:
                print traceback.format_exc()
        try:
            left.attr('overscan').unlock()
            left.attr('overscan').set(1.0)
        except:
            print traceback.format_exc()
        # disable resolution display
        try:
            left.attr('displayResolution').unlock()
            left.attr('displayResolution').set(False)
        except:
            pass
        pm.modelEditor(p_editor, edit=True, camera=left, activeView=True)
        pm.lookThru(left)
        pm.refresh()
    except:
        print traceback.format_exc()

    left_img = pm.playblast( startTime=cut_in, endTime=cut_out,  format='image', filename=file_name+'.left', \
                forceOverwrite=True, sequenceTime=0, clearCache=False, viewer=False, showOrnaments=True, \
                offScreen=True, fp=4, percent=100, compression=ext, widthHeight=(widthHeight[0],widthHeight[1]), quality=100)
    try:
        left.attr('overscan').lock()
        left.attr('displayResolution').lock()
    except:
        pass

    # right eye follows
    try:
        try:
            if safearea:
                safearea.attr('panScanRatio').set(ratio)
                safearea.attr('panScanOffset').set(0)
        except:
            pass
        if safearea and (fwv['rl'] or fwv['rr']):
            try:
                setPanScanValues(fwv, safearea, cut_in, cut_out, ratio, eye='right')
            except:
                print traceback.format_exc()
        try:
            right.attr('overscan').unlock()
            right.attr('overscan').set(1.0)
        except:
            print traceback.format_exc()
        # disable resolution display
        try:
            right.attr('displayResolution').unlock()
            right.attr('displayResolution').set(False)
        except:
            pass
        pm.modelEditor(p_editor, edit=True, camera=right, activeView=True)
        pm.lookThru(right)
        pm.refresh()
    except:
        print traceback.format_exc()

    right_img = pm.playblast( startTime=cut_in, endTime=cut_out,  format='image', filename=file_name+'.right', \
                forceOverwrite=True, sequenceTime=0, clearCache=False, viewer=False, showOrnaments=True, \
                offScreen=True, fp=4, percent=100, compression=ext, widthHeight=(widthHeight[0],widthHeight[1]), quality=100)
    try:
        right.attr('overscan').lock()
        right.attr('displayResolution').lock()
    except:
        pass

    cleanPlayblastWindow(ui, renderers)
    
    #stereo_pb_continue = False

    print left_img
    print right_img
    # the returned filename is formated as path/image_name.####.ext
    return [cf.osPathConvert(left_img), cf.osPathConvert(right_img)]
Пример #33
0
    def _do_playblast(self):

        MODEL_EDITOR_PARAMS = {
            "activeView": True,
            "cameras": False,
            "controlVertices": False,
            "deformers": False,
            "dimensions": False,
            "displayAppearance": "smoothShaded",
            "displayLights": "default",
            "displayTextures": True,
            "dynamicConstraints": False,
            "fogging": False,
            "follicles": False,
            "grid": False,
            "handles": False,
            "headsUpDisplay": True,
            "hulls": False,
            "ignorePanZoom": False,
            "ikHandles": False,
            "imagePlane": True,
            "joints": False,
            "lights": False,
            "locators": False,
            "manipulators": False,
            "nurbsCurves": False,
            "nurbsSurfaces": True,
            "pivots": False,
            "planes": False,
            "selectionHiliteDisplay": False,
            "shadows": False,
            "sortTransparent": True,
            "strokes": True,
            "textures": True,
            "useDefaultMaterial": False,
            "wireframeOnShaded": False,
        }

        windowName = "review_blast"

        try:
            _current_panel = pm.getPanel(wf=True)
            if pm.modelEditor(_current_panel, q=True, fogging=True) == True:
                MODEL_EDITOR_PARAMS["fogging"] = True
        except:
            pass

        try:
            if pm.windowPref(windowName, exists=True):
                pm.windowPref(windowName, remove=True)
                pm.deleteUI(windowName)
        except:
            pass

        _window = pm.window(windowName,
                            titleBar=True,
                            iconify=True,
                            leftEdge=100,
                            topEdge=100,
                            width=800,
                            height=600,
                            sizeable=False)

        _layout = pm.formLayout()
        _editor = pm.modelEditor(**MODEL_EDITOR_PARAMS)

        pm.formLayout(_layout,
                      edit=True,
                      attachForm=((_editor, "left", 0), (_editor, "top", 0),
                                  (_editor, "right", 0), (_editor, "bottom",
                                                          0)))

        # Legacy viewport used
        try:
            mel.eval("setRendererInModelPanel ogsRenderer {};".format(_editor))
        except:
            cmds.confirmDialog(
                message=
                'You need to change your viewport as the legacy version',
                dismissString='No')

        # viewport 2.0 used
        # mel.eval( "setRendererInModelPanel \"vp2Renderer\" {};".format( _editor))

        pm.setFocus(_editor)
        pm.lookThru(_editor, self._shot_cam)

        cmds.refresh()

        _labelColor = cmds.displayColor('headsUpDisplayLabels',
                                        q=True,
                                        dormant=True)
        _labelValue = cmds.displayColor('headsUpDisplayValues',
                                        q=True,
                                        dormant=True)

        visibleHUDs = [
            f for f in pm.headsUpDisplay(listHeadsUpDisplays=True)
            if pm.headsUpDisplay(f, query=True, visible=True)
        ]
        map(lambda f: pm.headsUpDisplay(f, edit=True, visible=False),
            visibleHUDs)

        for h in pm.headsUpDisplay(listHeadsUpDisplays=True):
            if pm.headsUpDisplay(h, q=1, s=1) == 7:
                if pm.headsUpDisplay(h, q=1, b=1) == 5:
                    try:
                        pm.headsUpDisplay(h, rem=True)
                    except:
                        pass

        for h in pm.headsUpDisplay(listHeadsUpDisplays=True):
            if pm.headsUpDisplay(h, q=1, s=1) == 7:
                if pm.headsUpDisplay(h, q=1, b=1) == 6:
                    try:
                        pm.headsUpDisplay(h, rem=True)
                    except:
                        pass

        cmds.displayColor('headsUpDisplayValues', 17, dormant=True)
        cmds.displayColor('headsUpDisplayLabels', 16, dormant=True)

        def hudShot():
            _nameTemp = cmds.file(q=1, ns=1).split(".")[0]
            return _nameTemp.rsplit("_", 1)[0]

        def hudName():
            return getpass.getuser()

        pm.headsUpDisplay('HUDCurrentFrame',
                          edit=True,
                          visible=True,
                          labelFontSize="large",
                          dataFontSize="large",
                          section=5,
                          block=1)
        #cmds.headsUpDisplay('HUDA',s=7,b=6, blockAlignment='center', dataFontSize='large', command=hudShot)
        #cmds.headsUpDisplay('HUDB',s=7,b=5, blockAlignment='center', dataFontSize='large', label="Artist:", labelFontSize="large", command=hudName)

        pm.setFocus(_editor)

        #if pm.headsUpDisplay('HUDCurrentFrame', query=True, visible=False):
        #    print "works 111"
        #    pass
        #else:
        _mov_file = os.path.splitext(self._file)[0]
        # print _mov_file
        # __audios = pm.ls(type="audio")
        __audios = pm.ls(type="audio")

        if len(__audios) > 0:
            __audio = str(__audios[0])
        else:
            __audio = False

        # frame catching min, max, current
        _min_frame = pm.playbackOptions(q=1, min=1)
        _max_frame = pm.playbackOptions(q=1, max=1)
        _current_frame = pm.currentTime(q=1)
        pm.currentTime(_min_frame)

        ### playblast option ###
        # play_args = "playblast -format avfoundation -filename \"{}\" -sound \"{}\" -sequenceTime 0 -clearCache 1 -viewer 1 -forceOverwrite -showOrnaments 1 -offScreen -fp 4 -percent 100 -compression \"H.264\" -quality 70 -widthHeight {} {};".format( self._file, __audio, self.resolution_size[0], self.resolution_size[1])

        try:

            _temp_path, _temp_file = os.path.split(self._file)
            _temp_mov_path = _temp_path + "/.temp"

            _temp_file_01 = os.path.splitext(_temp_file)
            _temp_mov_file = _temp_file_01[0] + "_uncomp" + _temp_file_01[1]

            _full_temp_mov_file = os.path.join(_temp_mov_path, _temp_mov_file)

            print _full_temp_mov_file

            try:
                if not os.path.exists(_temp_mov_path):
                    os.makedirs(_temp_mov_path)

                if os.path.exists(_full_temp_mov_file):
                    os.remove(_full_temp_mov_file)
            except:
                raise

            ### making playblast
            play_args = "playblast -format qt -filename \"{}\" -sound \"{}\" -sequenceTime 0 -clearCache 1 -viewer 0 -showOrnaments 1 -compression \"H.264\" -offScreen -fp 4 -percent 100 -quality 100 -widthHeight {} {};".format(
                _full_temp_mov_file, __audio, self.resolution_size[0],
                self.resolution_size[1])
            mel.eval(play_args)
            pm.currentTime(_current_frame)

            sceneName = pm.sceneName()
            tk = sgtk.sgtk_from_path(sceneName)

            # get entity information
            _context = tk.context_from_path(sceneName)

            _date = datetime.date.today()
            _task = _context.step["name"]
            _shot_name = _context.entity["name"]
            _png_file = os.path.normpath(
                _temp_mov_path + "/" +
                _context.user["name"].translate(None, string.whitespace) +
                ".png")

            try:
                if not os.path.exists(_temp_mov_path):
                    os.makedirs(_temp_mov_path)

                if os.path.exists(_png_file):
                    os.remove(_png_file)
            except:
                raise

            ### write information on png file ###
            _copylight = "Copyright (C) {} JibJab Studios - All Rights Reserved".format(
                _date.year)
            _img = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0))
            _slate_image = ImageDraw.Draw(_img)
            _type_shot_asset = ImageFont.truetype('/Library/Fonts/arial.ttf',
                                                  30)
            _type_copyright = ImageFont.truetype('/Library/Fonts/arial.ttf',
                                                 15)
            _type_task = ImageFont.truetype('/Library/Fonts/arial.ttf', 18)

            _slate_image.text((820, 1000),
                              _shot_name,
                              font=_type_shot_asset,
                              fill=(255, 255, 255, 128))
            _slate_image.text((780, 1060),
                              _copylight,
                              font=_type_copyright,
                              fill=(255, 255, 255, 128))
            _slate_image.text((910, 1035),
                              "Task : {}".format(_task),
                              font=_type_task,
                              fill=(255, 255, 255, 128))
            # _slate_image.text((1610, 1060), _review_file, font=_type_copyright, fill=(255,255,255,80))

            _img.save(_png_file, 'PNG')

            ### convert uncomppresed file to h.264
            #t = os.system("/Volumes/public/StoryBots/production/series/ask_the_storybots/03_shared_assets/01_cg/05_maya_tools/pipeline/module/ffmpeg/ffmpeg -y -i " + _full_temp_mov_file + " -vcodec libx264 -pix_fmt yuv420p -preset slower -crf 0 -vf eq=brightness=0.04 -g 1 -acodec copy " + self._file)
            t = os.system(
                "/Volumes/public/StoryBots/production/series/ask_the_storybots/03_shared_assets/01_cg/05_maya_tools/pipeline/module/ffmpeg/ffmpeg -y -i "
                + _full_temp_mov_file + " -i " + _png_file +
                " -vcodec libx264 -pix_fmt yuv420p -preset slow -crf 22 -filter_complex \"overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2\" -g 0 -acodec copy "
                + self._file)
            ######################################
            #### This is RV open with mov file ###
            ######################################

            _mov_path_RV, _mov_file_RV = os.path.split(self._file)
            os.chdir(_mov_path_RV)
            subprocess.Popen(self._RV_path + _mov_file_RV, shell=True)

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

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

        except:
            pm.confirmDialog(
                title="Playblast Error",
                message=
                "Close your RV or deselect the file.\nYour file is being used from other application",
                defaultButton="Yes")
            raise

        # playblast  -format avfoundation -sound "ATS_301_sq020_020" -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 0 -offScreen  -fp 4 -percent 80 -compression "H.264" -quality 70 -widthHeight 1920 1080;
        #pm.showWindow( _window )
        pm.headsUpDisplay('HUDCurrentFrame',
                          edit=True,
                          visible=False,
                          section=5,
                          block=1)
        # cmds.headsUpDisplay( 'HUDA', rem=True )
        # cmds.headsUpDisplay( 'HUDB', rem=True )
        # delete playblast window
        pm.deleteUI(_window)
        # revive HOD modes

        cmds.displayColor('headsUpDisplayValues', _labelColor, dormant=True)
        cmds.displayColor('headsUpDisplayLabels', _labelValue, dormant=True)
        map(lambda f: pm.headsUpDisplay(f, edit=True, visible=True),
            visibleHUDs)
Пример #34
0
def switchCam(cam):
    pc.lookThru(cam)
    sel = pc.ls(sl=True)
    pc.select(cam)
    fillinout.fill()
    pc.select(sel)