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)
Example #3
0
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
Example #4
0
	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 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 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"])
Example #7
0
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 __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 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 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)
Example #11
0
 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)
Example #12
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=':')
Example #13
0
    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
Example #14
0
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)
Example #15
0
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
Example #16
0
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
Example #17
0
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)
Example #19
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 rotateCamerY(valueY):
     stepAcc = 0
     while stepAcc < 360:
         stepAcc = stepAcc + valueY
         cmds.setAttr('persp.rotateY',  stepAcc)
         cmds.viewFit('persp', an=False)