Python Forum
Python in MAYA - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python in MAYA (/thread-3021.html)



Python in MAYA - I_suck_at_python - Apr-24-2017

Right basically I've got to submit this tomorrow and I'm new to Python and have no idea what  any of it means. I've been provided with a MAYA file and this script that is used within it. I know the code is not yet complete, but could anyone possibly add comments to all of the necessary lines of code explaining what they do within MAYA? would be a great help thanks (Also sorry about the format of the script not being correct and not showing indents and such correctly, I can't add the text with it keeping its original layout)

import maya.cmds as mc #imports MEL commands as Python wrapper
import os #importing operate system preferences
import copy
dirPath = ""#declares variable as string 

def importFBX(_filepath): #defines importFBX as a file directory 
global dirPath
#http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/CommandsPython/file.html
try:
cmds.file(_filepath, i = True, type = "FBX")
path, filename = os.path.split(_filepath) #runs file
return True

except RuntimeError:
pass 

try:
_filepath = dirPath + "\\" +_filepath
cmds.file(_filepath, i = True, type = "FBX")
path, filename = os.path.split(_filepath)
return True

except RuntimeError as er:
print "unable to import FBX file: %s . File may be missing or corrupted" % _filepath
print er
return False

def cd(_newPath):
global dirPath 
dirPath = str(_newPath)

def loadExpressions(_path = ""):
global dirPath
expressions = {}  # dictionary of dictionaries
f = open(_path + '\\expressions.txt', 'r')  

currentExpressionId = ''
currentTarget = ''
currentExpression = {}

for line in f:
line = line[:-1]
print "line:" + line
print "exId:" + currentExpressionId
print "skId:" + currentTarget

if line == "EXID":        
currentExpressionId = ''

elif currentExpressionId == '':        
currentExpressionId = str(line)

elif currentTarget == '':   
strs = str(line).split(':')
num = len(strs)
currentTarget = strs[num-1]

else:
currentExpression[currentTarget] = float(line)
expressions[currentExpressionId] = {}
expressions[currentExpressionId] = copy.deepcopy(currentExpression)
currentTarget = ''
print("ShapeKey added")
  
f.close() 
print ("expression dict")
print (expressions)
print ("------")
return expressions

def writeExpression(name, _path = ""):
global dirPath
if _path == "":
_path = dirPath + '\expressions.txt'

f = open(_path, 'a')  
f.write("EXID\n" + str(name) + "\n")

blendShapes = mc.ls(type = 'blendShape', an=True)
print (blendShapes)

for blend in blendShapes:
f.write(generateExpressionString(blend))
f.close()

def generateExpressionString(_blend):
global dirPath
expressionString = ""
expressions = mc.listAttr(_blend + '.w', m = True)
#print (expressions)

for i in expressions:
weight = mc.getAttr(_blend + '.' + i)
expressionString += _blend.lstrip(":") + ".%s\n" % i 
expressionString += "%s\n" % weight

return expressionString

def generateBlendShapeTarget(_expressionID, _expression, _basemodel):
global dirPath
print('Building %s expression' %_expressionID)

for AU in _expression: # Action Unit
try:
mc.setAttr(AU, _expression[AU])
except RuntimeError as err:
print(err)
# try:
# with parent name appended 
# will need to do a search for it
pass

tempObjs = mc.duplicate( _basemodel , n=_expressionID)  
tempObjId = mc.bakePartialHistory( tempObjs, preCache=True )

for AU in _expression: # Action Unit
try:
mc.setAttr(AU, 0.0)
except RuntimeError as err:
print(err)
pass

print('successfully built %s expression' %_expressionID)
return tempObjs

def buildShapeKeyExpressions():
global dirPath   #defines "buildshapekeyExpressions as a global variable so it can be called upon in the entire script
objs = mc.ls( selection=True, sn=True)

if len(objs) == 0:
mc.select( clear=True )
geometry = mc.ls(geometry=True)
transforms = mc.listRelatives(geometry, p=True, path=True)
mc.select(geometry, r=True)

objs = mc.ls( selection=True, sn=True)

if len(objs) == 0:
mc.error("no poly objects detected") 

expressions = loadExpressions(dirPath)
oldexpressions = blendShapes = mc.ls(type = 'blendShape', an=True)

try:
finalObj = mc.polyUnite( *objs, o=True, ch=True, n='character' );
except RuntimeError:
print("Error: unable to Unite objects, are non-poly obects selected?")# print error message 

mc.select( clear=True )

print("creating BlendShape targets")
#print(expressions)

newObjs = [];
for exID in expressions:
#print(exID)
#print(expressions[exID])

newObjs = generateBlendShapeTarget(exID, expressions[exID], finalObj[0])
mc.select( newObjs[0], add=True ) #create a new blend shape and selects it


mc.select( finalObj[0], add=True ) #
mc.blendShape(n='Expressions') # build shape keys, last selected object is base
mc.select( finalObj[0], d=True ) # deselect the final obj

for old in oldexpressions:
mc.select(old, add=True)#loop that selects old and adds a true value

mc.delete(mc.ls( selection=True, sn=True)) # delete all inbetween objects

mc.select( clear=True )
print("Done :)")#displays "Done :)"



cmds.showWindow()#shows window 
    

CreateWindow()#creates window