def remove_sub_frames(obj_list): ''' Sets a key on every whole frame over the keyed range of all objects, then removes all subframe keys. Args: obj_list (list<PyNode>): List of all objects to remove sub frames on ''' #pm.select(None) #for model_panel in pm.getPanel(type='modelPanel'): # pm.isolateSelect(model_panel, state=True) #pm.refresh(su=True) try: key_frame_list = list(set(pm.keyframe(obj_list, q=True))) key_frame_list.sort() first_keyframe = get_first_or_default(key_frame_list) last_keyframe = get_last_or_default(key_frame_list) time_range = (int(first_keyframe), int(last_keyframe)) current_time = pm.currentTime() for frame in xrange(time_range[0], time_range[1] + 1): pm.currentTime(frame) pm.setKeyframe(obj_list) except: pass finally: pm.refresh(su=False) for model_panel in pm.getPanel(type='modelPanel'): pm.isolateSelect(model_panel, state=False) pm.currentTime(current_time) pm.select(obj_list, r=True) for frame in [x for x in key_frame_list if x % 1 > 0]: pm.cutKey(obj_list, t=frame)
def toggleIsolateSelected(): """Toggle isolated view of selection""" newState = not pm.isolateSelect( 'modelPanel4', query=True, state=True ) for i in range( 1, 5 ): pm.isolateSelect( 'modelPanel%s' % i, state=newState ) pm.isolateSelect( 'modelPanel%s' % i, addSelected=True )
def isolate_current_panel(add=False, *args): panel = pm.paneLayout('viewPanes', q=1, pane1=1) state = pm.isolateSelect(panel, q=1, state=1) pm.editor(panel, e=1, mainListConnection="activeList") pm.isolateSelect(panel, loadSelected=1) pm.isolateSelect(panel, state=not state) if add: pm.editor(panel, e=1, unlockMainConnection=1) else: pm.editor(panel, e=1, lockMainConnection=1)
def isolateSelect(sel, *args, **kwargs): view = pm.paneLayout('viewPanes', q=True, pane1=True) # inverting a query of the current boolean state returns the toggled value new_state = 1 - int(pm.isolateSelect(view, q=True, state=True)) pm.isolateSelect(view, state=new_state) if new_state == 1: # when toggling on.... pm.isolateSelect(view, u=True) # update with the current selection pm.mel.eval('enableIsolateSelect ' + view + ' true;') # and use this MEL script for some reason
def openTransform(): controlObj = pm.ls(selection=True) parentObject = pm.listRelatives(controlObj[0], parent=True)[0] print("parentObject= %s" % parentObject) constraint = pm.listConnections(controlObj[0], type="parentConstraint")[0] print("constraint= %s" % constraint) joints = pm.listConnections(constraint, type="joint")[0] print("joints= %s" % joints) skinCluster = pm.listConnections(joints, type="skinCluster")[0] print("skinCluster= %s" % skinCluster) geometry = pm.listConnections(skinCluster, type="mesh")[0] print("geometry= %s" % geometry) pm.select(geometry, replace=True) pm.select(parentObject, add=True) pm.isolateSelect("modelPanel4", state=1) pm.isolateSelect("modelPanel4", loadSelected=1) print("isolating = \n%s, \n%s" % (geometry, parentObject)) pm.select(parentObject, replace=True) pm.delete(constraint) return joints, controlObj
def IsolateSelected(state=True, showSelected=False): if state: # turn ON isolation if not showSelected: # hide everything ( useful during point cache ) pm.select(clear=True) allModelPanels = pm.getPanel(type='modelPanel') for onePanel in allModelPanels: if pm.isolateSelect(onePanel, q=True, state=True): pm.isolateSelect(onePanel, loadSelected=True) #pm.isolateSelect( onePanel, update=True ) mel.eval('doReload %s;' % onePanel) else: pm.isolateSelect(onePanel, state=True) #pm.isolateSelect( onePanel, update=True ) mel.eval('doReload %s;' % onePanel) else: # turn OFF isolation allModelPanels = pm.getPanel(type='modelPanel') for onePanel in allModelPanels: pm.isolateSelect(onePanel, state=False)
def IsolateSelected( state=True, showSelected=False ): if state: # turn ON isolation if not showSelected: # hide everything ( useful during point cache ) pm.select( clear=True ) allModelPanels = pm.getPanel( type='modelPanel' ) for onePanel in allModelPanels: if pm.isolateSelect( onePanel, q=True, state=True ): pm.isolateSelect( onePanel, loadSelected=True ) #pm.isolateSelect( onePanel, update=True ) mel.eval( 'doReload %s;'%onePanel ) else: pm.isolateSelect( onePanel, state=True ) #pm.isolateSelect( onePanel, update=True ) mel.eval( 'doReload %s;'%onePanel ) else: # turn OFF isolation allModelPanels = pm.getPanel( type='modelPanel' ) for onePanel in allModelPanels: pm.isolateSelect( onePanel, state=False )
def isoSel(mode=0, focus=False): sel = pm.ls(sl=True) # Store current focus panel currentPanel = getFocusPanel() or [] # Get the modelPanel from current scene visPanels = pm.getPanel(vis=True) or [] modelPanels = [] if visPanels: for each in visPanels: if "modelPanel" in each: modelPanels.append(each) if modelPanels: for each in modelPanels: # If focus = True, will only add/remove selected objects for the isolate select if focus: # If the model panel does not equal the current panel, continue the loop if each != currentPanel: continue # Add selected objects for the isolate select if sel: # mode == 0 : Add selected mode if mode == 0: pm.isolateSelect(each, addSelected=1) # mode == 1 : Remove selected mode if mode == 1: pm.isolateSelect(each, removeSelected=1) # If noting selected will turn off the isolate select else: pm.isolateSelect(each, state=0) # Return to previous focus panel setFocusPanel(currentPanel)
def previewSaver(self, name, assetDirectory): """ Saves the preview files under the Asset Directory Args: name: (Unicode) Name of the Asset assetDirectory: (Unicode) Directory of Asset Returns: (Tuple) Thumbnail path, Screenshot path, Wireframe path """ logger.info("Saving Preview Images") selection = pm.ls(sl=True) validShapes = pm.listRelatives(selection, ad=True, type=["mesh", "nurbsSurface"]) thumbPath = os.path.join(assetDirectory, '%s_thumb.jpg' % name) SSpath = os.path.join(assetDirectory, '%s_s.jpg' % name) WFpath = os.path.join(assetDirectory, '%s_w.jpg' % name) # make sure the viewport display is suitable panel = pm.getPanel(wf=True) if pm.getPanel(to=panel) != "modelPanel": logger.warning( "The focus is not on a model panel, using the perspective view" ) panel = pm.getPanel(wl="Persp View") # Somehot wl dont return a regular string, convert it to a regular string t = "" for z in panel: t += z panel = t pm.modelEditor(panel, e=1, allObjects=1) pm.modelEditor(panel, e=1, da="smoothShaded") pm.modelEditor(panel, e=1, displayTextures=1) pm.modelEditor(panel, e=1, wireframeOnShaded=0) pm.viewFit() pm.isolateSelect(panel, state=1) pm.isolateSelect(panel, addSelected=True) # temporarily deselect pm.select(d=True) pm.setAttr("defaultRenderGlobals.imageFormat", 8) # This is the value for jpeg frame = pm.currentTime(query=True) # thumb pm.playblast(completeFilename=thumbPath, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, frame=[frame], viewer=False) # screenshot pm.playblast(completeFilename=SSpath, forceOverwrite=True, format='image', width=1600, height=1600, showOrnaments=False, frame=[frame], viewer=False) # Wireframe pm.modelEditor(panel, e=1, displayTextures=0) pm.modelEditor(panel, e=1, wireframeOnShaded=1) pm.playblast(completeFilename=WFpath, forceOverwrite=True, format='image', width=1600, height=1600, showOrnaments=False, frame=[frame], viewer=False) pm.select(selection) # UV Snapshot -- It needs logger.info("Saving UV Snapshots") for i in range(0, len(validShapes)): print "validShape", validShapes[i] # transformNode = validShapes[i].getParent() objName = validShapes[i].name() UVpath = os.path.join(assetDirectory, '%s_uv.jpg' % objName) pm.select(validShapes[i]) try: pm.uvSnapshot(o=True, ff="jpg", n=UVpath, xr=1600, yr=1600) except: logger.warning("UV snapshot is missed for %s" % validShapes[i]) pm.isolateSelect(panel, state=0) pm.isolateSelect(panel, removeSelected=True) # TODO // store the scene defaults (camera position, imageFormat, etc. return thumbPath, SSpath, WFpath
def one_cam_to_shots(self): # make sure selected object is a camera sel = pm.selected() if len(sel) != 1: raise RuntimeError('Select just 1 camera.') the_cam = sel[0] if the_cam.getShape().type() != 'camera': message = 'Select just 1 Camera.\r\n' pm.confirmDialog(title='Error', message=message, button='OK') raise RuntimeError('Select just 1 camera.') # unlock locked attrs attributes_locked = [] for attr in pm.listAttr(the_cam, locked=1): attributes_locked.append(attr) for attr in pm.listAttr(the_cam.getShape(), locked=1): attributes_locked.append(attr) for attr in attributes_locked: the_cam.attr(attr).unlock() id = 0 for shot in self.shots_descending: s_frame = shot.getStartTime() e_frame = shot.getEndTime() # duplicate, clear parents and unparent shot cam from original pm.currentTime(s_frame) id += 1 shot_camera = pm.duplicate(the_cam, rr=1, name='camera__shotExp_%s' % str(id)) tr_parents = shot_camera[0].listRelatives(type='transform') for tr in tr_parents: pm.delete(tr) pm.parent(shot_camera, w=1) # connect animation curves from original to duplicated shot cam anim_curves = [] connections = the_cam.getShape().listConnections() for connection in connections: if 'animCurve' in str(connection.type()): attribute_name = str( connection.listConnections(p=1)[0].split('.')[-1:][0]) new_key = pm.duplicate(connection, rr=1) anim_curves.append(new_key[0]) pm.connectAttr( '%s.output' % new_key[0], '%s.%s' % (shot_camera[0].getShape(), attribute_name)) # parent constraint shot cam to original constraint = pm.parentConstraint(the_cam, shot_camera[0], mo=0, weight=1) # isolate none to speed things up panel_list = pm.getPanel(type='modelPanel') pm.select(None) for panel in panel_list: pm.isolateSelect(panel, state=1) # bake all keyable attrs between shot frame range pm.mel.eval( 'bakeResults -simulation true -t "%s:%s" -sampleBy 1 -disableImplicitControl true ' '-preserveOutsideKeys true -sparseAnimCurveBake false -removeBakedAttributeFromLayer false ' '-bakeOnOverrideLayer false -minimizeRotation true -controlPoints false -shape true %s;' % (int(s_frame), int(e_frame), shot_camera[0])) # restore isolation for panel in panel_list: pm.isolateSelect(panel, state=0) # set some forced attrs shot_camera[0].disconnectAttr('scaleX') shot_camera[0].setAttr('scaleX', 1) shot_camera[0].disconnectAttr('scaleY') shot_camera[0].setAttr('scaleY', 1) shot_camera[0].disconnectAttr('scaleZ') shot_camera[0].setAttr('scaleZ', 1) shot_camera[0].disconnectAttr('visibility') shot_camera[0].setAttr('visibility', 1) shot_camera[0].getShape().disconnectAttr('farClipPlane') shot_camera[0].getShape().setAttr('farClipPlane', 10000000) # make all camera anim curves linear for curve in shot_camera[0].listAttr(k=1): pm.selectKey(curve, add=1, k=1) pm.keyTangent(itt='linear', ott='linear') for curve in shot_camera[0].getShape().listAttr(k=1): pm.selectKey(curve, add=1, k=1) pm.keyTangent(itt='linear', ott='linear') # no need for constraint node pm.delete(constraint) # lock previously unlocked attrs again for attr in attributes_locked: the_cam.attr(attr).lock() # set shot camera pm.select(cl=1) shot.set_camera(shot_camera[0])
def BakeTransform( self, bakeOnNewLocator=True, *args ): # BakeTransform( bakeOnNewLocator=False ) ''' Useful for exporting translate and rotate animation to other 3D packages. if bakeOnNewLocator in True: For every selected object, creates a locator and bakes object's animation on this locator. if bakeOnNewLocator in False: For every selected object, bakes their translate, rotate and scale animations in world space. ''' objs = pm.ls( sl=True ) if not objs: pm.warning( "ehm_tools...BakeAnimation: Select an object to bake it's transform animation." ) return try: # get info from UI, if in UI mode selectedItem = pm.radioCollection( self.bakeModeRC, q=True, select=True ) bakeOnNewLocatorState = pm.radioButton( selectedItem, q=True, label=True ) if bakeOnNewLocatorState == 'Bake On New Locator': bakeOnNewLocator=True else: bakeOnNewLocator=False except: pass timeRange = self.getTimeRange() locs = [] cons = [] # for each selected object... for obj in objs: # bake it's animation on a new locator if obj.type() in [ 'transform', 'joint' ]: loc = pm.spaceLocator( name= '%s_SRT'%obj.name() ) cons.append( pm.pointConstraint( obj, loc ) ) cons.append( pm.orientConstraint( obj, loc ) ) cons.append( pm.scaleConstraint( obj, loc ) ) # hide all objects to increase speed of baking animation, IsolateSelected( state=True, showSelected=False ) locs.append( loc ) pm.bakeResults( locs , simulation=True, t=timeRange, disableImplicitControl=True, preserveOutsideKeys=True, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, controlPoints=False, shape=False ) # unhide all objects allModelPanels = pm.getPanel( type='modelPanel' ) for onePanel in allModelPanels: pm.isolateSelect( onePanel, state=False ) pm.delete( cons ) pm.select( locs ) cons = [] # for each selected object... if not bakeOnNewLocator: # bake keys on selected objects themseleves not on new locators bakedObjects = pm.group( empty=True, name='baked_objects_grp') for i in range( len(objs) ): UnlockUnhideAttrs( objs = objs[i] ) self.removeConnections( objs = objs[i] ) pm.parent( objs[i], bakedObjects ) cons.append( pm.pointConstraint( locs[i], objs[i] ) ) cons.append( pm.orientConstraint( locs[i], objs[i] ) ) cons.append( pm.scaleConstraint( locs[i], objs[i] ) ) # hide all objects to increase speed of baking animation, IsolateSelected( state=True, showSelected=False ) pm.bakeResults( objs , simulation=True, t=timeRange, disableImplicitControl=True, preserveOutsideKeys=True, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, controlPoints=False, shape=False ) # unhide all objects for onePanel in allModelPanels: pm.isolateSelect( onePanel, state=False ) pm.delete( cons ) pm.delete( locs ) pm.select( objs )
def createTargetIcons(self): self.deleteTargetIcons() panel = getCurrentPannel() isolateState = pymel.isolateSelect(panel, query=True, state=True) radius = 1 if not self.targetIconsShaderA: # make lambert for A spheres lambertA = pymel.shadingNode('lambert', asShader=True, name='DELETE_ME__TEMP_rightLambert') lambertA.addAttr('createColoredVertexSpheres_tempType', dt='string') lambertA.color.set( [0,0,0] ) lambertA.transparency.set( [0.5,0.5,0.5] ) shadingEngineA = pymel.sets(renderable=True, noSurfaceShader=True, empty=True, name='DELETE_ME__TEMP_rightshadingEngine') shadingEngineA.addAttr('createColoredVertexSpheres_tempType', dt='string') pymel.connectAttr(lambertA+".outColor", shadingEngineA+".surfaceShader", force=True) self.targetIconsShaderA = (lambertA, shadingEngineA) if not self.targetIconsShaderB: # make lambert for B spheres lambertB = pymel.shadingNode('lambert', asShader=True, name='DELETE_ME__TEMP_rightLambert') lambertB.addAttr('createColoredVertexSpheres_tempType', dt='string') lambertB.color.set( [0,0,0] ) lambertB.transparency.set( [0.5,0.5,0.5] ) shadingEngineB = pymel.sets(renderable=True, noSurfaceShader=True, empty=True, name='DELETE_ME__TEMP_rightshadingEngine') shadingEngineB.addAttr('createColoredVertexSpheres_tempType', dt='string') pymel.connectAttr(lambertB+".outColor", shadingEngineB+".surfaceShader", force=True) self.targetIconsShaderB = (lambertB, shadingEngineB) # create Icon A targetIconAOrig = pymel.sphere(name='DELETE_ME__targetASpheres', radius=radius, sections=1, startSweep=180, spans=2)[0] #targetIconAOrig = pymel.torus(axis=(0,0,-1), radius=radius*.666, heightRatio=0.33, sections=1, startSweep=20, endSweep=160, spans=4)[0] targetIconAOrig.rename('DELETE_ME__targetASpheres') targetIconAOrig.overrideEnabled.set(1) targetIconAOrig.drawOverride.overrideColor.set(2) targetIconAOrig.addAttr('createColoredVertexSpheres_tempType', dt='string') pymel.sets( shadingEngineA, forceElement=targetIconAOrig, ) # create Icon B targetIconBOrig = pymel.sphere(name='DELETE_ME__targetBSpheres', radius=radius, sections=1, startSweep=180, spans=2)[0] #targetIconBOrig = pymel.torus(axis=(0,0,-1), radius=radius*.666, heightRatio=0.33, sections=1, startSweep=20, endSweep=160, spans=4)[0] targetIconBOrig.rename('DELETE_ME__targetBSpheres') targetIconBOrig.overrideEnabled.set(1) targetIconBOrig.drawOverride.overrideColor.set(2) targetIconBOrig.addAttr('createColoredVertexSpheres_tempType', dt='string') pymel.sets( shadingEngineB, forceElement=targetIconBOrig, ) for shapeID in self.strandSequenceDict: for strandID in self.strandSequenceDict[shapeID]: for point in self.strandSequenceDict[shapeID][strandID]['targetSequences']: targetPointSets = self.strandSequenceDict[shapeID][strandID]['currentTargetSequence'][point] targetPointSetsA = targetPointSets[0] targetPointSetsB = targetPointSets[1] # Instance Sphere A targetIcons = [] for targetA in targetPointSetsA: if targetA is not None: targetIconA = pymel.instance(targetIconAOrig,)[0] targetIconA.rename('DELETE_ME__targetASpheres') targetIcons.append(targetIconA) if isolateState: pymel.isolateSelect(panel, addDagObject=targetIconA) else: targetIcons.append(None) self.strandSequenceDict[shapeID][strandID]['iconsA'][point] = tuple(targetIcons) # Instance Sphere B targetIcons = [] for targetB in targetPointSetsB: if targetB is not None: targetIconB = pymel.instance(targetIconBOrig,)[0] targetIconB.rename('DELETE_ME__targetBSpheres') targetIcons.append(targetIconB) if isolateState: pymel.isolateSelect(panel, addDagObject=targetIconB) else: targetIcons.append(None) self.strandSequenceDict[shapeID][strandID]['iconsB'][point] = tuple(targetIcons) targetIconAOrig.v.set(0) targetIconBOrig.v.set(0) self.setTargetIconPositions() #pymel.select(self.pointsInNodesDict.keys()) #pymel.select(clear=True) pymel.select(self.selection) for shapeID in self.strandInfoDict: shapeNode = self.strandInfoDict[shapeID]['componentInfoDict']['pyShape'] mel.eval( 'hilite %s' % str(shapeNode))
def one_cam_to_shots(self): # make sure selected object is a camera sel = pm.selected() if len(sel) != 1: raise RuntimeError('Select just 1 camera.') the_cam = sel[0] if the_cam.getShape().type() != 'camera': message = 'Select just 1 Camera.\r\n' pm.confirmDialog(title='Error', message=message, button='OK') raise RuntimeError('Select just 1 camera.') # unlock locked attrs attributes_locked = [] for attr in pm.listAttr(the_cam, locked=1): attributes_locked.append(attr) for attr in pm.listAttr(the_cam.getShape(), locked=1): attributes_locked.append(attr) for attr in attributes_locked: the_cam.attr(attr).unlock() id = 0 for shot in self.shots_descending: s_frame = shot.getStartTime() e_frame = shot.getEndTime() # duplicate, clear parents and unparent shot cam from original pm.currentTime(s_frame) id += 1 shot_camera = pm.duplicate(the_cam, rr=1, name='camera__shotExp_%s' % str(id)) tr_parents = shot_camera[0].listRelatives(type='transform') for tr in tr_parents: pm.delete(tr) pm.parent(shot_camera, w=1) # connect animation curves from original to duplicated shot cam anim_curves = [] connections = the_cam.getShape().listConnections() for connection in connections: if 'animCurve' in str(connection.type()): attribute_name = str(connection.listConnections(p=1)[0].split('.')[-1:][0]) new_key = pm.duplicate(connection, rr=1) anim_curves.append(new_key[0]) pm.connectAttr('%s.output' % new_key[0], '%s.%s' % (shot_camera[0].getShape(), attribute_name)) # parent constraint shot cam to original constraint = pm.parentConstraint(the_cam, shot_camera[0], mo=0, weight=1) # isolate none to speed things up panel_list = pm.getPanel(type='modelPanel') pm.select(None) for panel in panel_list: pm.isolateSelect(panel, state=1) # bake all keyable attrs between shot frame range pm.mel.eval('bakeResults -simulation true -t "%s:%s" -sampleBy 1 -disableImplicitControl true ' '-preserveOutsideKeys true -sparseAnimCurveBake false -removeBakedAttributeFromLayer false ' '-bakeOnOverrideLayer false -minimizeRotation true -controlPoints false -shape true %s;' % (int(s_frame), int(e_frame), shot_camera[0])) # restore isolation for panel in panel_list: pm.isolateSelect(panel, state=0) # set some forced attrs shot_camera[0].disconnectAttr('scaleX') shot_camera[0].setAttr('scaleX', 1) shot_camera[0].disconnectAttr('scaleY') shot_camera[0].setAttr('scaleY', 1) shot_camera[0].disconnectAttr('scaleZ') shot_camera[0].setAttr('scaleZ', 1) shot_camera[0].disconnectAttr('visibility') shot_camera[0].setAttr('visibility', 1) shot_camera[0].getShape().disconnectAttr('farClipPlane') shot_camera[0].getShape().setAttr('farClipPlane', 10000000) # make all camera anim curves linear for curve in shot_camera[0].listAttr(k=1): pm.selectKey(curve, add=1, k=1) pm.keyTangent(itt='linear', ott='linear') for curve in shot_camera[0].getShape().listAttr(k=1): pm.selectKey(curve, add=1, k=1) pm.keyTangent(itt='linear', ott='linear') # no need for constraint node pm.delete(constraint) # lock previously unlocked attrs again for attr in attributes_locked: the_cam.attr(attr).lock() # set shot camera pm.select(cl=1) shot.set_camera(shot_camera[0])
def closeTransform(controlObj, joints): pm.makeIdentity(eachObject, apply=True, t=1) pm.parentConstraint(controlObj, joints, mo=True) pm.isolateSelect("modelPanel4", state=0)