def getStereoRigShapeNode(self, name):
sh = cmds.listRelatives(name, s=1)
for s in sh:
if cmds.nodeType(s) == 'stereoRigCamera':
return s
else:
return name
python类nodeType()的实例源码
def getNodeType(self, iter):
obj = om.MObject()
iter.getDependNode(obj)
dep = om.MFnDependencyNode(obj)
return cmds.nodeType(dep.name())
def readCustomAttrib(self, iter):
# attribs = self.tokenPrefix(self.op['exppivattrib'][1])
# attribs = self.tokenAttributes(attribs)
attribs = self.reorderAttrs(self.op['exppivattrib'][1])
dagPath = om.MDagPath()
nodes = []
while not iter.isDone():
iter.getDagPath( dagPath )
nd = cmds.nodeType(dagPath.fullPathName())
if nd in self.spetialObjectsList:
proc = self.spetialObjectsList[nd]
objName = proc(dagPath.fullPathName())
else:
try:
dagPath.extendToShape()
except:
pass
print 'No shape for', dagPath.fullPathName()
objName = dagPath.fullPathName()
nodes.append(objName)
iter.next()
iter.reset()
checked, pp = self.checkAttribtypes(nodes, attribs)
for i, node in enumerate(nodes):
for attr in checked:
renamed = self.checkLegalChar(checked[attr][2]) or self.checkLegalChar(attr)
if not renamed in self.pointAttribArray:
self.pointAttribArray[renamed] = []
default = checked[attr][0]
value = self.getAttribFromNode(node, attr, checked[attr][1], default)
if value is None:
value = default
self.defaultValues[renamed] = default
self.pointAttribArray[renamed] += ([value])
###################################
def getChannelFromAnimCurve(curve, plugs=True):
'''
Finding the channel associated with a curve has gotten really complicated since animation layers.
This is a recursive function which walks connections from a curve until an animated channel is found.
'''
#we need to save the attribute for later.
attr = ''
if '.' in curve:
curve, attr = curve.split('.')
nodeType = mc.nodeType(curve)
if nodeType.startswith('animCurveT') or nodeType.startswith('animBlendNode'):
source = mc.listConnections(curve+'.output', source=False, plugs=plugs)
if not source and nodeType=='animBlendNodeAdditiveRotation':
#if we haven't found a connection from .output, then it may be a node that uses outputX, outputY, etc.
#get the proper attribute by using the last letter of the input attribute, which should be X, Y, etc.
#if we're not returning plugs, then we wont have an attr suffix to use, so just use X.
attrSuffix = 'X'
if plugs:
attrSuffix = attr[-1]
source = mc.listConnections(curve+'.output'+attrSuffix, source=False, plugs=plugs)
if source:
nodeType = mc.nodeType(source[0])
if nodeType.startswith('animCurveT') or nodeType.startswith('animBlendNode'):
return getChannelFromAnimCurve(source[0], plugs=plugs)
return source[0]
def getCurrentCamera():
'''
Returns the camera that you're currently looking through.
If the current highlighted panel isn't a modelPanel,
'''
panel = mc.getPanel(withFocus=True)
if mc.getPanel(typeOf=panel) != 'modelPanel':
#just get the first visible model panel we find, hopefully the correct one.
for p in mc.getPanel(visiblePanels=True):
if mc.getPanel(typeOf=p) == 'modelPanel':
panel = p
mc.setFocus(panel)
break
if mc.getPanel(typeOf=panel) != 'modelPanel':
OpenMaya.MGlobal.displayWarning('Please highlight a camera viewport.')
return False
camShape = mc.modelEditor(panel, query=True, camera=True)
if not camShape:
return False
camNodeType = mc.nodeType(camShape)
if mc.nodeType(camShape) == 'transform':
return camShape
elif mc.nodeType(camShape) in ['camera','stereoRigCamera']:
return mc.listRelatives(camShape, parent=True, path=True)[0]
def clone(shape, worldspace=False):
"""Clone `shape`
Arguments:
shape (str): Absolute path to shape
worldspace (bool, optional): Whether or not to consider worldspace
Returns:
node (str): Newly created clone
"""
type = cmds.nodeType(shape)
assert type in ("mesh", "nurbsSurface", "nurbsCurve"), (
"clone() works on polygonal and nurbs surfaces")
src, dst = {
"mesh": (".outMesh", ".inMesh"),
"nurbsSurface": (".local", ".create"),
"nurbsCurve": (".local", ".create"),
}[type]
nodetype = cmds.nodeType(shape)
name = lib.unique(name=shape.rsplit("|")[-1])
clone = cmds.createNode(nodetype, name=name)
cmds.connectAttr(shape + src, clone + dst, force=True)
if worldspace:
transform = cmds.createNode("transformGeometry",
name=name + "_transformGeometry")
cmds.connectAttr(shape + src,
transform + ".inputGeometry", force=True)
cmds.connectAttr(shape + ".worldMatrix[0]",
transform + ".transform", force=True)
cmds.connectAttr(transform + ".outputGeometry",
clone + dst, force=True)
# Assign default shader
cmds.sets(clone, addElement="initialShadingGroup")
return clone
def follicle(*args):
supported = ["mesh", "nurbsSurface"]
selection = cmds.ls(sl=1)
new_follicles = []
for sel in selection:
uv = lib.uv_from_element(sel)
geometry_shape = lib.shape_from_element(sel)
geometry_transform = cmds.listRelatives(geometry_shape, parent=True)[0]
# Figure out output connection
inputs = [".inputMesh", ".inputSurface"]
outputs = [".outMesh", ".local"]
failed = False
type = cmds.nodeType(geometry_shape)
if type not in supported:
failed = True
shapes = cmds.listRelatives(geometry_shape, shapes=True)
if shapes:
geometry_shape = shapes[0]
type = cmds.nodeType(geometry_shape)
if type in supported:
failed = False
if failed:
cmds.error("Skipping '%s': Type not accepted" % type)
return
input = inputs[supported.index(type)]
output = outputs[supported.index(type)]
# Make follicle
follicle = cmds.createNode("follicle",
name=geometry_transform + "_follicleShape1")
follicle_transform = cmds.listRelatives(follicle, parent=True)[0]
follicle_transform = cmds.rename(follicle_transform,
geometry_transform + "_follicle1")
# Set U and V value
cmds.setAttr(follicle + ".parameterU", uv[0])
cmds.setAttr(follicle + ".parameterV", uv[1])
# Make the connections
cmds.connectAttr(follicle + ".outTranslate",
follicle_transform + ".translate")
cmds.connectAttr(follicle + ".outRotate",
follicle_transform + ".rotate")
cmds.connectAttr(geometry_shape + output,
follicle + input)
# Select last
new_follicles.append(follicle_transform)
# Select newly created follicles
if new_follicles:
cmds.select(new_follicles, r=1)
return new_follicles
def get_current_camera():
"""Returns the currently active camera.
Searched in the order of:
1. Active Panel
2. Selected Camera Shape
3. Selected Camera Transform
Returns:
str: name of active camera transform
"""
# Get camera from active modelPanel (if any)
panel = cmds.getPanel(withFocus=True)
if cmds.getPanel(typeOf=panel) == "modelPanel":
cam = cmds.modelEditor(panel, query=True, camera=True)
# In some cases above returns the shape, but most often it returns the
# transform. Still we need to make sure we return the transform.
if cam:
if cmds.nodeType(cam) == "transform":
return cam
# camera shape is a shape type
elif cmds.objectType(cam, isAType="shape"):
parent = cmds.listRelatives(cam, parent=True, fullPath=True)
if parent:
return parent[0]
# Check if a camShape is selected (if so use that)
cam_shapes = cmds.ls(selection=True, type="camera")
if cam_shapes:
return cmds.listRelatives(cam_shapes,
parent=True,
fullPath=True)[0]
# Check if a transform of a camShape is selected
# (return cam transform if any)
transforms = cmds.ls(selection=True, type="transform")
if transforms:
cam_shapes = cmds.listRelatives(transforms, shapes=True, type="camera")
if cam_shapes:
return cmds.listRelatives(cam_shapes,
parent=True,
fullPath=True)[0]
def follicle(surface="none", folName="none", u=0.5, v=0.5, *args):
"""
creates a follicle on a surface based on the uv input.
Args are: surface, folName, u, v
"""
#------------do a bit more checking here to make sure the shapes, numbers etc work out
if surface=="none":
#decide if surface is polymesh or nurbsSurface
surfaceXform = cmds.ls(sl=True, dag=True, type="transform")[0]
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
else:
surfaceXform = surface
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
if folName == "none":
folShapeName = "myFollicleShape"
folXformName = "myFollicle"
else:
folShapeName = "%sShape"%folName
folXformName = folName
#------------test if follicle exists
#create the follicle
folShape = cmds.createNode("follicle", n=folShapeName)
folXform = cmds.listRelatives(folShape, p=True, type="transform")[0]
cmds.rename(folXform, folXformName)
#connect up the follicle!
#connect the matrix of the surface to the matrix of the follicle
cmds.connectAttr("%s.worldMatrix[0]"%surfaceShape, "%s.inputWorldMatrix"%folShape)
#check for surface type, poly or nurbs and connect the matrix into the follicle
if (cmds.nodeType(surfaceShape)=="nurbsSurface"):
cmds.connectAttr("%s.local"%surfaceShape, "%s.inputSurface"%folShape)
elif (cmds.nodeType(surfaceShape)=="mesh"):
cmds.connectAttr("%s.outMesh"%surfaceShape, "%s.inputMesh"%folShape)
else:
cmds.warning("not the right kind of selection. Need a poly or nurbs surface")
#connect the transl, rots from shape to transform of follicle
cmds.connectAttr("%s.outTranslate"%folShape, "%s.translate"%folXform)
cmds.connectAttr("%s.outRotate"%folShape, "%s.rotate"%folXform)
cmds.setAttr("%s.parameterU"%folShape, u)
cmds.setAttr("%s.parameterV"%folShape, v)
cmds.setAttr("%s.translate"%folXform, l=True)
cmds.setAttr("%s.rotate"%folXform, l=True)
return(folXform, folShape)
def zbw_follicle(surface="none", folName="none", u=0.5, v=0.5, *args):
#------------do a bit more checking here to make sure the shapes, numbers etc work out
if surface=="none":
#decide if surface is polymesh or nurbsSurface
surfaceXform = cmds.ls(sl=True, dag=True, type="transform")[0]
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
else:
surfaceXform = surface
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
if folName == "none":
folShapeName = "myFollicleShape"
folXformName = "myFollicle"
else:
folShapeName = "%sShape"%folName
folXformName = folName
#create the follicle
folShape = cmds.createNode("follicle", n=folShapeName)
folXform = cmds.listRelatives(folShape, p=True, type="transform")[0]
cmds.rename(folXform, folXformName)
#connect up the follicle!
#connect the matrix of the surface to the matrix of the follicle
cmds.connectAttr("%s.worldMatrix[0]"%surfaceShape, "%s.inputWorldMatrix"%folShape)
#check for surface type, poly or nurbs and connect the matrix into the follicle
if (cmds.nodeType(surfaceShape)=="nurbsSurface"):
cmds.connectAttr("%s.local"%surfaceShape, "%s.inputSurface"%folShape)
elif (cmds.nodeType(surfaceShape)=="mesh"):
cmds.connectAttr("%s.outMesh"%surfaceShape, "%s.inputMesh"%folShape)
else:
cmds.warning("not the right kind of selection. Need a poly or nurbs surface")
#connect the transl, rots from shape to transform of follicle
cmds.connectAttr("%s.outTranslate"%folShape, "%s.translate"%folXform)
cmds.connectAttr("%s.outRotate"%folShape, "%s.rotate"%folXform)
cmds.setAttr("%s.parameterU"%folShape, u)
cmds.setAttr("%s.parameterV"%folShape, v)
cmds.setAttr("%s.translate"%folXform, l=True)
cmds.setAttr("%s.rotate"%folXform, l=True)
return(folXform, folShape)
def preprocessNode(nodeName):
'''
Preprocessing a node.
This is needed as some nodes (like ramp or bump) can be
replaced by several other nodes for Katana.
We return either one original node or several
nodes if something was replaced during preprocessing
'''
nodeType = cmds.nodeType(nodeName)
if nodeType not in premap:
return None
nodes = {}
attributes = getNodeAttributes(nodeName)
connections = {}
nodeConnections = cmds.listConnections(nodeName, source=True, destination=False, connections=True, plugs=True)
if nodeConnections:
for i in range(len(nodeConnections) / 2):
connTo = nodeConnections[i * 2]
connTo = connTo[connTo.find('.') + 1:]
connFrom = nodeConnections[i * 2 + 1]
connections[connTo] = {
'node': connFrom[:connFrom.find('.')],
'originalPort': connFrom[connFrom.find('.') + 1:]
}
node = {
'name': nodeName,
'type': nodeType,
'attributes': attributes,
'connections': connections,
'renamings': {}
}
premapSettings = premap[nodeType]
for attr in ['type', 'postprocess']:
if premapSettings.get(attr):
node[attr] = premapSettings.get(attr)
if premapSettings.get('preprocess'):
preprocessFunc = premapSettings.get('preprocess')
if preprocessFunc:
preprocessResult = preprocessFunc(node)
if preprocessResult:
nodes.update(preprocessResult)
else:
nodes[node['name']] = node
return nodes
def parentShape(child=None, parent=None, maintainOffset=True):
'''
Parent a child shape node to a parent transform. The child node can be a shape,
or a transform which has any number of shapes.
'''
if not child or not parent:
sel = mc.ls(sl=True)
if sel and len(sel) > 1:
child = sel[:-1]
parent = sel[-1]
else:
OpenMaya.MGlobal.displayWarning('Please make a selection.')
return
parentNodeType = mc.nodeType(parent)
if not parentNodeType in ('transform', 'joint', 'ikHandle'):
OpenMaya.MGlobal.displayWarning('Parent must be a transform node.')
return
if not isinstance(child, (list, tuple)):
child = [child]
newChild = unparentShape(child)
shapes = list()
for each in newChild:
thisChild = mc.parent(each, parent)[0]
mc.makeIdentity(thisChild, apply=True)
for s in mc.listRelatives(thisChild, shapes=True, noIntermediate=True, path=True):
shape = mc.parent(s, parent, shape=True, relative=True)[0]
#move to bottom
mc.reorder(shape, back=True)
#rename
parentName = mc.ls(parent, shortNames=True)[0]
shapes.append(mc.rename(shape, parentName+'Shape#'))
mc.delete(newChild)
for each in child:
if not mc.listRelatives(each):
#if it doesn't have any kids, delete it
mc.delete(each)
return shapes
def unparentShape(objs=None):
if not objs:
objs = mc.ls(sl=True)
if not objs:
OpenMaya.MGlobal.displayWarning('Please select one or more nodes with shapes to unparent.')
return
elif not isinstance(objs, (list,tuple)):
objs = [objs]
#are these shapes or transforms
transforms = list()
shapes = list()
for obj in objs:
nodeType = mc.nodeType(obj)
if nodeType in ('mesh','nurbsCurve','nurbsSurface','locator','annotationShape'):
shapes.append(obj)
elif nodeType in ('transform', 'joint', 'ikHandle'):
if not mc.listRelatives(obj, shapes=True, path=True, noIntermediate=True):
OpenMaya.MGlobal.displayWarning(obj+' has no shapes, skipping.')
return
transforms.append(obj)
else:
OpenMaya.MGlobal.displayWarning(obj+' must be a shape, or a transform with shapes. Skipping')
return
for each in transforms:
childShapes = mc.listRelatives(each, shapes=True, path=True, noIntermediate=True)
shapes.extend([x for x in childShapes if x not in shapes])
#shapes that share a common parent get unparented together
newTransforms = dict()
for each in shapes:
shapeParent = mc.listRelatives(each, parent=True, fullPath=True)[0]
if not shapeParent in newTransforms:
newTransforms[shapeParent] = mc.createNode('transform', name='unparentedShape#')
newTransforms[shapeParent] = mc.parent(newTransforms[shapeParent], shapeParent)[0]
mc.setAttr(newTransforms[shapeParent]+'.translate', 0,0,0)
mc.setAttr(newTransforms[shapeParent]+'.rotate', 0,0,0)
mc.setAttr(newTransforms[shapeParent]+'.scale', 1,1,1)
newTransforms[shapeParent] = mc.parent(newTransforms[shapeParent], world=True)[0]
shape = mc.parent(each, newTransforms[shapeParent], shape=True, relative=True)[0]
return newTransforms.values()