def bs_removeHeadsUpDisplay(): """ @ remove headsUpDisplay and also delete expressions. Returns: None. """ # remove all headsUpDisplay. if pm.windows.headsUpDisplay(lh=True): for each in pm.windows.headsUpDisplay(lh=True): pm.windows.headsUpDisplay(each, rem=True) # remove resolution gates. shotCam = pm.PyNode('shot_cam') # add resolution gates. pm.camera(shotCam, e=True, dsa=False, dfc=False, displayFilmGate=False, displayResolution=False, displaySafeTitle=False) pm.setAttr(shotCam + '.displayGateMaskOpacity', 0) pm.setAttr(shotCam + '.displayGateMaskColor', [0, 0, 0], type='double3') pm.setAttr(shotCam + '.displayGateMask', 0) # delete expression. pm.delete('focalLengthUpdateEXP') pm.delete('frameCounterUpdateEXP')
def set_attr_for_pb(cameraShape): '''set camera attributes for playblast ''' pm.camera(cameraShape, e=1, displayFilmGate=0, displayResolution=0, overscan=1.0)
def camera_option_list(self, menu, *args): #clear array and optionMenu del self.listOfCameras[:] menu.clear() self.listOfCameras = [i for i in pm.ls(cameras=True)] for item in self.listOfCameras: ca = pm.camera(item, query=True, name=True) pm.menuItem(l=pm.camera(item, query=True, name=True), parent=menu)
def set_camera_background(self, camera_node=None, panel_node=None): if panel_node is None: panel_node = self.get_selected_panel() pmc.modelPanel(panel_node, edit=True, camera=camera_node) if camera_node is None: camera_node = self.get_selected_camera() self.draw_background(camera_node) pmc.camera(camera_node, edit=True, displayFilmGate=False, displayResolution=True, overscan=1.3)
def testSetRenderLayer(self): cam1 = pmc.camera()[0] defaultlayer = pmc.nodetypes.RenderLayer.defaultRenderLayer() newlayer = pmc.createRenderLayer() defaultlayer.setCurrent() with render_layer_active(newlayer): cam2 = pmc.camera()[0] self.assertEqual(pmc.nodetypes.RenderLayer.currentLayer(), newlayer) self.assertEqual(pmc.nodetypes.RenderLayer.currentLayer(), defaultlayer) self.assertTrue(defaultlayer.inLayer(cam1)) self.assertTrue(newlayer.inLayer(cam2))
def get_cam(self): cams= cmds.ls(cameras=1) print cams cams_standard = set(["perspShape","frontShape","sideShape","topShape"]) cam = list( set(cams) - cams_standard ) if not cam: cam = ["perspShape"] self.Cam = cam[0] print self.Cam # set camera attr #camera -e -displayFilmGate off -displayResolution off -overscan 1.0 $cams[0]; pm.camera(self.Cam,e=1,displayFilmGate=0,displayResolution=0,overscan=1.0)
def bs_playblast(): """ @ create playblast with headsUpDisplays. Returns: playblastPath. """ bs_addHeadsUpDisplay() epi, seq, shot, stage = bs_pathGenerator.bs_shotDetailsCheckAndReturn() outPath = bs_pathGenerator.bs_animFilePath(epi, seq, shot)[stage][:-3] shotCam = pm.PyNode('shot_cam') # add resolution gates. pm.camera(shotCam, e=True, filmFit='overscan') pm.camera(shotCam, e=True, dsa=True, dfc=False, displayFilmGate=False, displayResolution=True, displaySafeTitle=False) pm.setAttr(shotCam + '.displayGateMaskOpacity', 1) pm.setAttr(shotCam + '.displayGateMaskColor', [0, 0, 0], type='double3') pm.setAttr(shotCam + '.displayGateMask', 1) # get Sound File. soundFile = pm.windows.timeControl('timeControl1', q=True, s=True) # playblast. if soundFile: vidPath = pm.playblast(f=outPath, format='avi', s=soundFile, sequenceTime=0, forceOverwrite=True, clearCache=1, viewer=1, showOrnaments=1, fp=4, percent=100, quality=70, widthHeight=[960, 540]) else: vidPath = pm.playblast(f=outPath, format='avi', sequenceTime=0, forceOverwrite=True, clearCache=1, viewer=1, showOrnaments=1, fp=4, percent=100, quality=70, widthHeight=[960, 540]) bs_removeHeadsUpDisplay() bs_qui.bs_displayMessage('success', '{0}'.format(vidPath)) return vidPath
def test_get_meshes_in_selection_should_only_return_meshes(): import pymel.core as pm from arnold_subdiv_manager.maya_abstraction_implementation import ( MayaAbstractionImplementation, ) pm.newFile(f=True) pm.camera() pm.polyCube() pm.select(["pCube1", "camera1"]) maya_abstraction = MayaAbstractionImplementation() meshes = maya_abstraction.get_meshes_in_selection() assert meshes == [Mesh("|pCube1")]
def test_get_meshes_in_selection_should_handle_shapes_correctly(): import pymel.core as pm from arnold_subdiv_manager.maya_abstraction_implementation import ( MayaAbstractionImplementation, ) pm.newFile(f=True) pm.camera() pm.polyCube() pm.select(["|pCube1|pCubeShape1", "|pCube1"]) maya_abstraction = MayaAbstractionImplementation() meshes = maya_abstraction.get_meshes_in_selection() assert meshes == [Mesh("|pCube1|pCubeShape1"), Mesh("|pCube1")]
def clean_reference_cameras(): ''' Default cameras from referenced scenes can get into animation scenes. This finds them, unflags their default status, and deletes them ''' for cam in pm.ls(type = "camera"): try: topParent = cam.getParent(generations = -1) isStartUp = pm.camera(cam, q = True, startupCamera = True) if topParent.isReferenced() and isStartUp: pm.camera(cam, e = True, startupCamera = False) pm.delete(cam.getParent()) except: continue
def fixedCamera(render_cam, frame): ''' Create an fgshooter camera fixed at the render camera's position for a spcified frame. ''' # Not the best way to get the world position and rotation values out of the render_camera... but it works. # Pymel's matrix.rotate and matrix.getRotation() seem to be broken. tmp_node = pm.createNode("decomposeMatrix") render_cam.worldMatrix >> tmp_node.inputMatrix frame_position = [tmp_node.outputTranslateX.get(time = frame), tmp_node.outputTranslateY.get(time = frame), tmp_node.outputTranslateZ.get(time = frame)] frame_rotation = [tmp_node.outputRotateX.get(time = frame), tmp_node.outputRotateY.get(time = frame), tmp_node.outputRotateZ.get(time = frame)] pm.delete(tmp_node) # Create the fixed camera. Change it's wireframe color. fg_cam, fg_cam_shape = pm.camera(name="fgshooterCamera", position=frame_position, rotation=frame_rotation) pm.color(fg_cam, ud=2) # Adjust the fgshooter camera's scale to pass aperture, aspect, and focal length information. aperture = render_cam.horizontalFilmAperture.get(time = frame) aspect = aperture / pm.Attribute("defaultResolution.deviceAspectRatio").get(time = frame) focal = 0.03937 * render_cam.focalLength.get(time = frame) fg_cam.scaleX.set(aperture) fg_cam.scaleY.set(aspect) fg_cam.scaleZ.set(focal) return fg_cam_shape
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)
def setCamera(self): 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])
def makeNull(): #pm.melGlobals.initVar( 'string[]', 'KinectSkelNames' ) i = 0 for i in range(0, 24): pm.spaceLocator(p=(0, 0, 0), n=KinectSkelNames[i]) pm.spaceLocator(p=(0, 0, 0), n="KINECT_HAND") for i in range(0, 15): point[i] = [0.0, 0.0, 0.0] makeSkel() for i in range(0, 15): pm.rename('joint' + str(i + 1), KinectSkelJoints[i] + '_jt') for i in range(0, 15): pm.pointConstraint(KinectSkelJoints[i], KinectSkelJoints[i] + '_jt') pm.orientConstraint(KinectSkelJoints[i], KinectSkelJoints[i] + '_jt') #Create Camera cam = pm.camera()[1] #print pm.camera(cam, query=True, aspectRatio=True) cam.setAspectRatio(3) print cam.getAspectRatio()
def createHighlight(mesh, lightType=mayaLights["Spot"], offset=6): """ Create Light based on curve drawn on object """ # Get the currently selected curve curveA = getSelection() # Get the start and end points of the curve as Vectors crv_posA = dt.Vector(pm.pointOnCurve(curveA, pr=0)) crv_posB = dt.Vector(pm.pointOnCurve(curveA, pr=curveA.maxValue.get())) # Calculate the mid point midPoint = (crv_posA + crv_posB) / 2 # Get closest point & normal on mesh pointOnMesh_set = mesh.getClosestPointAndNormal(midPoint, space="world") pointOnMesh = pointOnMesh_set[0] pointOnMesh_normal = pointOnMesh_set[1] pm.spaceLocator(p=pointOnMesh) # For debug/vis # Create dummy camera cam = pm.camera() camera = cam[0] camera.setTranslation(pointOnMesh + pointOnMesh_normal * offset) pm.viewLookAt(camera, pos=pointOnMesh) # Create light createLight(lightType, camera.getTranslation(), camera.getRotation()) # Delete dummy camera pm.delete(camera)
def makeNull(): #pm.melGlobals.initVar( 'string[]', 'KinectSkelNames' ) i=0 for i in range(0,24): pm.spaceLocator(p=(0, 0, 0),n=KinectSkelNames[i]) pm.spaceLocator(p=(0, 0, 0),n="KINECT_HAND") for i in range(0,15): point[i] = [0.0,0.0,0.0] makeSkel() for i in range(0,15): pm.rename('joint'+str(i+1), KinectSkelJoints[i]+'_jt') for i in range(0,15): pm.pointConstraint( KinectSkelJoints[i], KinectSkelJoints[i]+'_jt' ) pm.orientConstraint( KinectSkelJoints[i], KinectSkelJoints[i]+'_jt' ) #Create Camera cam = pm.camera()[1] #print pm.camera(cam, query=True, aspectRatio=True) cam.setAspectRatio(3) print cam.getAspectRatio()
def setCamera(self): 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])
def get_cam(self): cams = cmds.ls(cameras=1) print cams cams_standard = set( ["perspShape", "frontShape", "sideShape", "topShape"]) cam = list(set(cams) - cams_standard) if not cam: cam = ["perspShape"] self.Cam = cam[0] print self.Cam # set camera attr #camera -e -displayFilmGate off -displayResolution off -overscan 1.0 $cams[0]; pm.camera(self.Cam, e=1, displayFilmGate=0, displayResolution=0, overscan=1.0)
def fix_cams(ratio='16/9'): ratio = ratio.split('/') if len(ratio) > 2: raise ValueError('Enter a valid ratio, like 4/3, 16/9...') w = float(ratio[0]) h = float(ratio[-1]) ratio = w / h import pymel.core as pmc cams = pmc.ls(cameras=True) for cam in cams: pmc.camera(cam, e=True, ar=ratio) return cams
def newCamera(self): sel = pm.selected() c = pm.camera(n='iconCaptureCamera')[0] pm.viewSet(c, home=True) c.focalLength.set(150) pm.select(sel) pm.viewSet(c, fit=True) return c
def camConstraint(self): #making no-aim camera self.cameraShapeRename() newCamGrp = pm.camera() #creating camera newCamShape = newCamGrp[1] #declaring camera shape pm.xform(newCamGrp[0], rotateOrder = 'zxy')#changing rotation order so I can add the camera roll later pm.camera(newCamShape, edit = True, fl = pm.camera('cameraShape1', q = True, fl = True), coi = pm.camera('cameraShape1', q = True, coi = True) ) #adjusting attributes of camera shape pm.setAttr(newCamShape.filmFit, 2) pm.copyKey('cameraShape1', time = (animAPI.MAnimControl.minTime().value(), animAPI.MAnimControl.maxTime().value()), option = 'curve')#copying of camera shape keys try: pm.pasteKey(newCamShape) #pasting except: print('camShape has no keys') pm.parentConstraint('camera1', newCamGrp[0], mo = False) #constraining camera pm.bakeResults(newCamGrp[0], simulation = True, time = (animAPI.MAnimControl.minTime().value(), animAPI.MAnimControl.maxTime().value()) )#baking the movement into the camera pm.keyframe(newCamGrp[0].rotateZ, edit = True, animation = 'objects', relative = True, valueChange = pm.camera('cameraShape1', q = True, filmRollValue = True) ) #adding the roll to the camera rotateZ pm.select(newCamGrp)
def shotAssemble(partField, sequenceField, shotField, listPhase, act): # New scene pm.newFile(f=True) # Extract SHOT NUMBER from UI codePart = partField.getText() codeSequence = sequenceField.getText() codeShot = shotField.getText() # Build SHOT DICTIONARY from FTrack data dataShotDic = dna.buildShotDic(codePart, codeSequence, 'SHOT_{0}'.format(codeShot)) listChars = dataShotDic['characters'] listProps = dataShotDic['props'] listEDA = dataShotDic['eda'] listEnv = dataShotDic['environments'] # START ASSEMBLING for action in act: if action == 'save': fileNameFull = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format( rootScene, listPhase[1], codePart, codeSequence, codeShot, listPhase[2]) dna.exportFileLV(fileNameFull) # Save scene dna.rangeSetup(codePart, codeSequence, codeShot) # PLAYBACK START/END RANGE SETUP dna.setRes() # Setup RESOLUTION elif action == 'add assets': dna.referenceItems( listChars, listPhase[0] ) # reference ( list of CHARS, RIG-GEO triger, asset type) print ' << CHARACTERS DONE! >>' dna.referenceItems(listProps, listPhase[0]) # REF PROPS print ' << PROPS DONE! >>' if listEnv: dna.referenceItems(listEnv, 'GEO') # REF ENVIRONMENT print ' << ENVIRONMENNT DONE! >>' if listEDA[0]: print listEDA dna.referenceItems(listEDA, listPhase[0]) # REF EDA print ' << EDA DONE! >>' elif action == 'create camera': cam = pm.camera() camName = 'E' + codeSequence + '_S' + codeShot cam[0].rename(camName) cam[1].rename(str(camName) + 'Shape') dna.camSetup(cam[1]) elif action == 'add ML': for i in listChars: matPath = dna.buildItemFullPath(i, 'MAT') dna.importData(matPath) # IMPORT ML for CHAR print '<< IMPORTED MATERIAL FOR: {} >>'.format(i) if listEnv: matPath = dna.buildItemFullPath(listEnv[0], 'MAT') dna.importData(matPath) # IMPORT ML for ENV print '<< IMPORTED MATERIAL FOR: {} >>'.format(listEnv[0]) # SAVE SCENE pm.saveFile() # CREATE REPORT print 'ASSEMBLING DONE!'
def create_camera_and_plane(json_path, image_path): """ Create a camera and image plane given a json with data generated from fSpy. :param str json_path: full path to the json. :param str image_path: full or relative path to the image to use. :return: A dictionary containing the newly created nodes in the following format: {'camera': (camera_transform, camera_shape), 'image_plane': (image_transform, image_shape), 'root': group} :rtype: dict """ with open(json_path) as json_file: data = json.load(json_file) # Group for all the created items. group = pm.group(em=True, n='projected_camera_grp_001') # Applying the matrix transformations onto a camera matrix_rows = [['in00', 'in10', 'in20', 'in30'], ['in01', 'in11', 'in21', 'in31'], ['in02', 'in12', 'in22', 'in32'], ['in03', 'in13', 'in23', 'in33']] # Creating a camera, 4x4 matrix and decompose-matrix, then setting up the connections. camera_transform, camera_shape = pm.camera() pm.parent(camera_transform, group) matrix = pm.createNode('fourByFourMatrix', n='cameraTransform_fourByFourMatrix') decompose_matrix = pm.createNode('decomposeMatrix', n='cameraTransform_decomposeMatrix') pm.connectAttr(matrix.output, decompose_matrix.inputMatrix) pm.connectAttr(decompose_matrix.outputTranslate, camera_transform.translate) pm.connectAttr(decompose_matrix.outputRotate, camera_transform.rotate) # Setting the matrix attrs onto the 4x4 matrix. for i, matrix_list in enumerate(data['cameraTransform']['rows']): for value, attr in zip(matrix_list, matrix_rows[i]): pm.setAttr(matrix.attr(attr), value) # creating an image plane for the camera image_transform, image_shape = pm.imagePlane(camera=camera_transform) pm.setAttr(image_shape.imageName, image_path, type='string') # Cleanup pm.delete([matrix, decompose_matrix]) for attr in ['translate', 'rotate', 'scale']: for ax in ['X', 'Y', 'Z']: camera_transform.attr(attr + ax).lock() image_transform.attr(attr + ax).lock() # Returning all the newly created items in case someone wants to grab and use them later. return { 'camera': (camera_transform, camera_shape), 'image_plane': (image_transform, image_shape), 'root': group }
def getCamera(): cameras = pm.ls(type='camera', l=True) startup_cameras = [ camera for camera in cameras if pm.camera(camera.parent(0), startupCamera=True, q=True) ] cameraShape = list(set(cameras) - set(startup_cameras)) camera = map(lambda x: x.parent(0), cameraShape)[0] return camera
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
def model_screenshot(selected=True, debug=False, centerCam=False): meshes = pm.ls(sl=True) cam = pm.camera(n='tempCam') hfv=cam[1].getHorizontalFieldOfView() vfv=cam[1].getVerticalFieldOfView() grp = pm.group(em=True, n='tempCamOffset_GRP') #Determine the selection if selected==False: meshes = [mesh.getParent() for mesh in pm.ls(type=pm.nt.Mesh)] print meshes boundingBox = pm.polyEvaluate(meshes, b=True) #Determine the positions of the bounding box as variables xmin=boundingBox[0][0] xmax=boundingBox[0][1] ymin=boundingBox[1][0] ymax=boundingBox[1][1] zmin=boundingBox[2][0] zmax=boundingBox[2][1] #get the midpoints (these are also the object center!) zmid=(zmin+zmax)/2 ymid=(ymin+ymax)/2 xmid=(xmin+xmax)/2 # Create locators to visualize the bounding box locators=[] locators.append(pm.spaceLocator(n='xmin',p=[xmin,ymid,zmid])) locators.append(pm.spaceLocator(n='xmax',p=[xmax,ymid,zmid])) locators.append(pm.spaceLocator(n='ymin',p=[xmid,ymin,zmid])) locators.append(pm.spaceLocator(n='ymax',p=[xmid,ymax,zmid])) locators.append(pm.spaceLocator(n='zmin',p=[xmid,ymid,zmin])) locators.append(pm.spaceLocator(n='zmax',p=[xmid,ymid,zmax])) #Determine the furthest distance needed from the object h_dist=(math.tan(hfv)*abs(xmin-xmax)) + abs(zmin-zmax) zh_dist=(math.tan(vfv)*abs(zmin-zmax)) + abs(zmin-zmax) zv_dist=(math.tan(vfv)*abs(zmin-zmax)) + abs(zmin-zmax) v_dist=(math.tan(vfv)*abs(ymin-ymax)) + abs(zmin-zmax) #this will never be used, always going to be shortest. #set the camera distance etc for the bounding box. print h_dist,v_dist,zh_dist, zv_dist print max(h_dist,v_dist,zh_dist, zv_dist) cam[0].translateZ.set(max(h_dist,zh_dist,v_dist,zv_dist)) cam[0].translateY.set(ymid) cam[0].setParent(grp) if debug: pm.delete(locators) if centerCam: grp.translate.set([zmid,0,xmid]) pm.setKeyframe(grp.rotateY, t=pm.playbackOptions(q=True,ast=True), v=0) pm.setKeyframe(grp.rotateY, t=pm.playbackOptions(q=True,aet=True), v=360)
def getEditor(): """ The modelEditor is the node in maya that contains all the information about a modelPanel. A panel is an object in maya that acts as the root of a ui element. The model editor for instance holds information about what cameras have been added to a panel. """ if pm.modelEditor("mypanel", exists=True): print("the panel exists...deleting and creating a new one") pm.deleteUI("mypanel") cam = pm.ls(selection=True)[0] #SETTING CAMERA VIEWPORT SETTINGS pm.camera(cam, edit=True, displayResolution=False, displayFilmGate=False) window = pm.window(width=1280, height=720, backgroundColor=(1.0, 0.0, 0.0)) lay = pm.paneLayout() pan = pm.modelPanel() pm.modelEditor("mypanel", camera=cam, activeView=True, displayAppearance="smoothShaded") pm.showWindow(window, window=True)
def shotAssemble(partField, sequenceField, shotField, listPhase, act ): # New scene pm.newFile(f = True) # Extract SHOT NUMBER from UI codePart = partField.getText() codeSequence = sequenceField.getText() codeShot = shotField.getText() # Build SHOT DICTIONARY from FTrack data dataShotDic = dna.buildShotDic( codePart, codeSequence, 'SHOT_{0}'.format(codeShot)) listChars = dataShotDic['characters'] listProps = dataShotDic['props'] listEDA = dataShotDic['eda'] listEnv = dataShotDic['environments'] # START ASSEMBLING for action in act: if action == 'save': fileNameFull = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format(rootScene, listPhase[1], codePart, codeSequence, codeShot, listPhase[2]) dna.exportFileLV( fileNameFull ) # Save scene dna.rangeSetup(codePart, codeSequence, codeShot) # PLAYBACK START/END RANGE SETUP dna.setRes() # Setup RESOLUTION elif action == 'add assets': dna.referenceItems(listChars, listPhase[0]) # reference ( list of CHARS, RIG-GEO triger, asset type) print ' << CHARACTERS DONE! >>' dna.referenceItems(listProps, listPhase[0]) # REF PROPS print ' << PROPS DONE! >>' if listEnv: dna.referenceItems(listEnv, 'GEO' ) # REF ENVIRONMENT print ' << ENVIRONMENNT DONE! >>' if listEDA[0]: print listEDA dna.referenceItems(listEDA, listPhase[0] ) # REF EDA print ' << EDA DONE! >>' elif action == 'create camera': cam = pm.camera() camName = 'E' + codeSequence + '_S' + codeShot cam[0].rename(camName) cam[1].rename(str(camName) + 'Shape') dna.camSetup(cam[1]) elif action == 'add ML': for i in listChars: matPath = dna.buildItemFullPath(i, 'MAT') dna.importData(matPath) # IMPORT ML for CHAR print '<< IMPORTED MATERIAL FOR: {} >>'.format(i) if listEnv: matPath = dna.buildItemFullPath(listEnv[0], 'MAT') dna.importData(matPath) # IMPORT ML for ENV print '<< IMPORTED MATERIAL FOR: {} >>'.format( listEnv[0] ) # SAVE SCENE pm.saveFile() # CREATE REPORT print 'ASSEMBLING DONE!'
def wrapData(self): """ Get the camera name from the scene :return: """ cameras = pm.ls(type='camera', l=True) startup_cameras = [camera for camera in cameras if pm.camera(camera.parent (0), startupCamera=True, q=True)] cameraShape = list(set(cameras) - set(startup_cameras)) if not cameraShape: return None camera = map(lambda x: x.parent(0), cameraShape)[0] self.cameraTransform = camera
def turnResolutionGateOff(camera): global __resolutionGate__ global __safeAction__ global __safeTitle__ if not __resolutionGate__: pc.camera(camera, e=True, displayResolution=False, overscan=1.0) __resolutionGate__ = True if not __safeAction__: pc.camera(camera, e=True, displaySafeAction=True, overscan=1.0) __safeAction__ = True if not __safeTitle__: pc.camera(camera, e=True, displaySafeTitle=True, overscan=1.0) __safeTitle__ = True if not __resolutionGateMask__: pc.camera(camera, e=True, dgm=False, overscan=1.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 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 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)
def makeCamera(*args): #set render resolution mc.setAttr('defaultResolution.height', UI.resolution) mc.setAttr('defaultResolution.width', UI.resolution) #square image - 1/1 ratio for no distortion mc.setAttr('defaultResolution.deviceAspectRatio', 1) #makeCamera.cam makeCamera.cam = pm.camera(dof=True, ar=1, fd=10) #mc.setAttr(camera1.translateZ, 45); mel.eval('setAttr "camera1.translateZ" 45;') #dir light pm.directionalLight(intensity=0.8) #mel.eval('renderWindowRender redoPreviousRender renderView') makeCamera.editor = 'renderView' #try to str(cam[0]) later instead of 'cameraShape1' mc.lookThru('perspView', 'cameraShape1')
def cam_to_chan(start_frame, end_frame): """Exports maya camera to nuke Select camera to export and call cam2Chan(startFrame, endFrame) :param start_frame: start frame :param end_frame: end frame :return: """ selection = pm.ls(sl=1) chan_file = pm.fileDialog2(cap="Save", fm=0, ff="(*.chan)")[0] camera = selection[0] template = "%(frame)s\t%(posx)s\t%(posy)s\t%(posz)s\t" \ "%(rotx)s\t%(roty)s\t%(rotz)s\t%(vfv)s" lines = [] for i in range(start_frame, end_frame + 1): pm.currentTime(i, e=True) pos = pm.xform(camera, q=True, ws=True, t=True) rot = pm.xform(camera, q=True, ws=True, ro=True) vfv = pm.camera(camera, q=True, vfv=True) lines.append( template % { 'frame': i, 'posx': pos[0], 'posy': pos[1], 'posz': pos[2], 'rotx': rot[0], 'roty': rot[1], 'rotz': rot[2], 'vfv': vfv } ) with open(chan_file, 'w') as f: f.writelines('\n'.join(lines))
def createFallowCam( ): ''' 캐릭터를 따라다니는 카메라 생성 ''' # 선택한 물체에서 네임 스페이스 얻어옴. ns = '' sel = pm.selected() if sel: ns = sel[0].namespace() # 컨스트레인 걸 대상 리스트 확보 jnts = ['Hips','Spine*','*Leg','*Foot'] #jnts = ['Spine*','*Foot'] targets = [] for j in jnts: targets.extend( pm.ls( ns + j, exactType='joint' ) ) # 확보 안됨 끝. if not targets: print u'캐릭터의 일부를 선택하세요.' return # 카메라와 그룹 생성 cam = pm.camera(n='followCam')[0] grp = pm.group( cam, n='followCam_grp' ) # 컨스트레인 const = pm.pointConstraint( targets, grp ); pm.delete(const) # 우선 위치에 배치하고 #pm.pointConstraint( targets, grp, skip='y' ) # 컨스트레인 pm.pointConstraint( targets, grp ) # 컨스트레인 # 카메라 조정 cam.tz.set(1200) cam.focalLength.set(100) cam.centerOfInterest.set(1200) cam.filmFit.set(2) # vertical # 패널 조정 activePanel = pm.playblast( activeEditor=True ).split('|')[-1] pm.modelPanel( activePanel, edit=True, camera=cam )
def getCameras(): # Get all cameras first cameras = pm.ls(type=('camera'), l=True) # Let's filter all startup / default cameras startup_cameras = [ camera for camera in cameras if pm.camera(camera.parent(0), startupCamera=True, q=True) ] # non-default cameras are easy to find now. Please note that these are all PyNodes non_startup_cameras_pynodes = list(set(cameras) - set(startup_cameras)) # Let's get their respective transform names, just in-case non_startup_cameras_transform_pynodes = map(lambda x: x.parent(0), non_startup_cameras_pynodes) # Now we can have a non-PyNode, regular string names list of them non_startup_cameras = map(str, non_startup_cameras_pynodes) non_startup_cameras_transforms = map( str, non_startup_cameras_transform_pynodes) return non_startup_cameras_transforms
def aimCamMake(self): #will be deprecated self.cameraShapeRename() aimCam = pm.camera(coi = 5, fl = 35, lsr = 1, cs = 1, hfa = 1.41732, hfo = 0, vfa = 0.94488, vfo = 0, ff = 'Fill', ovr = 1, mb = 0, sa = 144, ncp = 0.1, ow = 30, pze = False, hpn = 0, zoom = 1) pm.rename(aimCam[0], 'camera1') mel.eval('cameraMakeNode 2 "";')#creates camera with aim constr = pm.parentConstraint('camera2', 'camera1_group', mo = False) #constraining the aimCam group to old camera camLoc = pm.spaceLocator() pm.xform(camLoc, ws = True, translation = pm.xform('camera1', ws = True, q = True, translation = True)) pm.parentConstraint('camera2', camLoc, mo = True) aimLoc = pm.spaceLocator() pm.xform(aimLoc, ws = True, translation = pm.xform('camera1_aim', ws = True, q = True, translation = True)) pm.parentConstraint('camera2', aimLoc, mo = True) pm.bakeResults(camLoc, aimLoc, simulation = True, time = (animAPI.MAnimControl.minTime().value(), animAPI.MAnimControl.maxTime().value()) )#baking the movement into the camera pm.copyKey(camLoc, time = (animAPI.MAnimControl.minTime().value(), animAPI.MAnimControl.maxTime().value())) pm.pasteKey('camera1') #pasting pm.copyKey(aimLoc, time = (animAPI.MAnimControl.minTime().value(), animAPI.MAnimControl.maxTime().value())) pm.pasteKey('camera1_aim') #pasting pm.copyKey('cameraShape2', time = (animAPI.MAnimControl.minTime().value(), animAPI.MAnimControl.maxTime().value()), option = 'curve') #copying all camera focal length and stuff try: pm.pasteKey('cameraShape1') #pasting except: print('camShape has no keys') pm.setAttr('cameraShape1.filmFit', 2) pm.copyKey('camera2', time = (animAPI.MAnimControl.minTime().value(), animAPI.MAnimControl.maxTime().value()), option = 'curve', at = 'rz') #copying rotate/roll data pm.pasteKey('cameraShape1', attribute = 'filmRollValue') #pasting into roll pm.delete(constr) pm.setAttr('camera1_group.tx', 0) pm.setAttr('camera1_group.ty', 0) pm.setAttr('camera1_group.tz', 0) pm.setAttr('camera1_group.rx', 0) pm.setAttr('camera1_group.ry', 0) pm.setAttr('camera1_group.rz', 0) pm.setKeyframe('camera1_group', time = 0) print('keyed camera1_group') pm.select('camera2')
def aw_bakeCam(): '''Takes a camera, duplicates it, bakes it and then ''' localUser = os.environ[ 'USER' ] localProject=os.environ[ 'MAYA_PROJECT' ] shotName=localProject.split("/")[-2] cams=pm.ls(sl=True) #Selection error checking for cam in cams: if cam.getShape().type()=='camera': #Store and set new camera camName = (shotName + "_CAM") cam_dup=pm.camera(n=camName)[0] copyCamSettings(cam,cam_dup) secureCam(cam_dup,lock=False) #Parent Constrain pc=pm.parentConstraint(cam,cam_dup) #Set start and end frame and bake to sequence begFrame = pm.playbackOptions(q=True,ast=True) endFrame = pm.playbackOptions(q=True,aet=True) pm.bakeResults(cam_dup, sparseAnimCurveBake=False, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, preserveOutsideKeys=True, simulation=True, sampleBy=1, shape=True, t=(begFrame,endFrame), at=["tx", "ty", "tz", "rx", "ry", "rz"], disableImplicitControl=True, controlPoints=False) #Clean up and delete pm.delete(pc) attachImagePlane( cam_dup, localProject, localUser, shotName ) secureCam(cam_dup,lock=False) mpc.rig_setsCreateHubSet([pm.PyNode(cam_dup)], cam_dup, 'camera')
def fixedCamera(render_cam, frame): ''' Create an fgshooter camera fixed at the render camera's position for a spcified frame. ''' # Not the best way to get the world position and rotation values out of the render_camera... but it works. # Pymel's matrix.rotate and matrix.getRotation() seem to be broken. tmp_node = pm.createNode("decomposeMatrix") render_cam.worldMatrix >> tmp_node.inputMatrix frame_position = [ tmp_node.outputTranslateX.get(time=frame), tmp_node.outputTranslateY.get(time=frame), tmp_node.outputTranslateZ.get(time=frame) ] frame_rotation = [ tmp_node.outputRotateX.get(time=frame), tmp_node.outputRotateY.get(time=frame), tmp_node.outputRotateZ.get(time=frame) ] pm.delete(tmp_node) # Create the fixed camera. Change it's wireframe color. fg_cam, fg_cam_shape = pm.camera(name="fgshooterCamera", position=frame_position, rotation=frame_rotation) pm.color(fg_cam, ud=2) # Adjust the fgshooter camera's scale to pass aperture, aspect, and focal length information. aperture = render_cam.horizontalFilmAperture.get(time=frame) aspect = aperture / pm.Attribute( "defaultResolution.deviceAspectRatio").get(time=frame) focal = 0.03937 * render_cam.focalLength.get(time=frame) fg_cam.scaleX.set(aperture) fg_cam.scaleY.set(aspect) fg_cam.scaleZ.set(focal) return fg_cam_shape
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)
def offsetCamera(render_cam, offset): ''' Create an fgshooter camera offset from the render camera by a few frames. ''' # Create camera and change wireframe color. fg_cam, fg_cam_shape = pm.camera(name = "fgshooterCamera") pm.color(fg_cam, ud=2) # Create all the connection nodes we are going to need. decompose_matrix = pm.createNode("decomposeMatrix") multiply_divide = pm.createNode("multiplyDivide") frame_cache_tx = pm.createNode("frameCache") frame_cache_ty = pm.createNode("frameCache") frame_cache_tz = pm.createNode("frameCache") frame_cache_rx = pm.createNode("frameCache") frame_cache_ry = pm.createNode("frameCache") frame_cache_rz = pm.createNode("frameCache") frame_cache_fl = pm.createNode("frameCache") # Connect all of those nodes to the render camera. render_cam.worldMatrix >> decompose_matrix.inputMatrix decompose_matrix.outputTranslateX >> frame_cache_tx.stream decompose_matrix.outputTranslateY >> frame_cache_ty.stream decompose_matrix.outputTranslateZ >> frame_cache_tz.stream decompose_matrix.outputRotateX >> frame_cache_rx.stream decompose_matrix.outputRotateY >> frame_cache_ry.stream decompose_matrix.outputRotateZ >> frame_cache_rz.stream render_cam.focalLength >> frame_cache_fl.stream # If the offset is positive, use the future attribute. if offset > 0: # Workaround for a pymel bug offset = ".future[" + str(offset) +"]" pm.Attribute(frame_cache_tx + offset) >> fg_cam.translateX pm.Attribute(frame_cache_ty + offset) >> fg_cam.translateY pm.Attribute(frame_cache_tz + offset) >> fg_cam.translateZ pm.Attribute(frame_cache_rx + offset) >> fg_cam.rotateX pm.Attribute(frame_cache_ry + offset) >> fg_cam.rotateY pm.Attribute(frame_cache_rz + offset) >> fg_cam.rotateZ pm.Attribute(frame_cache_fl + offset) >> multiply_divide.input1X # If the offset is negative, use the past attribute. else: offset = -offset frame_cache_tx.past[offset] >> fg_cam.translateX frame_cache_ty.past[offset] >> fg_cam.translateY frame_cache_tz.past[offset] >> fg_cam.translateZ frame_cache_rx.past[offset] >> fg_cam.rotateX frame_cache_ry.past[offset] >> fg_cam.rotateY frame_cache_rz.past[offset] >> fg_cam.rotateZ frame_cache_fl.past[offset] >> multiply_divide.input1X # Pass aperture, aspect, and focal length infromation with the fgshooter camera's scale. # Focal length is connected because it could be animated. aperture = render_cam.horizontalFilmAperture.get() aspect = aperture / pm.Attribute("defaultResolution.deviceAspectRatio").get() multiply_divide.input2X.set(0.03937) fg_cam.scaleX.set(aperture) fg_cam.scaleY.set(aspect) multiply_divide.outputX >> fg_cam.scaleZ return fg_cam_shape
def sCameraCubeCam(p = [0,0,0], r = [0,0,0], fov=90, name="camera"): name = getUniqueName(name) target = py.camera(n=str(name), horizontalFieldOfView=fov) py.move(p[0],p[1],p[2]) py.rotate(r[0],r[1],r[2]) return target
def set_attr_for_pb(cameraShape): '''set camera attributes for playblast ''' pm.camera(cameraShape,e=1,displayFilmGate=0,displayResolution=0,displaySafeAction=0,overscan=1.0)
def xpop(args=[], type='LOC', space=1, addSuffix='', parent=''): ''' Function: takes args and matchesPos + duplicates specified type onto each arg Args = type=str, space=int, addSuffix=str, parent=str State: type=one of ['LOC','PLANE','CUBE','JNT','GRP','CAM','SLGT','DLGT','PLGT','ALGT'] if in list of prespecified objects, will populate across. Explained: locator, plane, cube, joint, group, camera, spotlight, directional light, point light, area light space=1-4: check help for _SCRIPTS._LAYOUT.lib_position.matchPos for instruction on this otherwise leave default Returns: list of PyNode(type) Example Usage: xpop(type='JNT', addSuffix='TEMP') ''' print 'Populating type: %s' % type suffixes=['LOC','PLANE','CUBE','JNT','GRP','CAM','SLGT','DLGT','PLGT','ALGT'] if type.upper() in suffixes or pm.objExists(type): if args==[]: args = pm.ls(sl=True) #Create or store group if parent=='': grp = 'populate_'+type+'_GRP' else: grp = parent if not pm.objExists(grp): grp = pm.group(em=True, n=grp) else: grp = pm.PyNode(grp) result=[] print type for arg in args: if addSuffix=='': pop = nami.replaceSuffix(type,args=arg.name(),validSuffix=True) else: pop = arg.name()+addSuffix if not pm.objExists(pop): if type=='LOC': pop = pm.spaceLocator(n=pop) elif type=='PLANE': pop = pm.polyPlane(n=pop,sx=1, sy=1)[0] elif type=='CUBE': pop = pm.polyCube(n=pop)[0] elif type=='JNT': pop = pm.joint( n=pop ) pop.radius.set(10) elif type=='GRP': pop = pm.group(em=True,n=pop) elif type=='CAM': pop = pm.camera(n=pop)[0] elif type=='SLGT': pop = pm.spotLight().listRelatives(p=True)[0].rename(pop) elif type=='DLGT': pop = pm.directionalLight().listRelatives(p=True)[0].rename(pop) elif type=='PLGT': pop = pm.pointLight().listRelatives(p=True)[0].rename(pop) elif type=='ALGT': pop = pm.createNode('areaLight').listRelatives(p=True)[0].rename(pop) else: pop = pm.duplicate(type)[0] posi.matchPos(src=arg, args=[pop], type=1) pop.addAttr('target',dt='string') pop.target.set( arg ) pop.setParent( grp ) result.append(pop) else: pm.error('Unsupported object type, check the help() for supported types') return result
def viewportCapture(cls, camera_node, model_panel, path=None, toSquare=False, height=600, width=960, file_format='jpg'): from tempfile import NamedTemporaryFile file_path = NamedTemporaryFile(suffix=".%s" % file_format, delete=False) pmc.setFocus(model_panel) pmc.modelPanel( model_panel, edit=True, camera=camera_node ) pmc.modelEditor( model_panel, edit=True, allObjects=False, polymeshes=True, wireframeOnShaded=False, displayAppearance='smoothShaded' ) pmc.camera( camera_node, edit=True, displayFilmGate=False, displayResolution=False, overscan=1 ) # Capture image pmc.playblast( frame=pmc.currentTime(query=True), format="image", completeFilename=file_path.name, compression=file_format, percent=100, quality=100, viewer=False, height=height, width=width, offScreen=True, showOrnaments=False ) # Store img var and delete file q_image = QtGui.QImage(file_path.name) image_width = q_image.size().width() image_height = q_image.size().height() file_path.close() os.unlink(file_path.name) # Crop image if toSquare is True: rect = cls.get_containedSquare(image_width, image_height) else: rect = QtCore.QRect(0, 0, image_width, image_height) cropped = q_image.copy(rect) # Save image File if path is not None: cropped.save(fullPath, file_format, quality) return cropped, path, rect
def import_ent(filename, load_face_poses): dirpath, file = os.path.split(filename) basename, ext = os.path.splitext(file) if ext.lower() in ('.json'): entity = read_json_w3.readEntFile(filename) else: entity = None ent_namespace = entity.name + ":" entity = fixed(entity) root_bone = import_rig.import_w3_rig(entity.animation_rig, entity.name) animation_rig = root_bone group = pm.group(n=entity.name + "_anim_skel", em=True) pm.parent(animation_rig, group) pm.select(group) pm.xform(ro=(90, 0, 180), s=(100, 100, 100)) pm.addAttr(longName="witcher_name", dt="string") pm.setAttr(group + '.witcher_name', entity.name) mimic_rig = False mimic_namespace = False rig_rig = False faceData = False constrains = [] HardAttachments = [] hair_meshes = [] eye_meshes = [] #for template in entity.includedTemplates: for i in range(len(entity.includedTemplates)): cur_chunks = entity.includedTemplates[i]['chunks'] for chunk in cur_chunks: #each chunk gets it's own namespace as each "CMeshComponent" has lods and materials with the same name # ENTITY_NAMESPACE + TYPE + TEMPLATE_INDEX + CHUNK_INDEX chunk_namespace = ent_namespace + chunk['type'] + str(i) + str( chunk['chunkIndex']) if not isChildNode(chunk['chunkIndex'], cur_chunks): constrains.append([entity.name, chunk_namespace]) if chunk['type'] == "CMeshSkinningAttachment" or chunk[ 'type'] == "CAnimatedAttachment": parent = chunk['parent'] child = chunk['child'] for findChunk in cur_chunks: if findChunk['chunkIndex'] == parent: if findChunk['type'] == "CAnimDangleComponent": parentNS = GetChunkNS(findChunk['constraint'], cur_chunks, i) else: parentNS = findChunk['type'] + str(i) + str(parent) if findChunk['chunkIndex'] == child: if findChunk['type'] == "CAnimDangleComponent": childNS = GetChunkNS(findChunk['constraint'], cur_chunks, i) else: childNS = findChunk['type'] + str(i) + str(child) if parentNS and childNS: print([parentNS, childNS]) constrains.append( [ent_namespace + parentNS, ent_namespace + childNS]) else: print("ERROR FINDING SKINNING ATTACHMENT") if "mesh" in chunk: fbx_name = fbx_util.importFbx( chunk['mesh'], chunk['type'] + str(i) + str(chunk['chunkIndex']), entity.name) if "\\he_" in chunk['mesh']: eye_meshes.append(chunk_namespace) if "\\c_" in chunk['mesh'] or "\\hh_" in chunk[ 'mesh'] or "\\hb_" in chunk['mesh']: hair_meshes.append(chunk_namespace) if "skeleton" in chunk: rig_grp_name = entity.name + chunk['type'] + "_rig" + "_grp" root_bone = import_rig.import_w3_rig(chunk['skeleton'], chunk_namespace) group = pm.group(n=rig_grp_name, em=True) pm.parent(root_bone, group) pm.select(group) pm.xform(ro=(90, 0, 180), s=(100, 100, 100)) rig_rig = root_bone if "dyng" in chunk: rig_grp_name = entity.name + chunk['type'] + "_rig" + "_grp" root_bone = import_rig.import_w3_rig(chunk['dyng'], chunk_namespace) group = pm.group(n=rig_grp_name, em=True) pm.parent(root_bone, group) pm.select(group) pm.xform(ro=(90, 0, 180), s=(100, 100, 100)) if "mimicFace" in chunk: rig_grp_name = entity.name + chunk['type'] + "_rig" + "_grp" #root_bone = import_rig.import_w3_rig(chunk['rig'],chunk_namespace) faceData = import_rig.loadFaceFile(chunk['mimicFace']) root_bone = import_rig.import_w3_rig2(faceData.mimicSkeleton, chunk_namespace) group = pm.group(n=rig_grp_name, em=True) pm.parent(root_bone, group) pm.select(group) pm.xform(ro=(90, 0, 180), s=(100, 100, 100)) mimic_rig = root_bone mimic_namespace = chunk_namespace if "camera" in entity.includedTemplates[i]: currentNs = cmds.namespaceInfo(cur=True) cmds.namespace(relativeNames=True) if not cmds.namespace(ex=':%s' % entity.name): cmds.namespace(add=':%s' % entity.name) cmds.namespace(set=':%s' % entity.name) camera = pm.camera(name="w_cam") pm.parent(camera, "Camera_Node") pm.xform(ro=(90, 0, 0), s=(0.2, 0.2, 0.2), t=(0, 0, 0)) cmds.namespace(set=currentNs) cmds.namespace(relativeNames=False) if entity.staticMeshes is not None: cur_chunks = entity.staticMeshes.get('chunks', []) i = "" for chunk in cur_chunks: #each chunk gets it's own namespace as each "CMeshComponent" has lods and materials with the same name # ENTITY_NAMESPACE + TYPE + TEMPLATE_INDEX + CHUNK_INDEX chunk_namespace = ent_namespace + chunk['type'] + str(i) + str( chunk['chunkIndex']) if not isChildNode(chunk['chunkIndex'], cur_chunks): constrains.append([entity.name, chunk_namespace]) if "mesh" in chunk: fbx_name = fbx_util.importFbx( chunk['mesh'], chunk['type'] + str(i) + str(chunk['chunkIndex']), entity.name) if "\\he_" in chunk['mesh']: eye_meshes.append(chunk_namespace) if "\\c_" in chunk['mesh'] or "\\hh_" in chunk[ 'mesh'] or "\\hb_" in chunk['mesh']: hair_meshes.append(chunk_namespace) if chunk['type'] == "CHardAttachment": parent = chunk['parent'] child = chunk['child'] parentSlotName = chunk['parentSlotName'] parentSlot = chunk['parentSlot'] for findChunk in cur_chunks: if findChunk['chunkIndex'] == child: childNS = findChunk['type'] + str(i) + str( child) + ":Mesh_lod0" if parentSlotName and childNS: print([parentSlotName, childNS]) HardAttachments.append([ ent_namespace + parentSlotName, ent_namespace + childNS ]) else: print("ERROR FINDING SKINNING ATTACHMENT") # main_group = pm.group(n=entity.name+"_grp", em=True ) # pm.parent(fbx_name,main_group) pm.modelEditor('modelPanel4', e=True, displayTextures=True) pm.modelEditor('modelPanel4', e=True, twoSidedLighting=True) #SET PROPER COLOR SPACE files = cmds.ls(type='file') for f in files: print(f) if "Normal" in f: cmds.setAttr(f + '.colorSpace', 'Raw', type='string') if "Diffuse" in f: cmds.setAttr(f + '.colorSpace', 'sRGB', type='string') # Set "Tangent Space" Coordinate Systems "Left Handed" allMesh = pm.ls(type='mesh') for mesh in allMesh: mesh.tangentSpace.set(2) sg = mesh.outputs(type='shadingEngine') for g in sg: for material in g.surfaceShader.listConnections(): if "diffuse" in material: material.diffuse.set(1.0) #GET SHADERS #check textures #do material operations if inList(mesh.nodeName(), eye_meshes) and not mesh.nodeName().endswith("Orig"): print(mesh) #Get the shading group from the selected mesh sg = mesh.outputs(type='shadingEngine') #print(sg) for g in sg: #sgInfo = g.connections(mat=True) for material in g.surfaceShader.listConnections(): #print(material) fileNode = material.connections(type='file') if fileNode: for file in fileNode: textureFile = pm.getAttr(file.fileTextureName) if "eyelash" in textureFile: mat_name = material.getName() print("found eyelash on " + mat_name) pm.rename(mat_name, mat_name + "_OLD") eyelash = create_hair(g, material, file, mat_name) eyelash.Diffuse.set(1.0) eyelash.AmbiantAmount.set(0.0) eyelash.OpacityAmount.set(0.8) #print 'This is the file', str(textureFile) else: if set(material.color.get()) == set([1.0, 1.0, 1.0]): material.transparency.set([1.0, 1.0, 1.0, 1.0]) if inList(mesh.nodeName(), hair_meshes) and not mesh.nodeName().endswith("Orig"): print(mesh) #Get the shading group from the selected mesh sg = mesh.outputs(type='shadingEngine') #print(sg) for g in sg: #sgInfo = g.connections(mat=True) for material in g.surfaceShader.listConnections(): print(material) mat_name = material.getName() pm.rename(mat_name, mat_name + "_OLD") fileNode = material.connections(type='file') if fileNode: for file in fileNode: textureFile = pm.getAttr(file.fileTextureName) print 'This is the file', str(textureFile) create_hair(g, material, file, mat_name) # allShader = pm.ls(type='shader') # for shade in allShader: # shade.diffuse.set(1.000) for constrain in constrains: #print(constrain) import_rig.constrain_w3_rig(constrain[0], constrain[1], mo=False) for constrain in HardAttachments: import_rig.hard_attach(constrain[0], constrain[1], mo=False) if load_face_poses: mimicPoses = import_rig.import_w3_mimicPoses( faceData.mimicPoses, faceData.mimicSkeleton, actor=entity.name, mimic_namespace=mimic_namespace) return '' #filename+"Cake"
def __init__(self, name): self.rootcam = pm.camera(name=name) self.selection = self.rootcam[0] self.shape = self.selection.getShape()
#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)
def createMultiStereoCamera(root, rootShape, camIndex, nStereoCams=9): ''' create a multi stereo camera and setup control expressions ''' cam, camShape = pc.camera() pc.parent(cam, root) name = str(root) + '_StereoCam%d' % (camIndex+1) cam.rename(name) camShape.renderable.set(False) # Connect the camera attributes from the master, hide them # for attr in [ 'horizontalFilmAperture', 'verticalFilmAperture', 'focalLength', 'lensSqueezeRatio', 'fStop', 'focusDistance', 'shutterAngle', 'cameraPrecompTemplate', 'filmFit', 'displayFilmGate', 'displayResolution', 'nearClipPlane', 'farClipPlane' ] : camShapeAttr = camShape.attr(attr) rootShape.attr(attr) >> camShapeAttr camShapeAttr.set(keyable=False) for attr in [ 'visibility', 'centerOfInterest' ] : cam.attr(attr).set(keyable=False) #stereoOffset = stereoEyeSeparation * (camIndex - nCams/2.0 + 0.5) #shift = -stereoOffset * (fl/10.0) / imageZ * p / (INCHES_TO_MM/10) mult = camIndex - nStereoCams / 2.0 + 0.5 mult *= 2 offsetAttr = 'stereoRightOffset' rotAttr = 'stereoRightAngle' hfoAttr = 'filmBackOutputRight' if mult < 0: offsetAttr = 'stereoLeftOffset' rotAttr = 'stereoLeftAngle' hfoAttr = 'filmBackOutputLeft' mult = abs(mult) offsetAttr = root.attr(offsetAttr) rotAttr = root.attr(rotAttr) hfoAttr = root.attr(hfoAttr) expression = getMultStereoExpression( mult, hfoAttr, offsetAttr, rotAttr, rootShape.zeroParallax, cam.translateX, camShape.hfo, cam.rotateY ) exprNode = pc.expression(s=expression) exprNode.rename(cam.name() + '_expression') lockAndHide(cam) return cam