def saveScreenshot(self, name, directory): """ Saves screenshot out to disk Args: name: Name of the screenshot directory: Directory to save into """ # get camera, current position and focus object cameraName = cmds.lookThru(q=True) prevPosition = cmds.getAttr("{0}.translate".format(cameraName)) objName = cmds.ls(sl=True, l=True) if objName: objName = objName[0] else: cmds.error("No object has been selected") # frame camera to object cmds.viewFit() # 'f' on keyboard distance = lib.distanceBetween(cameraName, objName) frameDistance = distance * 0.5 cmds.dolly(cameraName, d=-frameDistance) # take screenshot screenshotDir = mnpr_system.renderFrame(os.path.join(directory, name), 100, 100, 1, ".jpg") # bring camera back to normal lib.setAttr(cameraName, "translate", prevPosition) return screenshotDir
def createCamera(self, *args): selectedFaces = cmds.ls(sl=True, fl=True) cameraName = cmds.camera(name="BadGeoFinderCam", ncp=0.001) cameraShape = cameraName[1] cmds.currentTime(0, e=True) for face in range(len(selectedFaces)): currentTime = cmds.currentTime(q=True) cmds.currentTime(currentTime + 1, e=True) print "target = " + str(selectedFaces[face]) face_pos = cmds.xform(selectedFaces[face], q=True, bb=True, ws=True) x_pos = (face_pos[0] + face_pos[3]) / 2 y_pos = (face_pos[1] + face_pos[4]) / 2 z_pos = (face_pos[2] + face_pos[5]) / 2 cube = cmds.polyCube(n="BGF_Cube_" + str(face)) print cube cmds.move(x_pos, y_pos, z_pos, cube) nConstraint = cmds.normalConstraint(selectedFaces[face], cube) cube_pos = cmds.xform(cube, q=True, t=True, ws=True) cube_rot = cmds.xform(cube, q=True, ro=True, ws=True) cmds.xform(cameraName, t=cube_pos, ro=cube_rot, ws=True) cmds.rotate(0, 45, 0, cameraName, r=True) cmds.select(selectedFaces[face]) cmds.viewFit(cameraShape, f=0.5) cmds.select(cameraName) cmds.setKeyframe() cmds.delete(nConstraint, cube) cmds.select(selectedFaces)
def update_cam_position(self): objeto = cmds.ls(self.UI_object) if len(objeto) < 1: return # cam position obj_pos = cmds.xform(objeto[0], q=True, t=True) # interpolacion lineal percentage = 0 #float((float(self.slider_timeline.value()) / 100) * 100) position = self.cam_pos_start + (self.UI_object_full_rotation * percentage) rotation = self.cam_rot_start + ((self.cam_rot_end - self.cam_dist_start) * percentage) distance = self.cam_dist_start + ((self.cam_rot_end - self.cam_dist_start) * percentage) height = self.cam_height_start + (self.cam_height_end - self.cam_height_start) * percentage # update de pos of the camera obj_pos[0] += math.sin(math.radians(position)) * distance obj_pos[1] += (float(height) / 100) * self.UI_object_height obj_pos[2] += math.cos(math.radians(position)) * distance cmds.xform(self.UI_camera, t=obj_pos) # update the rotation with the inverse of the position angle in obj space rotation_percentage = float(rotation) / 100 xpos = self.UI_object_bottom[0] ypos = self.UI_object_bottom[1] + rotation_percentage * self.UI_object_height zpos = self.UI_object_bottom[2] try: cmds.viewPlace(self.UI_cameraShape, la=(xpos,ypos,zpos)) except: cmds.viewFit(self.UI_cameraShape , all=True)
def create_setup(self): objecto = cmds.ls(self.UI_object) cmds.viewFit(self.UI_cameraShape , all=True) if len(objecto) < 1: return # CREATE CAMERA OR CONFIGURE IT _width, _depth , height , _center , bottom, radius = self.getObjectData(objecto[0]) self.UI_object_height = height self.UI_object_radius = radius self.UI_object_bottom = bottom # CENTRAR LOS WIDGETS THE TURN AROUND HERE # slider distancia self.Qslider_dist.blockSignals(True) medium = (radius * 5) self.Qslider_dist.setRange(0, radius * 5) self.Qslider_dist.setValue(medium) self.Qslider_dist.blockSignals(False) self.Qslider_dist_end.setRange(radius, radius * 5) # altura slider self.Qslider_height.blockSignals(True) self.Qslider_height.setValue(50 + 15) self.Qslider_height.blockSignals(False) # altura slider self.Qslider_rot.blockSignals(True) self.Qslider_rot.setValue(50 + 10) self.Qslider_rot.blockSignals(False) # timeline self.slider_timeline.setValue(0)
def saveScreenshot(self, name): """ This function saves a screenshot of the library mesh Args: name: The name of the file to be saved Returns: The path to the screenshot """ directory = self.DIRECTORY screenshotPath = os.path.join(directory, "%s.jpg" % name) cmds.viewFit() #We deselect the mesh so we can screenshot it prettier cmds.select(clear=True) #Save as jpeg cmds.setAttr('defaultRenderGlobals.imageFormat', 8) cmds.playblast(completeFilename=screenshotPath, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False) return screenshotPath
def screenshot(self): self.playblastpath = r"Q:\rig\scripts\test\q_repos\aas_scripts\aas_mayaTools\ani_scripts\strack_asset\midchangepic.jpg" # 设置截图保存路径 filename = pm.sceneName() if filename: strinfo = re.compile('.ma|.mb') self.path = strinfo.sub('.jpg', filename) cmds.viewFit() cmds.setAttr("defaultRenderGlobals.imageFormat", 8) if os.path.exists(self.path): picplayblast = cmds.playblast( completeFilename=self.playblastpath, forceOverwrite=True, format='image', width=500, height=500, showOrnaments=False, startTime=1, endTime=1, viewer=False) else: picplayblast = cmds.playblast(completeFilename=self.path, forceOverwrite=True, format='image', width=500, height=500, showOrnaments=False, startTime=1, endTime=1, viewer=False) map = QtGui.QPixmap(picplayblast) self.screenshotbtn.setPixmap(map) else: self.Message.setText("<h3>请打开这个文件(注意不要导入)</h3>")
def build(self, force_new=True): """ Main function to build the rig """ if self._import_scenes: mc.file(force=force_new, new=True) print('Building rig for asset {}'.format(self._asset_name)) self.create_main_groups() if self._import_scenes: self.import_model() self.import_proxy() self.import_builder() else: self._generate_input_data_structure() self.create_main_controls() self.create_main_attributes() self.connect_main_controls() self.clean_model_group() self.clean_proxy_group() self.setup() self.finish() mc.select(mc.ls()) mc.viewFit(animate=True) mc.select(clear=True)
def createSnapShotCamera(objs, rotation=[0, 0, 0], resolution=[400, 600]): # build the bounding box and find it's centre bBox = createBoundingBox(objs) focusPoint = cmds.xform(bBox, query=True, ws=True, t=True) # build the camera the move and orient it cam = cmds.camera(ar=True, ff=3, fl=20) cmds.setAttr(cam[1]+'.renderable', True) cmds.setAttr(cam[1]+'.displayFilmGate', True) cmds.setAttr(cam[1]+'.displayResolution', True) cmds.setAttr(cam[1]+'.horizontalFilmAperture', resolution[0]*1.0/resolution[1]*1.0) cmds.setAttr(cam[1]+'.verticalFilmAperture', 1) cmds.setAttr(cam[1]+'.backgroundColor', 0.3, 0.3, 0.3, type='double3') #transform cmds.xform(cam[0], t=focusPoint, ro=rotation, ws=True) # build the bounding box then fit the camera cmds.select(bBox) cmds.viewFit(cam[0], an = False, f = 1 ) cmds.delete(bBox) # set the render globals cmds.currentTime(1) cmds.setAttr('defaultRenderGlobals.imageFormat', 8) cmds.setAttr('defaultRenderQuality.edgeAntiAliasing', 0) cmds.setAttr('defaultRenderQuality.shadingSamples', 2) cmds.setAttr('defaultRenderQuality.maxShadingSamples', 8) cmds.setAttr('defaultRenderQuality.useMultiPixelFilter', 1) cmds.setAttr('defaultRenderQuality.enableRaytracing', 0) cmds.setAttr('defaultResolution.width', resolution[0]) cmds.setAttr('defaultResolution.height', resolution[1]) cmds.setAttr('defaultResolution.deviceAspectRatio', resolution[0]*1.0/resolution[1]*1.0) return cam
def takeSnapShot(targetObj, renderPath, rotX=-30.0, rotY=45.0, rotZ=0.0, resX=300, resY=300, useBoundingBox=False): ''' Take a snapshot of the selected object using the Maya renderer then move the image to a directory ''' # build the bounding box and find it's centre bBox = targetObj if useBoundingBox is True: bBox = buildBoundingBoxGeo(targetObj, noChildren=False, ignoreInv=True) focusPoint = cmds.xform(bBox, query=True, ws=True, t=True) # build the camera the move and orient it tempCam = cmds.camera(ar=True, ff=3, fl=35) camName = tempCam[1] cmds.setAttr(camName+'.renderable', True) cmds.setAttr(camName+'.displayFilmGate', True) cmds.setAttr(camName+'.displayResolution', True) cmds.setAttr(camName+'.backgroundColor', 0.5, 0.5, 0.5, type='double3') #transform cmds.move(focusPoint[0], focusPoint[1], focusPoint[2], tempCam, ws=True) cmds.rotate( rotX, rotY, rotZ, tempCam, ws=True) # build the bounding box then fit the camera cmds.select(bBox, r=True) cmds.viewFit(camName, an = False, f = 0.9 ) if useBoundingBox is True: cmds.delete(bBox) # set the render globals cmds.currentTime(1) cmds.setAttr('defaultRenderGlobals.imageFormat', 8) cmds.setAttr('defaultRenderQuality.edgeAntiAliasing', 0) cmds.setAttr('defaultRenderQuality.shadingSamples', 2) cmds.setAttr('defaultRenderQuality.maxShadingSamples', 8) cmds.setAttr('defaultRenderQuality.useMultiPixelFilter', 1) cmds.setAttr('defaultRenderQuality.enableRaytracing', 0) # build the lightrig lightRigGrp = cmds.group(em=True, name='lightRigGroup') lightMain = cmds.directionalLight(rotation=(-20, -45, 0), intensity=0.8) lightFill = cmds.directionalLight(rotation=(-20, 45, 0), intensity=0.4) lightUnder = cmds.directionalLight(rotation=(75, 0, 0), intensity=0.15) lightKey = cmds.directionalLight(rotation=(-25, 145, 0), intensity=4.0) cmds.parent([lightMain, lightFill, lightUnder, lightKey], lightRigGrp) cmds.rotate( rotX, rotY, rotZ, lightRigGrp, ws=True) # select everything, build the special shader, render, then delete everything cmds.select([targetObj, lightRigGrp], r=True) renderLayerName = cmds.createRenderLayer(name='tempSnapShot_rlayer', mc=True) shaderNodes = buildReverseNormalShader() #build the shader cmds.sets(targetObj, e=True, forceElement=shaderNodes[0]) #adding the shader here means it's in the render layer tempImage= cmds.render(camName, layer=renderLayerName, x=resX, y=resY) cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer') cmds.delete([lightRigGrp, tempCam[0], renderLayerName, shaderNodes[0], shaderNodes[1], shaderNodes[2], shaderNodes[3]]) # copy the thumbnail to the desired location output = cmds.sysFile(tempImage, rename=renderPath) if output==True: print 'Path for thumbnail: ' + renderPath return renderPath return None
def save_snapshot(self, geo): # Create new camera, isolated selected object, frame and take snapshot # Delete cam and return to perspective cam self.create_img_cam() cmds.lookThru(self.cameraName) cmds.select(geo) if cmds.isolateSelect('modelPanel4', q=True, state=True): cmds.isolateSelect('modelPanel4', state=False) cmds.isolateSelect('modelPanel4', state=True) cmds.isolateSelect('modelPanel4', addSelected=True) else: cmds.isolateSelect('modelPanel4', state=True) cmds.isolateSelect('modelPanel4', addSelected=True) cmds.viewFit() imageSnapshot = (os.path.join(self.img_path, geo)) + ".jpg" imageSnapshot = os.path.normpath(imageSnapshot) cmds.refresh(cv=True, fe = "jpg", fn = imageSnapshot) cmds.isolateSelect('modelPanel4', state=False) self.return_to_perspCam() if self.cameraName: cmds.delete(self.cameraName[0]) return imageSnapshot
def saveScreenshot(self, name): path = os.path.join(self.userPath, '%s.jpg' % name) activePanel = cmds.paneLayout('viewPanes', q=True, pane1=True) cmds.viewFit() cmds.setAttr('defaultRenderGlobals.imageFormat', 8) # Isolate selection if cmds.ls(selection=True): cmds.isolateSelect(activePanel, update=1) cmds.isolateSelect(activePanel, state=1) cmds.isolateSelect(activePanel, addSelected=1) cmds.modelEditor(activePanel, edit=True, sel=False) cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False) cmds.modelEditor(activePanel, edit=True, sel=True) cmds.isolateSelect(activePanel, state=0)
def saveScreenshot(self, name, directory=DIRECTORY): """ to save screenshot of the model Args: name: (str) name of the model directory: (str) (path) path of the control library Returns: path: path of image of the screenshot """ path = os.path.join(directory, '%s.jpg' % name) # to get the path of the screenshot cmds.viewFit( ) # view fit from maya commands of selected object i.e click 'f' key cmds.setAttr('defaultRenderGlobals.imageFormat', 8) # set maya render to image format of jpg cmds.playblast( completeFilename=path, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False) # get playblast of 1 frame and save in given path # return the path of the image return path
def create_camera(): # creates a camera mel.eval('camera -centerOfInterest 5 -focalLength 35 -cameraScale 1;objectMoveCommand; cameraMakeNode 2 "";') cmds.select(clear=True) cmds.select("camera1") # render settings mel.eval('setAttr "frontShape.renderable" 0;') mel.eval('setAttr "topShape.renderable" 0;') mel.eval('setAttr "sideShape.renderable" 0;') mel.eval('setAttr "perspShape.renderable" 0;') mel.eval('setAttr "cameraShape1.renderable" 1;') # prep for render mel.eval('select -r camera1_aim; move -absolute -worldSpaceDistance 0 0 0;') mel.eval('select -r camera1; move -absolute -worldSpaceDistance 0 ' + str(5) + ' 0;') mel.eval('select -r shirt') cmds.viewFit('camera1', f=0.95*(SHIRT_SCALE/0.8)) # shirt material settings mel.eval('select -r shirt;') mel.eval('shadingNode -asShader lambert;') mel.eval('rename lambert2 "shirt_mat";') mel.eval('sets -renderable true -noSurfaceShader true' + \ '-empty -name -shirt_matSG;') mel.eval('connectAttr -f shirt_mat.outColor shirt_matSG.surfaceShader;') mel.eval('setAttr "shirt_mat.color" -type double3 1 1 1;') mel.eval('setAttr "shirt_mat.ambientColor" -type double3 1 1 1;') mel.eval('select -r shirt ; sets -e -forceElement shirt_matSG;') # pointer material settings mel.eval('shadingNode -asShader lambert;') mel.eval('rename lambert2 "pointer_mat";') mel.eval('sets -renderable true -noSurfaceShader true' + \ '-empty -name -pointer_matSG;') mel.eval('connectAttr -f pointer_mat.outColor pointer_matSG.surfaceShader;') mel.eval('setAttr "pointer_mat.transparency" -type double3 1 1 1;')
def __icon(*arg): if "file" not in CACHE.viewkeys(): return mc.select(cl=True) for e in mc.lsUI(ed=True): try: mc.viewFit(p=e) except: pass f = CACHE["file"][:-3] + ".png" if os.path.isfile(f): os.remove(f) fmt = mc.getAttr("defaultRenderGlobals.imageFormat") mc.setAttr("defaultRenderGlobals.imageFormat", 32) i = mc.playblast(cf=f, fmt="image", cc=False, fr=1, v=False, orn=False, os=True, p=100, wh=[200, 200], qlt=100) mc.setAttr("defaultRenderGlobals.imageFormat", fmt) mc.image("img_FRW", e=True, i=f)
def gpsTurntable(): # Set up framerange startTime = cmds.playbackOptions ( query = True, minTime = True ) endTime = cmds.playbackOptions ( query = True, maxTime = True ) # Get current selection selectionList = cmds.ls (selection = True) if selectionList: # Get centre of selection bbox = cmds.exactWorldBoundingBox() centre_x = (bbox[0] + bbox[3]) / 2.0 centre_y = (bbox[1] + bbox[4]) / 2.0 centre_z = (bbox[2] + bbox[5]) / 2.0 # Create new group new_grp = cmds.group(empty=True, name="Turntable_%s_grp#" %selectionList[0]) cmds.move(centre_x, centre_y, centre_z, new_grp) # Create Turntable camera new_cam = cmds.camera() cmds.select (selectionList, r = True) cmds.viewFit (new_cam[0], allObjects = False) cmds.parent (new_cam[0], new_grp) cmds.setKeyframe (new_grp, time = startTime-1, attribute = "rotateY", value=0) cmds.setKeyframe (new_grp, time = endTime, attribute = "rotateY", value=360) cmds.selectKey (new_grp, time = (startTime-1, endTime), attribute = "rotateY", keyframe = True) cmds.keyTangent (inTangentType = "linear", outTangentType = "linear") cmds.rename ("Turntable_%s_cam#" %selectionList[0]) else: cmds.warning("Please select one or more objects!")
def saveScreenShot(self, name, directory=DIRECTORY): path = os.path.join(directory, '%s.jpg'%name) cmds.viewFit() cmds.setAttr('defaultRenderGlobals.imageFormat', 8) cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200, showOrnaments = False, startTime=1, endTime=1, viewer=False ) return path
def update_editor_view(self): cmds.viewFit() panels = cmds.getPanel(type='modelPanel') for panel in panels: modelEditor = cmds.modelPanel(panel, query=True, modelEditor=True) cmds.modelEditor(modelEditor, edit=True, displayAppearance='smoothShaded', displayTextures=True, textures=True, joints=False)
def focus_cam_object(node_name, cam_name="persp"): """ Focus on an object with specified camera Parameters ---------- node_name (string): Maya node name cam_name (string): Maya camera name Returns ------- Exception: Raise an exception if node_name is not foundable True (Boolean): Always return True if completed """ try: cmds.select(node_name) except: raise Exception( "Error: No able to found {} in the current scene".format( node_name)) # center perspective camera on it cmds.viewFit("persp", node_name) return True
def CreateViewWindow(self): self.camera = None form = cmds.formLayout(w=300, h=300) self.editorShot = cmds.modelEditor() column = cmds.columnLayout('true', bgc=[0, 0, 0]) cmds.formLayout(form, edit=True, attachForm=[(column, 'top', 10), (column, 'left', 10), (self.editorShot, 'top', 10), (self.editorShot, 'bottom', 10), (self.editorShot, 'right', 10), (self.editorShot, 'left', 10)], attachNone=[(column, 'bottom'), (column, 'right')], attachControl=(self.editorShot, 'left', 0, column)) self.camera = cmds.camera(centerOfInterest=2.450351, position=(1.535314, 1.135712, 1.535314), rotation=(0, 0, 0), worldUp=(0, 0, 1)) cmds.setAttr(self.camera[1] + ".focalLength", 70) cmds.modelEditor(self.editorShot, edit=True, camera=self.camera[0]) cmds.viewFit(self.camera[0]) cmds.modelEditor(self.editorShot, edit=True, nurbsCurves=False, displayAppearance="smoothShaded", displayTextures=True, headsUpDisplay=False, cameras=False, grid=False, joints=False, textures=True)
def addCharacter(self, close, *args): project = cmds.optionMenu(self.widgets["project"], q=True, value=True) selectedCharacter = cmds.textScrollList(self.widgets["characterList"], q=True, si=True)[0] rigPath = os.path.join( self.mayaToolsDir, "General", "ART", "Projects", project, "AnimRigs", selectedCharacter + ".mb" ) # find existing namespaces in scene namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) # reference the rig file cmds.file( rigPath, r=True, type="mayaBinary", loadReferenceDepth="all", namespace=selectedCharacter, options="v=0" ) # clear selection and fit view cmds.select(clear=True) cmds.viewFit() panels = cmds.getPanel(type="modelPanel") # turn on smooth shading for panel in panels: editor = cmds.modelPanel(panel, q=True, modelEditor=True) cmds.modelEditor(editor, edit=True, displayAppearance="smoothShaded", displayTextures=True, textures=True) # find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created) newCharacterName = selectedCharacter newNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for name in newNamespaces: if name not in namespaces: newCharacterName = name # launch UI import ART_animationUI reload(ART_animationUI) ART_animationUI.AnimationUI() if close: cmds.deleteUI(self.widgets["window"])
def __init__( self, xformRoots, traceableObjs ): self.xformRoots = xformRoots # all rigs self.traceableObjs = traceableObjs # the list of joints to pay attention to (ignore the rest) self.substeps = 1 # precision settings self.dragDensity = 0.2 self.selectedMotions = {} # a dictionary to hold the selected motions for each root self.motionPathsVisible = {} # a dictionary to remember whether (or not) the motion paths for a root were visible when the interaction started self.forceReload = False # force the re-definition of the tool? # for keeping track of time when mousePressed (when selection started) self.startTime = 0 # make an empty trajectory dictionary self.trace = {} self.nearestRoot = None self.nearestPath = None self.interactionPlane = None # measure the fit-one truck distance for the camera mc.select( xformRoots[0] ) mc.viewFit() self.viewFitDistance = self.CameraToPopDist() # zoom back out to view all mc.select(clear=True) mc.viewFit()
def importFiles(self): # import guides cmds.file(GUIDE_PATH, i=True, defaultNamespace=True) # import BlendNode cmds.file(IN_BLEND_PATH, i=True, defaultNamespace=True) cmds.viewFit()
def viewFromCamPosition(self, positionName, containerName): self.changeToPerspCam() cmd = "" if (positionName =='PERSPECTIVE'): cmd = "viewSet -animate `optionVar -query animateRollViewCompass` -p" #cmds.viewSet(p=True, an=False); elif (positionName == 'TOP'): cmd = "viewSet -animate `optionVar -query animateRollViewCompass` -top" elif (positionName == 'BOTTOM'): cmd = "viewSet -animate `optionVar -query animateRollViewCompass` -bottom" elif (positionName == 'RIGHT'): cmd = "viewSet -animate `optionVar -query animateRollViewCompass` -rightSide" elif (positionName == 'LEFT'): cmd = "viewSet -animate `optionVar -query animateRollViewCompass` -leftSide" elif (positionName == 'FRONT'): cmd = "viewSet -animate `optionVar -query animateRollViewCompass` -front" elif (positionName == 'BACK'): cmd = "viewSet -animate `optionVar -query animateRollViewCompass` -back" cmds.select(containerName) # Execute MEL command mel.eval(cmd) cmds.viewFit(an=False)
def TraceGestureRelease( self ): """ when the mouse is released, find the matching joint trajectory """ if debug>0: print("begin RELEASE") releasePosition = Vector( mc.draggerContext( 'TraceGesture', query=True, dragPoint=True) ).projectToPlane( self.trace[self.nearestRoot].normal, planePt=self.trace[self.nearestRoot].planePt ) if debug>0: print "release! ", releasePosition theTrace = self.trace[self.nearestRoot] selectedMotion = None if theTrace.closestJoint and theTrace.timespan and (theTrace.timespan[1]-theTrace.timespan[0]) > 1 and \ not mc.draggerContext( 'TraceGesture', query=True, modifier=True) == "ctrl": theDTW = theTrace.dtws[theTrace.closest] if debug > 0: print "closest = ", theTrace.closestJoint, theTrace.timespan if not mc.objExists("DTW_Y"): mc.group(n="DTW_Y",empty=True) for pt in theDTW.Y: loc = mc.spaceLocator(p=pt) mc.parent(loc,"DTW_Y") ## ghostJoint(trace[nearestRoot].closestJoint,trace[nearestRoot].timespan) # Build the motion curve and store it's name in the selectedMotions dictionary duration = [ int(theTrace.timespan[0]), int(theTrace.timespan[1]+1) ] keyframes = [ theTrace.searchList[theTrace.closestJoint].points[frame] for frame in range(duration[0],duration[1]) ] selectedMotion = bmt.CurveMotionTrace( theTrace.closestJoint, keys=keyframes ) #duration=theTrace.timespan ) else: self.ScrubToNearestTimeOnPath( releasePosition, self.nearestRoot, self.nearestPath ) cam2pop = self.CameraToPopDist() path = theTrace.searchList[self.nearestPath] pointKey = path.ClosestTimeTo(releasePosition) closestPoint = path.points[pointKey] closestPtOnPath = closestPoint.projectToPlane( theTrace.normal, planePt=theTrace.planePt ) mouse2path = (releasePosition - closestPtOnPath).mag() # if motion paths are visible and no drag happened # and releasePosition is very close to the path, # then select the whole motion path if self.motionPathsVisible[self.nearestRoot] and mouse2path < 0.3: # Build the motion curve and store it's name in the selectedMotions dictionary duration = [ mc.playbackOptions(q=True,min=True),mc.playbackOptions(q=True,max=True)+1 ] keyframes = [ theTrace.searchList[self.nearestPath].points[frame] for frame in range(duration[0],duration[1]) ] selectedMotion = bmt.CurveMotionTrace( self.nearestPath, keys=keyframes ) #duration=[mc.playbackOptions(q=True,min=True),mc.playbackOptions(q=True,max=True)] ) # if not scrubbing if not mc.draggerContext( 'TraceGesture', query=True, modifier=True) == "ctrl" and \ cam2pop >= self.viewFitDistance: # if trucked out, and mouse is clicked (w/ no drag) mc.select(self.nearestRoot) # zoom in on the nearest root for a better view mc.viewFit(fitFactor=2.5) # the invisible parts of the roots can artificially enlarge the BB, so truck in a little extra mc.select(clear=True) if selectedMotion: selectedMotionCurve = selectedMotion.construct(self.nearestPath) if not self.nearestRoot in self.selectedMotions.keys(): self.selectedMotions[self.nearestRoot] = [] mc.setAttr("%s_MotionTraces.visibility"%self.nearestRoot, 0) selectedMotionCurve = mc.rename(selectedMotionCurve, "%s_selection%d"%(self.nearestPath,len(self.selectedMotions[self.nearestRoot]))) self.selectedMotions[self.nearestRoot].append( selectedMotionCurve ) self.AddCustomAttr( selectedMotionCurve, "isTraceSelection", True ) self.AddCustomAttr( selectedMotionCurve, "interactTime", time.time()-self.startTime ) self.AddCustomAttr( selectedMotionCurve, "startFrame", duration[0] ) self.AddCustomAttr( selectedMotionCurve, "endFrame", duration[1] ) mc.select(cl=True)
def save_screenshot(self, name, directory=DIRECTORY): '''[summary] Arguments: name {string} -- Name of the asset to be used to make screenshot file Keyword Arguments: directory {string} -- Path of the asset library (default: {LIBRARY_PATH}) Returns: string -- Returns path of the screenshot file ''' path = os.path.join(directory, '{0}.jpg'.format(name)) cmds.viewFit() cmds.setAttr('defaultRenderGlobals.imageFormat', 8) cmds.playblast( completeFilename=path, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False) return path
def center_camera(): # center the camera bbx = cmds.xform("shirt", q=True, bb=True, ws=True) centerX = (bbx[0] + bbx[3]) / 2.0 centerZ = (bbx[2] + bbx[5]) / 2.0 mel.eval('select -r camera1_aim; move -absolute -worldSpaceDistance ' + str(centerX) + ' 0 ' + str(centerZ) + ';') mel.eval('select -r camera1; move -absolute -worldSpaceDistance ' + str(centerX) + ' 5 ' + str(centerZ) + ';') cmds.viewFit('camera1', all=True)
def playblast_picture(self): filename=(str(self.playblast_filename)) strinfo = re.compile('.ma|.mb') path= strinfo.sub('.jpg',filename) cmds.viewFit() cmds.setAttr("defaultRenderGlobals.imageFormat", 8) cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=800, height=800, showOrnaments=False, startTime=1, endTime=1, viewer=False)
def re_open_current_file(): current_file = mc.file(q=True, sceneName=True) if os.path.exists(current_file): mc.file(new=True, force=True) mc.file(current_file, open=True) mc.viewFit() else: mc.file(new=True, force=True)
def create_turntable(): # # save current file # mc.file(save=1, f=1) # sel the group for turntable sel = mc.ls(sl=1) group_name = "tt_rotation" # cam_name = "tt_camera" if sel: if pm.ls(group_name): logging.warning("tt_rotation group exist.") return else: # group the sel as tt_rotation mc.group(n="tt_rotation") # mc.parent(sel, "tt_rotation") mc.xform("tt_rotation", rotatePivot=[0, 0, 0], worldSpace=1) # key the tt_rotation group mc.setKeyframe("tt_rotation", value=0, t=0, itt="linear", ott="linear", at="rotateY") mc.setKeyframe('tt_rotation', v=360, t=120, itt='linear', ott='linear', at='rotateY') # set animation range mc.playbackOptions(minTime=0, animationStartTime=0) mc.playbackOptions(maxTime=120, animationEndTime=120) bb = bounding_by_frame([0, 120], ['tt_rotation']) box = create_warp_box_bounding(bb) view = OpenMayaUI.M3dView.active3dView() cam = OpenMaya.MDagPath() view.getCamera(cam) camPath = cam.fullPathName() # duplicate a camera new_camera = mc.duplicate(camPath)[0] mc.rename(new_camera, "tt_camera") # look though the camera mc.viewFit("tt_camera", fitFactor=mc.getAttr('defaultResolution.pixelAspect') / mc.getAttr('defaultResolution.deviceAspectRatio') * 1.2) #center = mc.objectCenter(box) #distance = max([abs(each) for each in bb]) #distance *= 2.42 #cam_ = mc.listRelatives(camPath,parent=True)[0] #mc.setAttr("%s.translateX" % cam_,center[0]) #mc.setAttr("%s.translateY" % cam_,center[1]) #mc.setAttr("%s.translateZ" % cam_,center[2]) #mc.camera(camPath,e=True,centerOfInterest=distance) mc.delete(box) return True else: logging.error('No object selected, please select an object') return False
def fitCamera(*args): cam = "cameraForShapes1" cmds.viewFit( cam, f=0.75) cmds.setAttr(cam + '.overrideEnabled', 1) cmds.setAttr (cam + '.overrideDisplayType', 2) cmds.select(clear=True)
def cleanMe(self): cmds.viewFit() object = pm.ls(tr=True)[0:6] for x in object: pm.select(x) pm.polyNormalPerVertex(x, ufn=True) pm.polySoftEdge(x, a=180, ch=1) pm.bakePartialHistory(x, ppt=True) pm.select(cl=True)
def YupZup(): if cmds.upAxis(q=True, axis=True) == "y": cmds.upAxis(ax="z", rv=True) else: cmds.upAxis(ax="y", rv=True) for cam in cmds.listCameras(): cmds.viewSet(cam, animate=False, home=True) cmds.viewFit(all=True)
def create_camera(model): """Create the camera to focus on the mode. Arguments: model(unicode): Model to fit in view. """ qc_camera = cmds.camera(name="QC_Camera") qc_camera_shape = qc_camera[1] cmds.select(model) cmds.viewFit(qc_camera_shape, fitFactor=0.8) return qc_camera[0]
def cleanup(): '''Closes all windows/panels and sets viewport to bounding box.''' win_exceptions = [ 'MayaWindow', 'clToolBoxWindow', 'clOutlinerWindow', 'clShowConnectionsWindow' ] windows = cmds.lsUI(windows=True) windows = list(set(windows).difference(win_exceptions)) for w in windows: cmds.deleteUI(w) clear_panels() for p in ['modelPanel1', 'modelPanel2', 'modelPanel3', 'modelPanel4']: cmds.modelEditor(p, e=True, displayAppearance='boundingBox') for func in [ lambda *args: cmds.setAttr( 'Transform_Ctrl.GeoRes', cmds.attributeQuery( 'GeoRes', n='Transform_Ctrl', listEnum=True)[0].split(':'). index('Proxy')), lambda *args: cmds.setAttr('Transform_Ctrl.GeoVis', 1), lambda *args: cmds.setAttr('Transform_Ctrl.GeoSmooth', 0), lambda *args: cmds.setAttr('COG_Ctrl.PivotCtrlVis', 0), lambda *args: cmds.setAttr('COG_Ctrl.BendCtrlVis', 0), lambda *args: cmds.setAttr('COG_Ctrl.SquashCtrlVis', 0), lambda *args: cmds.setAttr('COG_Ctrl.DefCtrlVis', 0), lambda *args: cmds.setAttr('Smooth.visibility', 1), lambda *args: cmds.setAttr('NoSmooth.visibility', 1), lambda *args: cmds.setAttr('Geo_Layer.visibility', 1), lambda *args: cmds.setAttr('Geometry_Layer.visibility', 1), lambda *args: cmds.setAttr('Controls_Layer.visibility', 1), lambda *args: cmds.setAttr('LgtRg_Layer.visibility', 1), lambda *args: cmds.setAttr('Smooth.displayType', 0), lambda *args: cmds.setAttr('NoSmooth.displayType', 0), lambda *args: cmds.setAttr('Geo_Layer.displayType', 2), lambda *args: cmds.setAttr('Geometry_Layer.displayType', 2), lambda *args: cmds.setAttr('Controls_Layer.displayType', 0), lambda *args: cmds.setAttr('LgtRg_Layer.displayType', 0), lambda *args: cmds.setAttr('Transform_Ctrl.t', 0, 0, 0), lambda *args: cmds.setAttr('Transform_Ctrl.r', 0, 0, 0), lambda *args: cmds.setAttr('Transform_Ctrl.s', 1, 1, 1), lambda *args: cmds.setAttr('COG_Ctrl.t', 0, 0, 0), lambda *args: cmds.setAttr('COG_Ctrl.r', 0, 0, 0), lambda *args: cmds.setAttr('COG_Ctrl.s', 1, 1, 1), lambda *args: cmds.setAttr('COG_Pivot_Ctrl.t', 0, 0, 0) ]: try: func() except: pass cmds.viewFit(allObjects=True, animate=False, f=.9) return
def objectSel(self, item): global objs items = self.objectQList.selectedItems() objs = [] for i in list(items): objs.append(i.text()) self.statusBar.showMessage(str(objs), 4000) cmds.showHidden(grpTemp + '*') cmds.select(objs) cmds.isolateSelect(viewer, s=False) cmds.isolateSelect(viewer, s=True) cmds.viewFit(objectViewerCam)
def addCharacter(self, close, *args): project = cmds.optionMenu(self.widgets["project"], q=True, value=True) selectedCharacter = cmds.textScrollList(self.widgets["characterList"], q=True, si=True)[0] rigPath = self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" + selectedCharacter + ".mb" #find existing namespaces in scene namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) #reference the rig file cmds.file(rigPath, r=True, type="mayaBinary", loadReferenceDepth="all", namespace=selectedCharacter, options="v=0") #clear selection and fit view cmds.select(clear=True) #query autoKeyFrame state if not cmds.autoKeyframe(q=True, state=True): cmds.viewFit() #cmds.viewFit() panels = cmds.getPanel(type='modelPanel') #turn on smooth shading for panel in panels: editor = cmds.modelPanel(panel, q=True, modelEditor=True) cmds.modelEditor(editor, edit=True, displayAppearance="smoothShaded", displayTextures=True, textures=True) #find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created) newCharacterName = selectedCharacter newNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for name in newNamespaces: if name not in namespaces: newCharacterName = name #launch UI import ART_animationUI reload(ART_animationUI) ART_animationUI.AnimationUI() if close: cmds.deleteUI(self.widgets["window"])
def snapShot(output_folder, isolate=True, fit=False): """ Generate viewport snapshot. """ # Get current selection, frame and panel currentSel = mc.ls(sl=True) currentFrame = mc.currentTime(q=True) currentPanel = mc.playblast(ae=True) # Isolate the current object if isolate: mc.isolateSelect(currentPanel, state=1) mc.isolateSelect(currentPanel, addSelected=True) # Frame view to selection if fit: mc.viewFit(fitFactor=1) # Store current selection and deselect all mc.select(cl=True) # Generate playblast mc.playblast( completeFilename=os.path.join(output_folder, 'preview.jpg'), #mc.playblast(filename=os.path.join(output_folder, 'preview'), frame=(currentFrame), framePadding=4, rawFrameNumbers=True, width=512, height=288, percent=100, format='image', compression='jpg', quality=90, viewer=False, offScreen=True, clearCache=True, showOrnaments=False) # Turn off isolate selection if isolate: mc.isolateSelect(currentPanel, state=0) # Reset view if fit: mc.viewSet(previousView=True) # Reselect original selection for sel in currentSel: mc.select(sel, add=True)
def createCam(s): if not cmds.objExists(s.camName): s.camera = cmds.camera(n=s.camName)[0] else: s.camera = cmds.ls(s.camName)[0] cmds.viewSet(s.camera, p=True) # Move camera to perspective position sel = cmds.ls(sl=True) objs = [a for a in s.data if cmds.objExists(a)] if objs: cmds.select(objs, r=True) cmds.viewFit(s.camera, f=0.5) cmds.select(sel, r=True) cmds.setAttr("%s.focalLength" % s.camera, 500) cmds.setAttr("%s.horizontalFilmAperture" % s.camera, 5) cmds.setAttr("%s.verticalFilmAperture" % s.camera, 5) cmds.setAttr("%s.visibility" % s.camera, 0)
def __createPreviewShape(self): selected_shape = self.__get_selectedShape() if selected_shape: if self.preview_curve is None or not cmds.objExists(self.preview_curve): self.preview_curve = createCurve(selected_shape, '%s:PREVIEW_CRV' % self.ns) cmds.parent(self.preview_curve, self.grp) else: replaceCurve(selected_shape, [self.preview_curve]) else: if cmds.objExists(self.preview_curve): cmds.delete(self.preview_curve) self.preview_curve = None self.__isolateSelectedInViewport() cam_shape = cmds.listRelatives(self.viewport_cam, shapes=True)[0] cmds.viewFit(cam_shape, namespace=':')
def prep_view(self): """ prep current view panel with required settings for screen grab """ mel.eval("lookThroughModelPanel %s %s" % (self.camera, self._current_panel)) if self._isolate_objs: # mel.eval('enableIsolateSelect %s %s;' % # (self._current_panel, self._isolate_objs)) mc.isolateSelect(self._current_panel, state=self._isolate_objs) mc.isolateSelect(self._current_panel, addSelected=True) mc.viewFit() mc.select(clear=True) # attempt to use Viewport 2.0 for better image try: mc.modelEditor(self._current_panel, edit=True, rendererName="vp2Renderer") except Exception, e: raise "Issue activating Viewport 2.0. %s" % e
def new_scene(force=True): """ Open new scene. Set all scene variables and options correctly. """ axis = os.getenv("UPAXIS") units = os.getenv("UNITS") # Force new open if force: cmds.file(f=force, new=1) else: mel.eval('saveChanges("file -f -new")') cmds.file(f=force, new=1) # Up Axis if cmds.upAxis(q=1, axis=1).capitalize() != axis.capitalize(): cmds.upAxis(axis=axis, rv=1) # FPS intFps=int(os.getenv("FPS")) fps=fps_val(intFps) cmds.currentUnit(time=fps, ua=0) # Units cmds.currentUnit(l=units) # Set Clipping Planes cmds.setAttr("perspShape.nearClipPlane", 0.001) cmds.setAttr("perspShape.farClipPlane", 1000) cmds.setAttr("sideShape.nearClipPlane", 0.001) cmds.setAttr("sideShape.farClipPlane", 1000) cmds.setAttr("topShape.nearClipPlane", 0.001) cmds.setAttr("topShape.farClipPlane", 1000) cmds.setAttr("frontShape.nearClipPlane", 0.001) cmds.setAttr("frontShape.farClipPlane", 1000) # Grid if units == "meter": cmds.grid(size=10, divisions=5, sp=5) elif units == "centimeter": cmds.grid(size=100, divisions=50, sp=5) elif units == "millimeter": cmds.grid(size=1000, divisions=500, sp=5) # Set timeline to first frame cmds.currentTime(1) cmds.playbackOptions(aet=100, min=1, max=100) # Fit view cmds.viewFit(an=1, all=1)
def clear() : global rigidbody global camera global lastCam global currentPanel global selection if camera and lastCam and currentPanel : pos = m.xform(camera, q=True, t=True, ws=True) ori = m.xform(camera, q=True, ro=True, ws=True) m.xform(lastCam, t=pos, ws=True) m.xform(lastCam, ro=ori, ws=True) m.setAttr( lastCam + ".rz", 0) m.modelPanel( currentPanel, cam=lastCam, e=True) m.select( selection ) m.viewFit() for i in [ rigidbody, camera ] : if i and m.objExists( i ) : m.delete(i) i = None
def doScreenGrab(node, currentAssetCategory="environments"): '''Saves out an image of the asset. ''' nodeName = node.rpartition("|")[2] currentAssetLibrary = ddConstants.ASSET_DIRECTORIES[currentAssetCategory] currentImageLibrary = ddConstants.IMAGE_DIRECTORIES[currentAssetCategory] charType = { "hero": "hero", "bg": "background", "sec": "secondary" } chesspieceTypes = ["CPF", "CPO", "CPD", "CPS"] invalidNodes = ddCheckNames.do(nodes=node, currentAssetCategory=currentAssetCategory) if invalidNodes: sys.stdout.write("Legalize names before taking screen grab.\n") return dirs = list() version = "" divider = "" dividerGRP = "" imagePath = currentAssetLibrary smallImagesPath = currentImageLibrary if currentAssetCategory == "environments": dirs = nodeName.rpartition("|")[2].split("_GRP")[0].split("_") version = nodeName.rpartition("|")[2].split("_GRP_")[1].split("_")[0] imagePath = currentAssetLibrary smallImagesPath = currentImageLibrary for i in range(len(dirs)): if not os.path.isdir(smallImagesPath): os.mkdir(smallImagesPath) imagePath = os.path.join(imagePath, dirs[i]) smallImagesPath = os.path.join(smallImagesPath, dirs[i]) imagePath = "%s_%s.jpg" % (imagePath, version) smallImagesPath = "%s_%s.jpg" % (smallImagesPath, version) elif currentAssetCategory == "characters": nodeSplits = nodeName.split("_") for nodeSplit in nodeSplits: if nodeSplit in chesspieceTypes: divider = nodeSplit dirParts = nodeName.split("_%s" % divider)[0].split("_") imagePath = currentAssetLibrary smallImagesPath = currentImageLibrary dividerGRP = "%s_GRP" % divider version = nodeName.split("_%s_" % dividerGRP)[1].split("_")[0] for i in range(2): # eg bg (background) and buffalo if dirParts[i+1] in charType.keys(): dirs.append(charType[dirParts[i+1]]) elif re.search('^[A-Z]+', dirParts[i+1]): print '%s_%s' % (dirParts[i+1], dirParts[i+2]) dirs.append('%s_%s' % (dirParts[i+1], dirParts[i+2])) else: dirs.append(dirParts[i+1]) fileName = nodeName.rpartition("_%s" % dividerGRP)[0].replace("%s_%s_" % (dirParts[0], dirParts[1]), "") fileVersionName = "%s_%s_%s" % (fileName, divider, version) for i in range(len(dirs)): if not os.path.isdir(smallImagesPath): os.mkdir(smallImagesPath) imagePath = os.path.join(imagePath, dirs[i]) smallImagesPath = os.path.join(smallImagesPath, dirs[i]) imagePath = os.path.join(imagePath, "chesspiece", "published") imagePath = os.path.join(imagePath, "%s.jpg" % fileVersionName) smallImagesPath = os.path.join(smallImagesPath.rpartition(os.sep)[0], "%s.jpg" % fileVersionName) cmds.select(node, replace=True) currentPanel = "modelPanel4" if not cmds.modelEditor(currentPanel, exists=True): currentPanel = cmds.getPanel(withFocus=True) mel.eval('enableIsolateSelect %s true;' % currentPanel) cmds.isolateSelect(currentPanel, state=1) mel.eval('lookThroughModelPanel persp %s' % currentPanel) cmds.viewFit() if not currentAssetCategory == "characters": cmds.setAttr("perspShape.preScale", 1.5) nearClipPlane = cmds.getAttr("perspShape.nearClipPlane") farClipPlane = cmds.getAttr("perspShape.farClipPlane") cmds.setAttr("perspShape.nearClipPlane", 0.1) cmds.setAttr("perspShape.farClipPlane", 100000) cmds.select(clear=True) cmds.modelEditor(currentPanel, edit=True, displayAppearance="smoothShaded", displayTextures=True, displayLights="default") cmds.playblast( frame=1, format="image", completeFilename=smallImagesPath, clearCache=True, viewer=False, showOrnaments=False, compression="jpg", quality=40, percent=100, widthHeight=[144,144] ) cmds.playblast( frame=1, format="image", completeFilename=imagePath, clearCache=True, viewer=False, showOrnaments=False, compression="jpg", quality=40, percent=100, widthHeight=[1024,768] ) cmds.isolateSelect(currentPanel, state=0) cmds.setAttr("perspShape.preScale", 1.0) cmds.setAttr("perspShape.nearClipPlane", nearClipPlane) cmds.setAttr("perspShape.farClipPlane", farClipPlane) sys.stdout.write("Screen grab saved to: %s\n" % imagePath)
mc.setAttr("ten_robe_model_main_TEN_ROBE_HERO.translateZ", tz) mc.setAttr("ten_robe_model_main_TEN_ROBE_HERO.rotateX", rx) mc.setAttr("ten_robe_model_main_TEN_ROBE_HERO.rotateY", ry) mc.setAttr("ten_robe_model_main_TEN_ROBE_HERO.rotateZ", rz) generateScene() ####################### ## Set Up Simulation ## ####################### #This code is brought to you in part by Brennan Mitchell and viewers like you. Thank you. mc.select('ten_robe_sim_model_main_ten_collide_body', replace=True) mc.viewFit() #Snap View to Body Collider mc.playbackOptions(animationStartTime=STARTPRE) mc.playbackOptions(minTime=STARTPRE) mc.currentTime(STARTPRE) #Wrap Colliders to Alembic mc.select('ten_robe_sim_model_main_ten_collide_body', replace=True) #Wrap Body mc.select('TEN_ANIM', add=True) mc.CreateWrap() #mc.setAttr('wrap1.exclusiveBind', 0) mc.select('ten_robe_sim_model_main_ten_collide_mitten_l', replace=True) #Wrap Left Mitten mc.select('TEN_ANIM', add=True) mc.CreateWrap() #mc.setAttr('wrap2.exclusiveBind', 0)
def do(nodes=None): """ Publish shader attached to nodes. @param nodes: One or more GEO or shader nodes. """ currentShaderLibrary = getAssetShaderLibrary() # Swatches file storage location. if not os.path.isdir(currentShaderLibrary): raise Exception("Directory %s does not exist" % currentShaderLibrary) if not nodes: nodes = cmds.ls(selection=True, long=True) # If still no nodes... if not nodes: sys.stdout.write("Select a mesh with an attached shader to be published.\n") if not isinstance(nodes, list): nodes = [nodes] for node in nodes: currentNode = node # Check if referenced. if cmds.referenceQuery(node, isNodeReferenced=True): confirm = cmds.confirmDialog( title="Warning", messageAlign="center", message="Cannot publish a referenced shader. Try importing from reference.", button=["Ok"], defaultButton="Ok", cancelButton="Ok", dismissString="Ok", ) if confirm == "Ok": return # If node is not a mesh, look for a shading engine. if not cmds.listRelatives(currentNode, shapes=True): # Check if node is a GRP with one mesh below. children = cmds.listRelatives(currentNode, children=True) if children: if len(children) == 1 and cmds.listRelatives(children[0], shapes=True): currentNode = children[0] else: confirm = cmds.confirmDialog( title="Warning", messageAlign="center", message="Unable to determine which shader to publish.", button=["Ok"], defaultButton="Ok", cancelButton="Ok", dismissString="Ok", ) if confirm == "Ok": return else: # Look for a connected shading engine. shadingEngines = [ x for x in (cmds.listHistory(currentNode, future=True) or []) if cmds.nodeType(x) == "shadingEngine" ] if shadingEngines: currentNode = shadingEngines[0] else: confirm = cmds.confirmDialog( title="Warning", messageAlign="center", message="Unable to find a shader to publish.", button=["Ok"], defaultButton="Ok", cancelButton="Ok", dismissString="Ok", ) if confirm == "Ok": return # Get the shader category. directory = getCategoryFolder() shadingEngine = doNameShaders(node=currentNode, directory=directory) if not shadingEngine: continue rootName = shadingEngine.replace("_SG", "") # Create swatch. swatch = cmds.polyPlane(name="%s_Swatch" % rootName, width=1, height=1, sx=1, sy=1, ax=[0, 0, 1], ch=0) swatchShape = cmds.listRelatives(swatch, shapes=True, path=True) cmds.sets(swatchShape, forceElement=shadingEngine) imagePath = os.path.join(directory, "%s.png" % rootName) # Create snapshot. screenGrabCam = cmds.camera(centerOfInterest=378.926) cmds.setAttr("%s.tz" % screenGrabCam[0], 378.926) cmds.setAttr("%s.orthographic" % screenGrabCam[1], 1) cmds.select(swatch, replace=True) currentPanel = "modelPanel4" if not cmds.modelEditor(currentPanel, exists=True): currentPanel = cmds.getPanel(withFocus=True) mel.eval("enableIsolateSelect %s true;" % currentPanel) cmds.isolateSelect(currentPanel, state=1) mel.eval("lookThroughModelPanel %s %s" % (screenGrabCam[0], currentPanel)) cmds.viewFit() cmds.setAttr("%s.orthographicWidth" % screenGrabCam[1], 1) cmds.select(clear=True) gridValue = cmds.modelEditor(currentPanel, query=True, grid=True) cmds.modelEditor( currentPanel, edit=True, displayAppearance="smoothShaded", displayTextures=True, displayLights="default", grid=False, ) cmds.playblast( frame=1, format="image", completeFilename=imagePath, clearCache=True, viewer=False, showOrnaments=False, compression="png", quality=40, percent=100, widthHeight=[144, 144], ) cmds.isolateSelect(currentPanel, state=0) cmds.modelEditor(currentPanel, edit=True, grid=gridValue) mel.eval("lookThroughModelPanel persp %s" % currentPanel) cmds.delete(screenGrabCam[0]) sys.stdout.write("Screen grab of swatch saved to: %s\n" % imagePath) # Delete unknown nodes (mental ray). ddDeleteUnknownNodes.do() # Export swatch file. swatchPath = os.path.join(directory, "%s.ma" % rootName) cmds.select(swatch, replace=True) exportedFile = cmds.file(swatchPath, type="mayaAscii", exportSelected=True, force=True) ddRemoveRequires.do(path=swatchPath) if exportedFile: cmds.delete(swatch)
def renderImagesFromCameras(self, generalSettings, fluidIndex, progress, progressIndex): """ :type generalSettings: MayaCacheCmdSettings """ listRenderedImages = list() self.viewFromCamPosition('PERSPECTIVE', generalSettings.fluidBoxName) renderImageFlag = False # True --> Images are rendered if (generalSettings.cam_perspective) == True | (generalSettings.cam_viewcube == True) | (generalSettings.cam_custom_name != None) | (generalSettings.cam_rotation != 0): renderImageFlag = True # Create image folder path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/" if not os.path.exists(path) & renderImageFlag: os.mkdir(path) # Settings fileName = "image" start = str(int(round(generalSettings.animationStartTime))) end = str(int(round(generalSettings.animationEndTime))) if generalSettings.cam_perspective: self.viewFromCamPosition('PERSPECTIVE', generalSettings.fluidBoxName) path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/perspective/" listRenderedImages.append(path) os.mkdir(path) #self.executeMELRemderCmd(path, fileName, start, end, resW, resH) mel.eval('RenderIntoNewWindow') # Rendering try: self.renderImages(path, fileName, start, end) except Exception as e: raise e return progressIndex += 1 progress.setValue(progressIndex) if (generalSettings.cam_viewcube == True): os.mkdir(generalSettings.outputPath + "/" + str(fluidIndex) + "/images/viewcube/") # FRONT self.viewFromCamPosition('FRONT', generalSettings.fluidBoxName) path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/viewcube/FRONT/" listRenderedImages.append(path) os.mkdir(path) #self.renderImages(path, fileName, start, end) try: self.renderImages(path, fileName, start, end) except Exception as e: raise e return progressIndex += 1 progress.setValue(progressIndex) # RIGHT self.viewFromCamPosition('RIGHT', generalSettings.fluidBoxName) path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/viewcube/SIDE/" listRenderedImages.append(path) os.mkdir(path) #self.renderImages(path, fileName, start, end) try: self.renderImages(path, fileName, start, end) except Exception as e: raise e return progressIndex += 1 progress.setValue(progressIndex) # TOP self.viewFromCamPosition('TOP', generalSettings.fluidBoxName) path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/viewcube/TOP/" listRenderedImages.append(path) os.mkdir(path) self.renderImages(path, fileName, start, end) progressIndex += 1 progress.setValue(progressIndex) if (generalSettings._cam_custom_name != None): # View from camera try: cmdStr = "lookThroughModelPanel" + " " + str(generalSettings.cam_custom_name) + " " + "modelPanel4;" mel.eval(cmdStr) except Exception as er: self.lgr.error('An error occured while camera was changed! Details: %s', er.message) self.lgr.error('Could not look through camera %s', generalSettings._cam_custom_name) raise Exception(er.message) return #cmdStr = "lookThroughModelPanel" + " " + str(generalSettings.cam_custom_name) + " " + "modelPanel4;" #mel.eval(cmdStr) path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/custom/" os.mkdir(path) mel.eval('RenderIntoNewWindow') #self.renderImages(path, fileName, start, end) try: self.renderImages(path, fileName, start, end) except Exception as e: raise e return progressIndex += 1 progress.setValue(progressIndex) listRenderedImages.append(path) self.viewFromCamPosition('PERSPECTIVE', generalSettings.fluidBoxName) if generalSettings.cam_rotation != 0: # Change to perspective camera self.viewFromCamPosition('PERSPECTIVE', generalSettings.fluidBoxName) cmds.viewFit('persp', an=False) path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/rotation/" os.mkdir(path) # Rotate stepAcc = 0 valueY = int(round(float(generalSettings.cam_rotation))) while stepAcc < 360: # Rotate camera cmds.setAttr('persp.rotateY', stepAcc) cmds.viewFit('persp', an=False) #cmds.dolly(d=-15) path = generalSettings.outputPath + "/" + str(fluidIndex) + "/images/rotation/" + "deg_" + str(stepAcc) + "/" os.mkdir(path) try: self.renderImages(path, fileName, start, end) except Exception as e: raise e return listRenderedImages.append(path) stepAcc = stepAcc + valueY progressIndex += 1 progress.setValue(progressIndex) cmds.viewFit('persp', an=False) return [int(progressIndex), listRenderedImages]
def boxParty(bpm, songLen, numBoxes): cmds.camera() cmds.rename('partyCam') bps = bpm/60.0 fpb = 24/bps cmds.polyCube(name='boxMain', w=1,h=1,d=1) for i in range(0,numBoxes): cmds.select('boxMain') cmds.instance(name= 'box' + str(i)) randX = random.random()*10 - 5 randY = random.random()*10 - 5 randZ = random.random()*10 - 5 cmds.xform(t=(randX,randY,randZ)) cmds.hide('boxMain') cmds.select([node for node in cmds.ls() if 'box' in node and 'Shape' not in node]) cmds.group(name='dancingBoxes') cmds.select('dancingBoxes') cmds.viewFit('partyCamShape') #for each beat framesKeyed = 0 elevAngle = 0 #moveToggle = True beat = 1 while framesKeyed/24 < songLen: cmds.currentTime(framesKeyed-fpb+4) # set time to get latest position for i in range(0,numBoxes): #pulsing cmds.select('box'+str(i)) cmds.setKeyframe(at='scaleX', value=1, t=framesKeyed-2) cmds.setKeyframe(at='scaleX', value=1.7, t=framesKeyed) cmds.setKeyframe(at='scaleX', value=1, t=framesKeyed+2) cmds.setKeyframe(at='scaleY', value=1, t=framesKeyed-2) cmds.setKeyframe(at='scaleY', value=1.7, t=framesKeyed) cmds.setKeyframe(at='scaleY', value=1, t=framesKeyed+2) cmds.setKeyframe(at='scaleZ', value=1, t=framesKeyed-2) cmds.setKeyframe(at='scaleZ', value=1.7, t=framesKeyed) cmds.setKeyframe(at='scaleZ', value=1, t=framesKeyed+2) #translating if beat == 1 or beat == 3: cmds.select('box' + str(i)) pos = cmds.xform(ws=True, q=True, t=True) direction = random.randint(0,2) displacement = random.randint(0,10) - 5 #try to keep within borders while pos[direction] + displacement > 6 or pos[direction] + displacement < -6: displacement = random.randint(0,10) - 5 direction = random.randint(0,2) if direction == 0: #going in x direction cmds.setKeyframe(at='translateX', value = pos[0], t = framesKeyed) cmds.setKeyframe(at='translateX', value = pos[0] + displacement, t = framesKeyed+4) cmds.setKeyframe(at='translateY', value = pos[1], t=framesKeyed) cmds.setKeyframe(at='translateY', value = pos[1], t=framesKeyed+4) cmds.setKeyframe(at='translateZ', value = pos[2], t=framesKeyed) cmds.setKeyframe(at='translateZ', value = pos[2], t=framesKeyed+4) elif direction == 1: #going in y direction cmds.setKeyframe(at='translateY', value = pos[1], t = framesKeyed) cmds.setKeyframe(at='translateY', value = pos[1] + displacement, t = framesKeyed+4) cmds.setKeyframe(at='translateX', value = pos[0], t=framesKeyed) cmds.setKeyframe(at='translateX', value = pos[0], t=framesKeyed+4) cmds.setKeyframe(at='translateZ', value = pos[2], t=framesKeyed) cmds.setKeyframe(at='translateZ', value = pos[2], t=framesKeyed+4) else: #going in z direction cmds.setKeyframe(at='translateZ', value = pos[2], t = framesKeyed) cmds.setKeyframe(at='translateZ', value = pos[2] + displacement, t = framesKeyed+4) cmds.setKeyframe(at='translateX', value = pos[0], t=framesKeyed) cmds.setKeyframe(at='translateX', value = pos[0], t=framesKeyed+4) cmds.setKeyframe(at='translateY', value = pos[1], t=framesKeyed) cmds.setKeyframe(at='translateY', value = pos[1], t=framesKeyed+4) #key partyCam every 4 beats if beat == 1: cmds.setKeyframe('partyCam', at='translateX', t = framesKeyed) cmds.setKeyframe('partyCam', at='translateY', t = framesKeyed) cmds.setKeyframe('partyCam', at='translateZ', t = framesKeyed) cmds.setKeyframe('partyCam', at='rotateX', t = framesKeyed) cmds.setKeyframe('partyCam', at='rotateY', t = framesKeyed) cmds.setKeyframe('partyCam', at='rotateZ', t = framesKeyed) elevAngleChange = random.random()*70 - 35 aAngleChange = random.random()* 360 - 180 if elevAngle + elevAngleChange > 70 or elevAngle + elevAngleChange < -20: elevAngle = elevAngle - elevAngle else: elevAngle = elevAngle + elevAngleChange cmds.tumble('partyCamShape', ea=elevAngle, aa=aAngleChange) cmds.setKeyframe('partyCam', at='translateX', t = framesKeyed+4) cmds.setKeyframe('partyCam', at='translateY', t = framesKeyed+4) cmds.setKeyframe('partyCam', at='translateZ', t = framesKeyed+4) cmds.setKeyframe('partyCam', at='rotateX', t = framesKeyed+4) cmds.setKeyframe('partyCam', at='rotateY', t = framesKeyed+4) cmds.setKeyframe('partyCam', at='rotateZ', t = framesKeyed+4) if beat == 4: beat = 1 else: beat += 1 framesKeyed += fpb
def rotateCamerY(valueY): stepAcc = 0 while stepAcc < 360: stepAcc = stepAcc + valueY cmds.setAttr('persp.rotateY', stepAcc) cmds.viewFit('persp', an=False)