def nuke():
    ilrNodeTypes = [
        u"ilrAshikhminShader",
        u"ilrBakeLayer",
        u"ilrBakeLayerManager",
        u"ilrBasicPhotonShader",
        u"ilrBssrdfShader",
        u"ilrDielectricPhotonShader",
        u"ilrDielectricShader",
        u"ilrHwBakeVisualizer",
        u"ilrLuaNode",
        u"ilrNormalMap",
        u"ilrOccData",
        u"ilrOccSampler",
        u"ilrOptionsNode",
        u"ilrOrenNayarShader",
        u"ilrOutputShaderBackendNode",
        u"ilrPhysicPhotonShader",
        u"ilrPointCloudShape",
        u"ilrPolyColorPerVertex",
        u"ilrRaySampler",
        u"ilrShadowMask",
        u"ilrSurfaceThickness",
        u"ilrUIOptionsNode",
        u"ilrUVMappingVisualizer",
    ]
    nodes = mc.ls(type=ilrNodeTypes)
    if nodes:
        mc.lockNode(nodes, l=False)
        mc.delete(nodes)
        mc.flushUndo()
        mc.unloadPlugin("Turtle.mll")
    else:
        mc.warning("No Turtle nodes found.")
Example #2
0
 def deleteIShatterCtx(self):
     '''
     Delete IShatter Context Tool
     '''
     cmds.deleteUI(self._mContext)
     cmds.modelEditor('modelPanel4', edit = True, grid = True)       
     
     cmds.scriptEditorInfo (clearHistory = True)
     cmds.flushUndo()   
Example #3
0
    def fix(self):
        """Remove all "unsupported" plugin nodes and unload plugins."""

        cmds.lockNode(self.errorNodes, l=False)
        cmds.delete(self.errorNodes)
        cmds.flushUndo()
        for plugin in self.errorPlugins:
            cmds.unloadPlugin(plugin)

        self.run()
def reloadPlugin(pluginName, **keywords):
	"""
	Quickly reload a plug-in during testing
	@param reload Specifies whether or not to close and reopen the current file
	"""
	file = cmds.file(q=True, sn=True)
	if keywords.setdefault('reload') == True: cmds.file(f=True, new=True)
	cmds.flushUndo()
	cmds.unloadPlugin(pluginName)
	cmds.loadPlugin(pluginName)
	if keywords.setdefault('reload') == True: cmds.file(file, o=True)
Example #5
0
def askFlushUndo():
    confirm = cmds.confirmDialog(t="flushUndo",
                                 m='Do you want to flush undo ?',
                                 ma="center",
                                 b=['Yes','No'],
                                 db='Yes',
                                 cb='No',
                                 ds='No')

    if confirm == "Yes":
        print "flushUndo..."
        cmds.flushUndo()
    else:
        print "abort..."
Example #6
0
def reload_plugin(plugin_name):
    '''
    Safely reloading a plug-in without restarting Maya
    '''
    # clear the scene
    cmds.file(f=True, new=True)
    
    # Clear the undo queueW
    cmds.flushUndo()
    
    # Unload the plug-in
    cmds.unloadPlugin(plugin_name)
    
    # Reload the plug-in
    cmds.loadPlugin(plugin_name)
Example #7
0
def reloadFile():
    '''
    Reloads Maya scene to free memory and increase performance.
    
    A copy of the file is saved as filename.tmp and opened. The open file is renamed to the original filename
    '''
    deState = cmds.file(de=1,q=1)
    cmds.file(de=0)
    fullFileName = cmds.file(exn=1,q=1)
    fileName = fullFileName.rpartition('/')[-1]
    fileLocation = fullFileName.rpartition('/')[0]
    tmpName = cmds.file(rn=fileName+'.tmp')
    cmds.file(s=1,de=0)
    cmds.file(new=1,force=1)
    cmds.file(tmpName,o=1)
    cmds.file(rn=fileName)
    cmds.file(de=deState)
    cmds.flushUndo()
Example #8
0
def pub_cutPiece(_baseObj, _locName, _crack, _sel):
	if len(_sel) == 0:
		_locs = mc.ls(sl=True)
	else:
		_locs = _sel

	_locCenter = ""
	_locToRemove = ""

	_val = -1
	_pieceNumber = len(_locs)

	for _i in range (0, _pieceNumber):

		if _locName == _locs[ _i ]:

			_obj = mc.duplicate( _baseObj )
			mc.setAttr( _obj[0] + ".visibility", 1)
			mc.setAttr( _obj[0] + ".template", 0)
			for _j in range (0, _pieceNumber):

				if _i < _j:
					_val = 1
					_locCenter = _locs[_i]
					_locToRemove = _locs[_j]
				else:
					_val = 0
					_locCenter = _locs[_j]
					_locToRemove = _locs[_i]

				if _i != _j:
					priv_doCut(_val, _locCenter, _locToRemove, _obj[0], _crack)

			# add _crack attribute
			mc.addAttr( _obj[0], ln="factureCrack", at="float", keyable=False)
			mc.setAttr( _obj[0] + ".factureCrack", _crack)
			#connect the locator to the piece - later to be used is a cleaning is required
			mc.connectAttr(_obj[0] + ".displayHandle", _locs[_i] + ".displayHandle", force=True)

			mc.setAttr( _obj[0] + ".visibility", 1)
			mc.setAttr( _obj[0] + ".template", 0)

	mc.flushUndo()
Example #9
0
def nwKilltheTURTLE():
    tShelf = cmds.shelfLayout('TURTLE', exists=True)
    turtle = cmds.pluginInfo('Turtle.mll', loaded=True, q=True)
    if turtle:
        types = cmds.pluginInfo('Turtle.mll', dependNode=True, q=True)
        nodes = cmds.ls(type=types, long=True)
        if nodes:
            cmds.lockNode(nodes, lock=False)
            cmds.delete(nodes)
        cmds.flushUndo()
        cmds.unloadPlugin('Turtle.mll')
    else:
        nmGUI_func.nmGUI_runCheck('error', 'TURTLE already unloaded')
    if tShelf:
        mel.eval('deleteShelfTab "TURTLE";')
        nmGUI_func.nmGUI_runCheck('complete',
                                  'TURTLE unloaded and shelf deleted.')
    else:
        nmGUI_func.nmGUI_runCheck('error', 'TURTLE shelf already deleted')
Example #10
0
def render(start,end,jump=4,thobe="cotton",prefix=None):

    print "Rendering frames %d to %d for dress %s" %(start,end,thobe)
    tfs = get_faces_shaders(thobeDiscription)
    bfs = get_faces_shaders(lowerBodyDiscription)

    bodyfaces = Object("BODY",bfs).faces
    thobefaces = Object(thobe,tfs).faces

    if prefix is None:
        prefix =  "$s/images/" %  PROJECT_ROOT
    
    iffsDir = prefix + "iffs"   
    pngDir = prefix + "pngs"
    
    make_dir(iffsDir)
    make_dir(pngDir)

    cmds.workspace(prefix, o=True)
    cmds.workspace(fileRule=("images",iffsDir))

    for i in range(start,end, jump):
        print "rendering frame",i
        whiten(thobe)
        cmds.currentTime(i)
        start_time = time.time()
        update_faces(bodyfaces)
        update_faces(thobefaces)
        sort_by_y(bodyfaces)
        sort_by_y(thobefaces)
        print "scene updated for frame",i
        scan_lines(thobefaces,bodyfaces)
        cmds.hwRender(currentFrame= True)
        ###offset = 16 (camera) * (frame number)/jump
        iff.convert(iffsDir,pngDir,only=str(i),offset=16*i/jump)
        print("finished timeframe %d --- %s seconds ---" % (i,time.time() - start_time))
        #cmds.clearCache( all=True )
        cmds.flushUndo()
        cmds.clearCache( all=True )
        cmds.DeleteHistory()
Example #11
0
 def delObjectToShatterCmd(self, *args):
     '''
     
     '''
     if not (cmds.draggerContext(self._IScontextTool._mContext, exists = True)):           
         
         if cmds.objExists(self._IScontextTool._mVoroObject):
             
             mBreakNode = cmds.listConnections(self._IScontextTool._mVoroObject, sh = True, type = 'fxBreakGeometry')
             if mBreakNode:              
             
                 bDelete = cmds.confirmDialog(title = 'IShatter Warning', message = 'Remove FractureFX Nodes on ' + self._IScontextTool._mVoroObject + ' ?', button = ['Yes','No'], defaultButton = 'Yes', cancelButton = 'No', dismissString = 'No')
                 if bDelete == 'Yes':
                     
                     iMinTime = cmds.playbackOptions(query = True, minTime = True)
                     cmds.currentTime(iMinTime, edit = True)                    
                     
                     mBreakNode = cmds.listConnections(self._IScontextTool._mVoroObject, sh = True, type = 'fxBreakGeometry')               
                     if mBreakNode:                       
                         mBreakTrs = [cmds.listRelatives(b, parent = True)[0] for b in mBreakNode]
                         cmds.delete(mBreakTrs)                                                
                     
                     mChoiceNode = cmds.listConnections(self._IScontextTool._mVoroObject, sh = True, type = 'fxChoice')
                     if mChoiceNode:
                         mChoiceNode = list(set(mChoiceNode))
                         cmds.delete(mChoiceNode)
                     
                     self._IScontextTool.deleteVoroFragsGRP()
                     cmds.delete(self._IScontextTool._mVoroObject, ch = True)
                     cmds.flushUndo()                   
             
             self.resetIShatterGUI()                       
             
         else:
             cmds.confirmDialog(title = 'Oups... IShatter Error', message = 'Current selected object does not exist anymore !', button = 'OK', defaultButton = 'Yes', cancelButton = 'No', dismissString = 'No')
             self.resetIShatterGUI()                      
Example #12
0
 def uniformVoroPoints(self):
     '''
     Performs voronoi uniform fragmentation
     '''
     # duplicate original shape
     mVoroInputMeshFn = OpenMaya.MFnMesh(self._mVoroInputMeshDAG)
     
     mPoints = OpenMaya.MPointArray()
     mVerticesCount = OpenMaya.MIntArray()
     mVerticesList = OpenMaya.MIntArray()        
     
     mVoroInputMeshFn.getPoints(mPoints, OpenMaya.MSpace.kWorld)
     mVoroInputMeshFn.getVertices(mVerticesCount, mVerticesList)
     mNumPoly = mVoroInputMeshFn.numPolygons()
     
     mCopyMeshFn = OpenMaya.MFnMesh()
     mCopyTrs = mCopyMeshFn.create(mPoints.length(), mNumPoly, mPoints, mVerticesCount, mVerticesList)
     
     mDagPath = OpenMaya.MDagPath()
     OpenMaya.MDagPath.getAPathTo(mCopyTrs, mDagPath)
     mMeshName = mDagPath.fullPathName()             
     
     # create boolean op between sphere and duplicated shape
     mRadius = cmds.getAttr(self._mVoroImpactShape + '.radius')
     mRadius = max(.15, mRadius)
     
     mImpact = cmds.polySphere(r = mRadius, sx = 8, sy = 8)
     cmds.xform(mImpact[0], translation = [self._mOriginPt.x, self._mOriginPt.y, self._mOriginPt.z])
     
     cmds.select(clear = True)       
     mVolume = None
     
     if int(cmds.about(version = True).split()[0]) > 2014:        
         try:
             mVolume = cmds.polyCBoolOp(mMeshName, mImpact[0], op = 3, ch = False, classification = 1, n = 'IS_Volume')
         except:
             pass               
         
     else:
         try:
             mVolume = cmds.polyBoolOp(mMeshName, mImpact[0], op = 3, ch = False, n = 'IS_Volume')
         except:
             pass                    
     
     cmds.flushUndo()
     
     # Check if mVolume is valid
     if mVolume:       
         if cmds.polyEvaluate(mVolume, face = True) == 0:            
             cmds.delete(mVolume)
             mVolume = cmds.polySphere(r = mRadius, sx = 8, sy = 8)
         
     else:
        mVolume = cmds.polySphere(r = mRadius, sx = 8, sy = 8) 
     
     # Fill volume of the boolean object with points
     mSelection = OpenMaya.MSelectionList()
     mSelection.add(mVolume[0])
     mSelection.getDagPath(0, mDagPath)
     mDagPath.extendToShape()
     
     mVerts = OpenMaya.MPointArray()
     triangleCounts, triangleVertices = OpenMaya.MIntArray(), OpenMaya.MIntArray()        
     
     mVolMeshFn = OpenMaya.MFnMesh(mDagPath)
     mVolMeshFn.getPoints(mVerts, OpenMaya.MSpace.kWorld)
     mVolMeshFn.getTriangles(triangleCounts, triangleVertices)
     numTriangles = triangleVertices.length() / 3
     
     mHitPoint = OpenMaya.MFloatPoint()
     mFloatRaySource = OpenMaya.MFloatPoint()
     mFloatRayNormal = OpenMaya.MFloatVector()
     
     # Randomly select a face, find a point on face surface (with bary coords) and launch a ray from the reversed normal
     mAccelerationStructure = mVolMeshFn.autoUniformGridParams()        
     for n in xrange(self._mVoroCount):
         
         triId = rand.randint(0, numTriangles-1)
         v0 = triangleVertices[3 * triId + 0]
         v1 = triangleVertices[3 * triId + 1]
         v2 = triangleVertices[3 * triId + 2]
         
         mVectorAB = mVerts[v1] - mVerts[v0]
         mVectorAC = mVerts[v2] - mVerts[v0]
         mNormal = (mVectorAB ^ mVectorAC) * -1.0
         mNormal.normalize()
         
         u = rand.uniform(0.0,1.0)
         v = rand.uniform(0.0, (1.0 - u))
         
         mSample = (mVerts[v0] + mVectorAB * u + mVectorAC * v) + (mNormal * 0.001)	        
         mFloatRaySource.x, mFloatRaySource.y, mFloatRaySource.z = mSample.x, mSample.y, mSample.z
         mFloatRayNormal.x, mFloatRayNormal.y, mFloatRayNormal.z = mNormal.x, mNormal.y, mNormal.z
         
         hit = mVolMeshFn.closestIntersection(
                                                 mFloatRaySource,
                                                 mFloatRayNormal,
                                                 None,
                                                 None,
                                                 None,
                                                 OpenMaya.MSpace.kWorld,
                                                 99999,
                                                 None,
                                                 mAccelerationStructure,
                                                 mHitPoint,
                                                 None,
                                                 None,
                                                 None,
                                                 None,
                                                 None
                                             )
        
         if hit:
             mDistance = mFloatRaySource.distanceTo(mHitPoint)
             self._mVoroPoints.append(mSample + (mNormal * rand.uniform(0.0, mDistance)))                
     
     mVolMeshFn.freeCachedIntersectionAccelerator()        
     cmds.delete(mVolume)
     
     # hide IShatter sphere helper
     cmds.setAttr(self._mVoroImpactTrs + '.visibility', False)
     cmds.setAttr(self._mVoroImpactShape + '.radius', 0.0001)
     cmds.xform(self._mVoroImpactTrs, translation = [0.0, 0.0, 0.0])
     self._mView.refresh(False, True)        
     
     # update fractureFX
     mel.eval("fxEraseParticles " + self._mVoroParticleObject)
     mVoroParticleSysFn = OpenMayaFX.MFnParticleSystem(self._mVoroParticleSysDAG)
     mVoroParticleSysFn.emit(self._mVoroPoints)
     mVoroParticleSysFn.saveInitialState()                                  
Example #13
0
def pub_cutAll():
	_sel = mc.ls(sl=True)
# START - get the number of pieces
	_pieceNumber = len(_sel) - 1
	if ( _pieceNumber <= 0):
		#print "Not enough cutting points!"
		mm.eval('error -showLineNumber False "Not enough cutting points!";')
# END - get the number of pieces
#
#
# START - get the object to cut and check if it`s valid
	_baseObj = _sel[-1]	# same thing with  _sel[ len(_sel) - 1]
	_shps = mc.listRelatives( _baseObj, shapes=True )
	for _shp in _shps:
#		print mc.objectType( _shp )
		if mc.objectType(_shp) != "mesh":
			#print "Make sure the last object selected is a polygon object!"
			mm.eval('error -showLineNumber False "Make sure the last object selected is a polygon object!";')
# END - get the object to cut and check if it`s valid
#
# START - ask for crack value
	_crack = 0.0;
	_retValue = ui_inputDlg("polyFracture", "Cut offset value (e.g. 0.005):", "0.0")
	if _retValue == "":
		ui_alertv( "Warning", "No value was typed ! Using default: 0" );
	else:
		if mc.about(version=True) == '2010':
			#print('2010')
			if mt.isnan( float( _retValue ) ) == False:
				_crack = float( _retValue )
		else:
			#print('2009')
			if float( _retValue ) != _crack:
				_crack = float( _retValue )
# END - ask for crack value
#
# START - ask user for visual refresh
	_visualRefresh = ui_confirm('Visual refresh', 'Do you wanna see it happening ? :)')
# END - ask user for visual refresh
#
#	 cutting timer
	_startCutTime = mc.timerX()

	_locCenter = "";
	_locToRemove = "";
	_val = -1;

#	 create a group to hold the pieces
	_grp = mc.group(em=True, name=("GRP_" + _baseObj + "_Pieces"))
	mc.xform(os=True, piv=(0, 0, 0))

#START - change current mode to select tool
#	global string $gSelect; setToolTo $gSelect;
#START - Change current selection mode to Select
#START - Preparing Maya statusbar
	ui_addPB( "add", 0, "Preparing fracture data ...", _pieceNumber)
#END - Preparing Maya statusbar
#
#
#START - deactivate undo queue if neccesary
	mc.flushUndo()
	_undoVal = mc.undoInfo( q=True, state=True )
	if _undoVal == 1:
		mc.undoInfo( state=False )
#END - deactivate undo queue if neccesary
#
#
#START - main loop
	for _i in range (0, _pieceNumber):

		gMainProgressBar = mm.eval('$tmp = $gMainProgressBar');
		if mc.progressBar( gMainProgressBar, query=True, isCancelled=True ) :
			break

		 #per piece timer
		_startTime = mc.timerX()

		_obj = mc.duplicate( _baseObj )

		for _j in range (0, _pieceNumber):

			if _i < _j:
				_val = 1
				_locCenter = _sel[_i]
				_locToRemove = _sel[_j]
			else:
				_val = 0
				_locCenter = _sel[_j]
				_locToRemove = _sel[_i]

			if _i != _j:
				priv_doCut(_val, _locCenter, _locToRemove, _obj[0], _crack)

		# add _crack attribute
		mc.addAttr( _obj[0], ln="factureCrack", at="float", keyable=False)
		mc.setAttr( _obj[0] + ".factureCrack", _crack)
		#connect the locator to the piece - later to be used if a cleaning is required
		mc.connectAttr(_obj[0] + ".displayHandle", _sel[_i] + ".displayHandle", force=True)
		mc.setAttr ( _obj[0] + ".visibility", 1)
		mc.setAttr ( _obj[0] + ".template", 0)
		#
		# rename and group
		_newName = mc.rename ( _obj[0], _baseObj + "_p_%d" % _i )
		mc.parent( _newName, _grp)

		if (_i % 10) == 0:
			mc.flushUndo()

		if _visualRefresh == True:
			mc.refresh(cv=True)

		# START - update progresBar
		_totalTime = mc.timerX( startTime= _startTime)
		ui_addPB( "edit", 1, "Calculating piece: %d/%d [ %gs ]   " % (_i, _pieceNumber, _totalTime), 0)
		# END - update progresBar
	mc.select(cl=True)
#START - close the progressBar
	ui_addPB("del", 0, "", 0)
#END - close the progressBar
#
#START - reactivate undo queue if neccesary
	if _undoVal == 1:
		mc.undoInfo( state=True )
#END - reactivate undo queue if neccesary
#
#START - show some statistics
	_totalCutTime = mc.timerX( startTime= _startCutTime)
	print ("Cutting " + _baseObj + " in %d pieces took %g s to complete." % ( _pieceNumber, _totalCutTime ))
def city(name_, size, houseHeightInt, houseWidthInt, windows, booleans, deformers, daytime, glow, environment, colourRange):
    '''
    Generates the city.
    
    name_: String specifying the name of the city.
    size: Tuple defining the size of the city.
    houseHeightInt: Tuple determining the minimum and the maximum height for the houses in the city.
    houseWidthInt: Tuple determining the minimum and the maximum width for the houses in the city.
    windows: A boolean variable which specifies if the houses should have windows.
    booleans: A boolean variable which determines whether the windows should be 
              combined with the houses using boolean difference or not. 
    deformers: A boolean variable which determines whether deformers will be 
               added to the houses or not.
    daytime: Boolean variable which is true if it is day and false if it is night.
    glow: Boolean variable which specifies if all windows will glow if daytime is false, 
          or if some windows will be dark.
    environment: Triple specifying the colour value the environment will have.
    colourRange: A tuple containing two triples with hsv colour values. These 
                 colour values gives the range for the hue, saturation and value 
                 the house shaders will have.
    On exit: A city with houses, trees, parks, traffic lights and street lights has been 
             generated. The height of the houses decrease the further away from the city center
             they are. 
    '''
    cmds.flushUndo()
    houseShaders = makeHouseShaders(40,colourRange)
    makeNecessaryShaders(daytime)
    treeShaders = park.makeTreeShaders(10)   
    windowShaders = makeWindowShaders(daytime, glow, environment)
    makeCamera(name_+ "RenderCam", environment)
    makeLights(daytime, name_)
    ground = cmds.polyPlane(n = "Ground", w = size[0], h = size[1])
    cmds.sets(ground[0], edit=True, forceElement="streetMaterialGroup")
    streetLightGeom = trafficLight.makeStreetLight()
    dir = random.choice(["horisontal","vertical"])
    # Make the binary tree forming the street structure for the city
    if (dir == "horisontal"):
        firstSplit = random.uniform(-size[1] / 2.0 + houseWidthInt[0] + 8 ,size[1] / 2.0  -houseWidthInt[0] - 8)
    else:
        firstSplit = random.uniform(-size[0] / 2.0 + houseWidthInt[0] + 8 ,size[0] / 2.0  -houseWidthInt[0] - 8)
    cityStreets = streets.Street((dir,firstSplit), (-size[0] / 2.0,-size[1] / 2.0), (size[0] / 2.0, size[1] / 2.0))
    cityStreets.split_((-size[0] / 2.0,-size[1] / 2.0), (size[0] / 2.0, size[1] / 2.0), houseWidthInt[1] + 8, houseWidthInt[0] + 8)
    list = []
    areas = cityStreets.listAreas((-size[0] / 2.0,-size[1] / 2.0), (size[0] / 2.0, size[1] / 2.0),list)
    heightIntList = makeZoneHeights(size, houseHeightInt) # Make a list with 6 different height ranges for the houses.
    maxCenterDistance = math.sqrt(math.pow((size[0] / 2.0), 2) + math.pow((size[1] / 2.0), 2))
    zoneWidth = maxCenterDistance/6 # The thickness of each circular zone.
    blockList = []
    cmds.group(n = "houses", empty = True)
    cmds.group(n = "parks", empty = True)
    for i in areas:
        centerx = (i[0][0] + i[1][0]) / 2.0
        centerz = (i[0][1] + i[1][1]) / 2.0
        width = (i[1][0] - i[0][0]) - 4
        depth = (i[1][1] - i[0][1]) - 4
        blockList.append(Block(width, depth, (centerx, centerz))) # Create Block object. 
        centerDistance = math.sqrt(math.pow(centerx, 2) + math.pow(centerz, 2))
        blockType = random.random() # Determine if house or park should be created.
        if blockType < 0.8:
            zone = int(math.floor(centerDistance / zoneWidth)) # Check which zone the house is in.
            house = makeHouse(name_ + "House", heightIntList[zone], (width - 4,depth - 4), houseShaders, treeShaders, windowShaders, windows, booleans, deformers)
            house.moveHouse((centerx,centerz))
            cmds.delete(house.name, ch = True)
            cmds.parent(house.name, "houses")
        elif blockType < 0.9:
            park_ = park.makeFountainPark((width - 3,depth - 3), treeShaders, daytime, streetLightGeom)
            cmds.xform(park_[0], translation = (centerx,0,centerz), r = True)
            cmds.parent(park_[0], "parks")
        else:
            park_ = park.makePark((width - 3,depth - 3), treeShaders, daytime, streetLightGeom)
            cmds.xform(park_[0], translation = (centerx,0,centerz), r = True)
            cmds.parent(park_[0], "parks")
    trafficLight.placeStreetLight(blockList,daytime,streetLightGeom)
    trafficLight.trafficLights(cityStreets,size,daytime)
    cmds.hide(streetLightGeom[0])
    # Group all blocks together.
    cmds.group(n = "blocks", empty = True)
    for i in blockList:
        cmds.parent(i.obj[0], "blocks")
        
Example #15
0
import maya.cmds as cmds

cmds.flushUndo()

cmds.unloadPlugin('unfolder.py')
cmds.loadPlugin('unfolder.py')


cmds.dagInfoCmd()

# print cmds.pluginInfo('eyeball.py', query=True, loaded=True)
# 
# if cmds.pluginInfo('eyeball.py', query=True, loaded=True):
#     cmds.select(all=True)
#     cmds.delete()
#     cmds.unloadPlugin('eyeball.py')
#     
# cmds.loadPlugin('eyeball.py')
#      
# cmds.eyeball( pupil=1 )


import eyeball
 
reload(eyeball)
eyeball.run()
Example #16
0
def pinocchioWeightsImport(mesh, skin, skelList, weightFile=None,
                           undoable=False):
    #Ensure that all influences in the skelList are influences for the skin
    allInfluences = influenceObjects(skin)
    pinocInfluences = [joint for joint, parent in skelList]
    for joint in pinocInfluences:
        if not nodeIn(joint, allInfluences):
            cmds.skinCluster(skin, edit=1, addInfluence=joint)

    if weightFile is None:
        weightFile = browseForFile(m=0, actionName='Import')
    vertBoneWeights = readPinocchioWeights(weightFile)
    numVertices = len(vertBoneWeights)
    numBones = len(vertBoneWeights[0])
    numJoints = len(skelList)
    numWeights = numVertices * numJoints
    if DEBUG:
        print "numVertices:", numVertices
        print "numBones:", numBones
    assert numBones == numJoints - 1, \
           "numBones (%d) != numJoints (%d) - 1" % (numBones, numJoints)

    # Pinocchio sets weights per-bone... maya weights per joint.
    # Need to decide whether to assign the bone weight to the 'start' joint
    #   of the bone, or the 'end' joint
    boneIndexToJointIndex = [0] * numBones
    vertJointWeights = [[0] * numJoints for i in xrange(numVertices)]

    assignBoneToEndJoint = False
    if assignBoneToEndJoint:
        for jointIndex in xrange(1, numJoints):
            boneIndexToJointIndex[jointIndex - 1] = jointIndex
    else:
        for jointIndex in xrange(1, numJoints):
            parentIndex = skelList[jointIndex][1]
            boneIndexToJointIndex[jointIndex - 1] = parentIndex
    
    for vertIndex, boneWeights in enumerate(vertBoneWeights):
        assert abs(sum(boneWeights) - 1) < 0.1, \
               "Output for vert %d not normalized - total was: %.03f" % \
               (vertIndex, sum(boneWeights))
        for boneIndex, boneValue in enumerate(boneWeights):
            # multiple bones can correspond to a single joint -
            # make sure to add the various bones values together!
            jointIndex = boneIndexToJointIndex[boneIndex] 
            vertJointWeights[vertIndex][jointIndex] += boneValue

    if DEBUG:
        print "vertJointWeights:"
        for i, jointWeights in enumerate(vertJointWeights):
            if i < 20:
                print jointWeights
            else:
                print "..."
                break
    
    if not undoable:
        # If we're using the non-undoable api method, there's a lot of setup
        # we have to do first; want to do this before zeroing weights,
        # in case there's an error 
        apiWeights = api.MDoubleArray(numWeights, 0)
        for vertIndex, jointWeights in enumerate(vertJointWeights):
            for jointIndex, jointValue in enumerate(jointWeights):
                apiWeights.set(jointValue, vertIndex * numJoints + jointIndex)
        apiJointIndices = api.MIntArray(numJoints, 0)
        if DEBUG:
            for jointIndex, (joint, parentIndex) in enumerate(skelList):
                print jointIndex, (joint, parentIndex)
        influences = influenceObjects(skin)
        for apiIndex, joint in enumerate(influences):
            influenceIndex = getNodeIndex(joint, pinocInfluences)
            if influenceIndex is None:
                raise InfluenceNotFoundError("%r not found in influences for skin %r: %r" %
                                             (joint, skin, pinocInfluences))
            apiJointIndices.set(apiIndex, influenceIndex)
        if DEBUG:
            print "apiJointIndices:",
            pyJointIndices = []
            for i in xrange(apiJointIndices.length()):
                pyJointIndices.append(apiJointIndices[i])
            print pyJointIndices
        apiComponents = api.MFnSingleIndexedComponent().create(api.MFn.kMeshVertComponent)
        apiVertices = api.MIntArray(numVertices, 0)
        for i in xrange(numVertices):
            apiVertices.set(i, i)
        api.MFnSingleIndexedComponent(apiComponents).addElements(apiVertices) 
        mfnSkin = apiAnim.MFnSkinCluster(toMObject(skin))
        meshDag = toMDagPath(mesh)
        # Save the weights, so that if there's an error later, we
        # can still restore the weights
        savedWeights = api.MDoubleArray(numWeights, 0)
        numInfluencesPtr = api.MScriptUtil()
        numInfluencesPtr.createFromInt(0) 
        mfnSkin.getWeights(meshDag, apiComponents, savedWeights,
                           numInfluencesPtr.asUintPtr())
        
    # Zero all weights (so if there's influences not among those we're
    # importing, they will have zero influence)
    cmds.skinPercent(skin, mesh, pruneWeights=100, normalize=False)

    if not undoable:
        # Use the api methods to set skin weights - MUCH faster than using
        # mel skinPercent, but api doesn't have built-in undo support, so
        # flush the undo queue
        zeroedWeights = api.MDoubleArray()
        undoState = cmds.undoInfo(q=1, state=1)
        cmds.undoInfo(state=False)
        try:
            try:
                mfnSkin.setWeights(meshDag,
                                   apiComponents,
                                   apiJointIndices,
                                   apiWeights,
                                   False,
                                   zeroedWeights)
                print "successfully set weights!"
            except Exception:
                # There was a problem, restore the saved weights!
                influenceIndices = api.MIntArray(len(influences), 0)
                for i in xrange(len(influences)):
                    influenceIndices.set(i,i)
                mfnSkin.setWeights(meshDag,
                                   apiComponents,
                                   influenceIndices,
                                   savedWeights,
                                   False,
                                   zeroedWeights)
                api.MGlobal.displayError("Encountered error setting new weights - original weights restored")
                raise
        finally:
            cmds.flushUndo()
            cmds.undoInfo(state=undoState)
    else:
        # Use mel skinPercent - much slower, but undoable
        cmds.progressWindow(title="Setting new weights...", isInterruptable=True,
                            max=numVertices)
        try:
            lastUpdateTime = cmds.timerX()
            updateInterval = .5
            for vertIndex, vertJoints in enumerate(vertJointWeights):
                jointValues = {}
                if cmds.progressWindow( query=True, isCancelled=True ) :
                    break
                #print "weighting vert:", vertIndex
                for jointIndex, jointValue in enumerate(vertJoints):
                    if jointValue > 0:
                        jointValues[pinocInfluences[jointIndex]] = jointValue
        
                if cmds.timerX(startTime=lastUpdateTime) > updateInterval:
                    cmds.progressWindow(edit=True,
                                        progress=vertIndex,
                                        status="Setting Vert: (%i of %i)" % (vertIndex, numVertices))
                    lastUpdateTime = cmds.timerX()
    
                cmds.skinPercent(skin, mesh + ".vtx[%d]" % vertIndex, normalize=False,
                                 transformValue=jointValues.items())
        finally:
            cmds.progressWindow(endProgress=True)    
Example #17
0
 def test_plugin_handling(self):
     mrp = "Mayatomr"
     pp = 'persistence'
     assert not cmds.pluginInfo(mrp, q=1, loaded=1)
     
     assert not hasattr(nt, 'Transmat')
     cmds.loadPlugin(mrp)
     
     # loading a plugin will add the node types
     assert hasattr(nt, 'Transmat')
     assert nt.typ.nodeTypeTree.has_node('transmat')
     tmat = nt.Transmat()    # mr dep node
     tmat.delete()
     
     dll = nt.MapVizShape()  # mr dag node
     assert isinstance(dll, nt.DagNode)
     dll.delete()
     cmds.flushUndo()    # make sure we get rid of the custom data
     
     
     # custom node types are favored and not overwritten by dummies when 
     # loading
     assert nt.StorageNode is mstorage.StorageNode
     
     # custom node types will remain when unloaded
     cmds.unloadPlugin(pp)
     assert not cmds.pluginInfo(pp, q=1, loaded=1) 
     assert hasattr(nt, 'StorageNode')
     
     # unloading a plugin will remove the nodetypes as well as the hierarchy 
     # entries
     # NOTE: on OSX unloading the plugin beautifully crashes maya, probably
     # a memory exception as MR claims to have had a peak memory of 136 GB
     # As a final goal, this test should be fixed to run here, there 
     # probably is some kind of workaround.
     # http://tracking.byronimo.de/view.php?id=144
     mr_testobj = "contour_composite1"
     if sys.platform != 'darwin':
         cmds.unloadPlugin(mrp, force=1)
         
         assert not hasattr(nt, 'Transmat')
         assert not hasattr(nt, 'MapVizShape')
         assert not nt.typ.nodeTypeTree.has_node('transmat')
         assert not nt.typ.nodeTypeTree.has_node('mapVizShape')
     
 
         # plugins required by a scene trigger the database to update as well
         assert not cmds.pluginInfo(mrp, q=1, loaded=1)
         assert not nt.objExists('transmat1')
         needs_mr_scene = get_maya_file('needsMayatomr.ma')
         mrvmaya.Scene.open(needs_mr_scene, force=True)
         assert hasattr(nt, 'Transmat')
         assert not nt.objExists(mr_testobj), "object shouldn't exist if it works"
         
         # try it during reference and import scenarios
         mrvmaya.Scene.new(force=True)
         cmds.unloadPlugin(mrp, force=0)
         assert not hasattr(nt, 'Transmat')
         
         FileReference.create(needs_mr_scene)
         assert hasattr(nt, 'Transmat'), "Should have triggered the callback"
         assert not nt.objExists(mr_testobj), "object shouldn't exist if it works"
         
         # try import
         mrvmaya.Scene.new(force=True)
         cmds.unloadPlugin(mrp, force=0)
         assert not hasattr(nt, 'Transmat')
         
         
         cmds.file(needs_mr_scene, i=True)
         assert hasattr(nt, 'Transmat'), "Should have triggered callback by import"
         assert not nt.objExists(mr_testobj), "object shouldn't exist if it works"
     # END skip this on osx
     
     assert not nt.objExists(mr_testobj)
     cmds.undoInfo(st=0)
     mod = api.MDGModifier()
     mod.createNode('transmat')
     assert not nt.objExists(mr_testobj), "Shouldn't actually create the object even if undo is off"
     cmds.undoInfo(st=1)
     
     # dynamically added types (which will not trigger a plugin changed event)
     # can be wrapped as well
     customMI = get_maya_file('customshader.mi')
     csn = "testCustomShader"
     csnc = "TestCustomShader"
     mrvmaya.Mel.mrFactory('-load',customMI)
     
     # it doesnt exist, but can be wrapped nontheless, then it exists
     assert not hasattr(nt, csnc)
     cs = nt.Node(cmds.createNode(csn))
     assert hasattr(nt, csnc)