import maya
try:
maya.OpenMayaUI.MExternalDropCallback.removeCallback(callback)
except:
pass
kMayaDefault = maya.OpenMayaUI.MExternalDropCallback.kMayaDefault
kNoMayaDefaultAndAccept = maya.OpenMayaUI.MExternalDropCallback.kNoMayaDefaultAndAccept
kNoMayaDefaultAndNoAccept = maya.OpenMayaUI.MExternalDropCallback.kNoMayaDefaultAndNoAccept
class CustomCallback(maya.OpenMayaUI.MExternalDropCallback):
def __init__(self):
maya.OpenMayaUI.MExternalDropCallback.__init__(self)
def externalDropCallback(self, doDrop, controlName, data):
"""
For some reason this callback loops back on itself to recheck the data
Return true if a valid drop then do the drop
:param doDrop:
:param controlName: MString
:param data: MExternalDropData
:return:
"""
print data.formats()
if data.hasText():
print "text"
print data.text()
if not doDrop:
return kNoMayaDefaultAndAccept
if data. hasUrls():
paths = data.urls()
print "paths"
print type(paths)
print paths
if not doDrop:
return kNoMayaDefaultAndAccept
if doDrop:
# Do the stuff
pass
return kMayaDefault
callback = CustomCallback()
maya.OpenMayaUI.MExternalDropCallback.addCallback(callback)
combine 2 or more nurbs curves to act as one
# the last item in the selection will be the main parent
selection = pm.ls(sl=True)
parentItem = selection[-1]
parentTransforms = pm.xform(parentItem,q=True, t=True, ws=True)
for item in selection[:-1]:
shape = item.getShape()
if shape:
if shape.type() == "nurbsCurve":
# set the parent to the world to make keep current transforms
pm.parent(item, world=True)
#move the pivot to the parents location
item.setRotatePivot(parentTransforms, ws=True)
item.setScalePivot(parentTransforms, ws=True)
# move the secondary curve back to the origin so we can set the transforms back onto it
pm.move(item,[0,0,0],rpr=True)
pm.makeIdentity(item, apply=True, t=True, r=True, s=True, n=False, pn=True)
# delete any history for cleanup
pm.delete(item, ch=True)
# set the transforms back onto the secondary curve
pm.xform(item, t=parentTransforms, ws=True)
# finally run the command to parent secondary curve
pm.parent(shape, parentItem, r=True, s=True)
# delete the remaining transform
pm.delete(item)
# select the parent item for user interaction
pm.select(parentItem)
coming soon
from PySide2 import QtCore , QtGui
import os
it = QtCore.QDirIterator(":")
while it.hasNext():
f = it.next()
pmap = QtGui.QPixmap(f)
if pmap.isNull():
continue
pmap.save(os.path.join("some/path", os.path.basename(f)))
for when windows are off screen
import pymel.core as pm
for window in pm.lsUI(wnd=True):
try:
window.setTopEdge(0)
window.setLeftEdge(0)
except:
# just in case for whatever reason it fails on the given window
pass
query mayas runtime command to get the script
import pymel.core as pm
pm.runTimeCommand("SelectAllLights", q=True, c=True)
__ICON_CACHE = {}
# See Feature Request MAYA-13005 for incorporating this utility into MQtUtil
def get_icon_path(file_name):
"""Search for an icon along XBMLANGPATH
For redundant file calls the query is cached do that subsequent calls
do not need to traverse directories
Args:
file_name (str): file name to look for (ext can be included)
Returns:
str | None: full path to the file if found
"""
# First see if we've already found this
if file_name in __ICON_CACHE:
resource_path = __ICON_CACHE[file_name]
if os.path.isfile(resource_path):
return resource_path
search_name = file_name
if search_name.startswith(":"):
search_name = ":" + search_name
# Assume using maya internal icon
__ICON_CACHE[file_name] = search_name
return search_name
# Search all paths until a candidtae is found
search_paths = os.environ.get('XBMLANGPATH', "").split(os.pathsep)
for search_path in search_paths:
search_path = search_path.replace('%B', '')
full_path = "/".join([search_path, file_name])
results = glob.glob(full_path + ".*")
for item in results:
item = item.replace("\\", "/")
if os.path.isfile(item):
__ICON_CACHE[file_name] = item
return item
pm.ls(type=pm.listNodeTypes("light"))
import pymel.core as pm
pm.dgmodified()
had an issue where the startup camera couldnt be found which would result in front1 and this camera would then be locked out for you to be able to delete or rename
import pymel.core as pm
# select the unwanted camera and run this
for cam in pm.ls(sl=True, typ="camera", dag=True):
cam.setStartupCamera(False)
# uncomment the line below to delete the selected camera as well
# pm.delete(cam)
# to set the startup camera back to the one in the scene
for cam in pm.ls(sl=True, typ="camera", dag=True):
cam.setStartupCamera(True)
to attach a pyside window to mayas main window
from PySide.QtGui import QMainWindow # maya < 2016
from PySide2.QtWidgets import QMainWindow # maya > 2017
import maya.OpenMayaUI as omui
def getMayaWin():
return wrapInstance(long(omui.MQtUtil.mainWindow()),QMainWindow)
cast mayas UI element from the string ui name to the given widget class
import maya.OpenMayaUI as omui
widget_class = QtGui.QWidget
qtObj = wrapInstance(long(omui.MQtUtil.findControl(uiName)), widget_class)
cleanup all namespaces sometimes left behind from importing and referencing
import pymel.core as pm
allNamespaces = pm.namespaceInfo(":", r=True, listOnlyNamespaces=True, absoluteName=True)
allNamespaces.remove(":shared") # default namespace shouldnt be removed
allNamespaces.remove(":UI") # default namespace shouldnt be removed
# in order to remove the namespace we need to remove the children first
# so the removal is in reverse order of the query
for namespace in reversed(allNamespaces):
try:
pm.namespace(mv=[namespace, ":"], f=True)
pm.namespace(rm=namespace)
except Exception, e:
# erros will get thrown if the namespace is referenced.
# instead of checking ill just skip over them
if "referenced" not in e.message:
raise e
remove all references from a scene
useful when testing different references
import pymel.core as pm
for ref in pm.listReferences(recursive=True):
ref.remove()
remove pasted string from pasted nodes
for item in pm.ls("pasted__*"): item.rename(item.replace("pasted__", ""))
select shaders from the selected objects
import pymel.core as pm
materialsToProcess = []
for i in pm.ls(sl=True):
if hasattr(i, "getShape"):
shape = i.getShape()
if shape is not None:
shadingEngines = shape.listConnections(t="shadingEngine")
for shadingEngine in shadingEngines:
materials = pm.ls(shadingEngine.listConnections(), mat=True)
for material in materials:
if material not in materialsToProcess:
materialsToProcess.append(material)
pm.select(materialsToProcess)
send mel commands to maya using maya's default port.
to send python or use your own port see commandPort in maya's help docs
import socket
maya = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
maya.connect(('localhost', 50007))
maya.send("melScript")
maya.close()
set attributes across multiple objects
attr = "<attr>"
value = "<value>"
for item in pm.ls(sl=True):
# only set the value on items that have
# the attribute so an error isnt thrown
if item.hasAttr(attr):
item.attr(attr).set(value)
sometimes the shape node seems to just break. By selecting the geo and another mesh. the vertices will be transferred to the selected mesh
import pymel.core as pm
old, new = pm.ls(sl=True)
old.getShape().outMesh >> new.getShape().inMesh # connect
pm.refresh(cv=True) # needed to break up the connect and disconnect or else it doesnt take effect
old.getShape().outMesh // new.getShape().inMesh # disconnect
nodes = cmds.ls(type="unknown")
if nodes:
cmds.delete(nodes)
for plugin in cmds.unknownPlugin(q=True, l=True) or []:
cmds.unknownPlugin(plugin,remove=True)
removes all uvmaps except map1 assuming there is a map1 change the name to whatever you'd like
for i in pm.ls(typ='mesh'):
try:
pm.polyCopyUV(i, uvSetNameInput= "" ,uvSetName ="map1" ,ch =True)
uvSets = pm.polyUVSet(i,q=True, auv=True )
for x in uvSets:
if x != "map1":
pm.polyUVSet(i,d=True,uvSet=x )
except Exception, e:
print e
grab an as is snapshot of the viewport
kinda doesn't matter now since you can use vp2 but still handy for a pipeline script
import maya.OpenMaya as om
image = om.MImage()
view = omui.M3dView.active3dView()
view.readColorBuffer(image, True)
image.writeToFile(r"C:\snapshot.jpg", "jpg")
add or remove VRay attributes
# vray_subdivision
# vray_subquality
# vray_displacement
# vray_opensubdiv
# vray_roundedges
# vray_user_attributes
# vray_objectID
# vray_fogFadeOut
# vray_localrayserver
attr = "<pick one from above>"
add = True # set to False to remove
import pymel.core as pm
for item in pm.ls(sl=True):
pm.vray("addAttributesFromGroup", item, attr, add)