Skip to content

Instantly share code, notes, and snippets.

@aobond2
Last active November 8, 2023 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aobond2/2c3b528ccae83e2c31f9e193f189e842 to your computer and use it in GitHub Desktop.
Save aobond2/2c3b528ccae83e2c31f9e193f189e842 to your computer and use it in GitHub Desktop.
Auto create blendshape from separate maya file
import os
import maya.cmds as cmds
import pymel.core as pm
currentFilePath = cmds.file(query=True, location=True)
subFolderName = "Blendshapes"
subFolderPath = os.path.join(os.path.dirname(currentFilePath), subFolderName)
blendshapeNamespace = 'Blendshape'
mainHead = None
targetShapes = []
def referenceMayaFilesFromFolder():
try:
# Get all maya files in subfolder and reference them
fileList = os.listdir(subFolderPath)
for fileName in fileList:
if fileName.endswith('.ma') or fileName.endswith('.mb'):
filePath = os.path.join(subFolderPath, fileName)
cmds.file(filePath, reference=True, namespace=blendshapeNamespace)
except:
print ("No blendshape folder")
def listBlendshapes():
for node in pm.ls(sl=True):
print(node.listHistory(pruneDagObjects=True, type='blendShape'))
def removeBlendShapes():
global mainHead
# TODO: Change this later, currently done on objects in selection
selectedObjects = cmds.ls(selection=True)
# List all deformers applied to the selected object
for selectedObject in selectedObjects:
# TODO: Add better check on this. Set selected object as baseMesh
mainHead = selectedObject
deformers = cmds.listHistory(selectedObject)
for deformer in deformers:
if cmds.nodeType(deformer) == "blendShape":
cmds.delete(deformer)
cmds.select(clear=True)
def assignBlendshapes():
print ("Blendshape assign")
cmds.select(mainHead)
blendshapeNode = cmds.blendShape(targetShapes, mainHead)[0]
cmds.rename(blendshapeNode, "Blendshapes")
def getReferencedBlendshapes():
global targetShapes
# Get all referenced nodes in the scene
references = pm.listReferences()
refInNamespace = [ref for ref in references if ref.namespace == blendshapeNamespace]
for ref_node in refInNamespace:
print (ref_node)
for c in ref_node.nodes():
# TODO: there's got to be better way than casting this to string
if ("BS_" in str(c)) and ("Shape" not in str(c)):
cmds.select(str(c), add=True)
targetShapes.append(c)
def removeAllReferences():
# List all referenced files in the scene
referencedFiles = cmds.file(q=True, r=True)
# Unload and remove each referenced file
for referencedFile in referencedFiles:
cmds.file(referencedFile, unloadReference=True)
cmds.file(referencedFile, removeReference=True)
def runThis():
removeBlendShapes()
removeAllReferences()
referenceMayaFilesFromFolder()
getReferencedBlendshapes()
assignBlendshapes()
# Once all done remove all references again
removeAllReferences()
runThis()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment