def saveScreenshot(self, name, directory=DIRECTORY):
path = os.path.join(directory, '%s.jpg' % name)
# We'll fit the view to the objects in our scene or our selection
cmds.viewFit()
# We'll change our render format to jpg
cmds.setAttr("defaultRenderGlobals.imageFormat", 8) # This is the value for jpeg
# Finally we'll save out our image using the playblast module
# There are a lot of arguments here so it's good to use the documentation to know what's going on
cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200,
showOrnaments=False, startTime=1, endTime=1, viewer=False)
# Return the path of the file we saved
return path
# This will be our first Qt UI!
# We'll be creating a dialog, so lets start by inheriting from Qt's QDialog
python类setAttr()的实例源码
def modifyExtrude(self, teeth=10, length=0.3):
faces = self.getTeethFaces(teeth)
# The extrude node has an attribute called inputComponents
# To change it we can use a simple setAttr call instead of recreating the extrude which can be expensive
# The arguments to changing a list of components is slightly different than a simple setAttr
# it is:
# cmds.setAttr('extrudeNode.inputComponents', numberOfItems, item1, item2, item3, type='componentList')
cmds.setAttr('%s.inputComponents' % self.extrude, len(faces), *faces, type='componentList')
# The *faces will be new to you.
# It basically means to expand a list in place for arguments
# so if the list has ['f[1]', 'f[2]'] etc, it will be expanded in the arguments to be like this
# cmds.setAttr('extrudeNode.inputComponents', 2, 'f[1]', 'f[2]', type='componentList'
# Finally we modify the length
self.changeLength(length)
def follicle(shape, u=0, v=0, name=""):
"""Attach follicle to "shape" at specified "u" and "v" values"""
type = cmds.nodeType(shape)
assert type in ("mesh", "nurbsSurface"), (
"follicle() works on polygonal meshes and nurbs")
src, dst = {
"mesh": (".outMesh", ".inputMesh"),
"nurbsSurface": (".local", ".inputSurface")
}[type]
follicle = cmds.createNode("follicle", name=name + "Shape")
transform = cmds.listRelatives(follicle, parent=True)[0]
cmds.setAttr(follicle + ".parameterU", u)
cmds.setAttr(follicle + ".parameterV", v)
cmds.connectAttr(follicle + ".outTranslate", transform + ".translate")
cmds.connectAttr(follicle + ".outRotate", transform + ".rotate")
cmds.connectAttr(shape + ".worldMatrix[0]", follicle + ".inputWorldMatrix")
cmds.connectAttr(shape + src, follicle + dst, force=True)
return transform
def set_defaults(*args):
"""Set currently selected values from channel box to their default value
If no channel is selected, default all keyable attributes.
"""
for node in cmds.ls(selection=True):
selected_channels = read_selected_channels()
for channel in (selected_channels or
cmds.listAttr(node, keyable=True)):
try:
default = cmds.attributeQuery(channel,
node=node,
listDefault=True)[0]
except Exception:
continue
else:
cmds.setAttr(node + "." + channel, default)
def clone_special(*args):
"""Clone in localspace, and preserve user-defined attributes"""
for transform in cmds.ls(selection=True, long=True):
if cmds.nodeType(transform) != "transform":
cmds.warning("Skipping '%s', not a `transform`" % transform)
continue
shape = _find_shape(transform)
type = cmds.nodeType(shape)
if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
cmds.warning("Skipping '{transform}': cannot clone nodes "
"of type '{type}'".format(**locals()))
continue
cloned = commands.clone(shape, worldspace=False)
new_transform = cmds.listRelatives(cloned,
parent=True,
fullPath=True)[0]
new_transform = cmds.rename(new_transform,
new_transform.rsplit(":", 1)[-1])
for attr in cmds.listAttr(transform,
userDefined=True) or list():
try:
cmds.addAttr(new_transform, longName=attr, dataType="string")
except Exception:
continue
value = cmds.getAttr(transform + "." + attr)
cmds.setAttr(new_transform + "." + attr, value, type="string")
# Connect visibility
cmds.connectAttr(transform + ".visibility",
new_transform + ".visibility")
def offset_orient(joints, amount, axis):
"""Offsets the orient by the given amount
@param joints: Joints to orient.
@param amount: Amount to offset by.
@param axis: Which axis X, Y or Z
"""
for joint in joints:
children = _unparent_children(joint)
attribute = '{0}.jointOrient{1}'.format(joint, axis)
orient = cmds.getAttr(attribute)
orient += amount
cmds.setAttr(attribute, orient)
_reparent_children(joint, children)
if joints:
cmds.select(joints)
def create_shaders():
"""
Creates the red/green/blue shaders.
@return: (Red, green, blue material nodes)
"""
red = cmds.shadingNode('lambert', asShader=True)
cmds.setAttr('{0}.color'.format(red), 1, 0, 0, type='double3')
cmds.setAttr('{0}.ambientColor'.format(red), 1, 0, 0, type='double3')
green = cmds.shadingNode('lambert', asShader=True)
cmds.setAttr('{0}.color'.format(green), 0, 1, 0, type='double3')
cmds.setAttr('{0}.ambientColor'.format(green), 0, 1, 0, type='double3')
blue = cmds.shadingNode('lambert', asShader=True)
cmds.setAttr('{0}.color'.format(blue), 0, 0, 1, type='double3')
cmds.setAttr('{0}.ambientColor'.format(blue), 0, 0, 1, type='double3')
t = 0.9
for node in [red, green, blue]:
cmds.setAttr('{0}.transparency'.format(node), t, t, t, type='double3')
return red, green, blue
def create_node(node_dictionary, parent=None):
"""Create the Maya node described by the given data dictionary.
:param node_dictionary: The data dictionary generated by one of the load/get functions.
:param parent: The node to parent the created node to.
"""
node = cmds.createNode(node_dictionary['nodeType'], name=node_dictionary['name'])
if parent:
cmds.parent(node, parent)
cmds.setAttr('{0}.t'.format(node), *node_dictionary['translate'])
cmds.setAttr('{0}.r'.format(node), *node_dictionary['rotate'])
cmds.setAttr('{0}.s'.format(node), *node_dictionary['scale'])
cmds.setAttr('{0}.rotateOrder'.format(node), node_dictionary['rotateOrder'])
cmds.setAttr('{0}.rotateAxis'.format(node), *node_dictionary['rotateAxis'])
if node_dictionary['nodeType'] == 'joint':
cmds.setAttr('{0}.jointOrient'.format(node), *node_dictionary['jointOrient'])
cmds.setAttr('{0}.radius'.format(node), node_dictionary['radius'])
cmds.setAttr('{0}.side'.format(node), node_dictionary['side'])
cmds.setAttr('{0}.type'.format(node), node_dictionary['type'])
cmds.setAttr('{0}.otherType'.format(node), node_dictionary['otherType'], type='string')
cmds.setAttr('{0}.jointTypeX'.format(node), node_dictionary['jointTypeX'])
cmds.setAttr('{0}.jointTypeY'.format(node), node_dictionary['jointTypeY'])
cmds.setAttr('{0}.jointTypeZ'.format(node), node_dictionary['jointTypeZ'])
for child in node_dictionary.get('children', []):
create_node(child, node)
def mirror(joint, search_for, replace_with):
joints = [joint, ] + (cmds.listRelatives(joint, ad=True, path=True) or [])
for joint in joints:
mirrored_joint = joint.replace(search_for, replace_with)
if cmds.objExists(mirrored_joint):
translate = list(cmds.getAttr('{0}.t'.format(joint))[0])
parent = cmds.listRelatives(joint, parent=True, path=True)
if parent and search_for not in parent[0]:
translate[2] *= -1.0
else:
translate = [x * -1.0 for x in translate]
cmds.setAttr('{0}.t'.format(mirrored_joint), *translate)
rotate = cmds.getAttr('{0}.r'.format(joint))[0]
cmds.setAttr('{0}.r'.format(mirrored_joint), *rotate)
scale = cmds.getAttr('{0}.s'.format(joint))[0]
cmds.setAttr('{0}.s'.format(mirrored_joint), *scale)
def create_curve(control):
"""Create a curve.
:param control: A data dictionary generated from the dump function.
:return: The created curve.
"""
periodic = control['form'] == 2
degree = control['degree']
points = control['cvs']
points = points + points[:degree] if periodic else points
curve = cmds.curve(degree=degree, p=points, n=control['name'], per=periodic, k=control['knots'])
cmds.xform(curve, ws=True, matrix=control['xform'])
cmds.xform(curve, piv=control['pivot'])
cmds.delete(curve, constructionHistory=True)
cmds.setAttr('{0}.overrideEnabled'.format(curve), control['overrideEnabled'])
cmds.setAttr('{0}.overrideRGBColors'.format(curve), control['overrideRGBColors'])
cmds.setAttr('{0}.overrideColorRGB'.format(curve), *control['overrideColorRGB'])
cmds.setAttr('{0}.overrideColor'.format(curve), control['overrideColor'])
return curve
def playblast_snapshot(path = None,format = None, compression = None, hud = None, offscreen = None, range=None, scale = None):
current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png
if range is None:
range = playback_selection_range()
print range
if range is None:
start = cmds.playbackOptions( q=True,min=True )
end = cmds.playbackOptions( q=True,max=True )
range = [start, end]
cmds.playblast(frame =int((range[0] + range[1])/2), cf = path, fmt="image", orn=hud, os=offscreen, wh = scene_resolution(), p=scale, v=False)
cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
def BT_Double3ValuesToNode(values = None, node = None, attr = None):
if not values or len(values) != 3:
return False
cmds.setAttr(node +'.' +attr, values[0], values[1], values[2], type = 'double3')
def doit(radius=5., num=36):
cmds.loadPlugin('rotationDriver', qt=True)
node = cmds.createNode('composeRotate')
node_or = node + '.outRotate'
node_h = node + '.bendH'
node_v = node + '.bendV'
shiftX = radius * 1.25
top0 = _plotBendHV(node_or, node_h, node_v, 'plotStereoProj', radius, num)
cmds.setAttr(top0 + '.tx', -shiftX)
cmds.setAttr(node + '.method', 1)
top1 = _plotBendHV(node_or, node_h, node_v, 'plotExpmap', radius, num)
cmds.setAttr(top1 + '.tx', shiftX)
cmds.delete(node)
cmds.select([top0, top1])
def WeaponBinder():
# Call of Duty specific
for x in xrange(0, len(GUN_BASE_TAGS)):
try:
# Select both tags and parent them
cmds.select(GUN_BASE_TAGS[x], replace = True)
cmds.select(VIEW_HAND_TAGS[x], toggle = True)
# Connect
cmds.connectJoint(connectMode = True)
# Parent
mel.eval("parent " + GUN_BASE_TAGS[x] + " " + VIEW_HAND_TAGS[x])
# Reset the positions of both bones
cmds.setAttr(GUN_BASE_TAGS[x] + ".t", 0, 0, 0)
cmds.setAttr(GUN_BASE_TAGS[x] + ".jo", 0, 0, 0)
cmds.setAttr(GUN_BASE_TAGS[x] + ".rotate", 0, 0, 0)
# Reset the rotation of the parent tag
cmds.setAttr(VIEW_HAND_TAGS[x] + ".jo", 0, 0, 0)
cmds.setAttr(VIEW_HAND_TAGS[x] + ".rotate", 0, 0, 0)
# Remove
cmds.select(clear = True)
except:
pass
# Place a notetrack
def ResetSceneAnim():
# Loop through them all
SceneJoints = cmds.ls(type="joint")
# Loop
for name in SceneJoints:
# Disconnect if required
ResetBoneKeyframes(DagPathFromJoint(name, False).transform())
# Check for undo
if (cmds.objExists(name + ".seanimUndoT")):
# Reset to it
ResetTranslation = cmds.getAttr(name + ".seanimUndoT")[0]
ResetScale = cmds.getAttr(name + ".seanimUndoS")[0]
ResetRotation = cmds.getAttr(name + ".seanimUndoR")[0]
# Apply
cmds.setAttr(name + ".t", ResetTranslation[0], ResetTranslation[1], ResetTranslation[2])
cmds.setAttr(name + ".scale", ResetScale[0], ResetScale[1], ResetScale[2])
cmds.setAttr(name + ".r", 0, 0, 0)
cmds.setAttr(name + ".jo", ResetRotation[0], ResetRotation[1], ResetRotation[2])
# Remove notetracks
if cmds.objExists("SENotes"):
# Delete
cmds.delete("SENotes")
# Processes a joint, creating it's rest position, and returning a dag path
def combine_curves(curve_shapes):
pnt_attr_nodes = []
for node in curve_shapes:
pa = cmds.createNode('pointAttributeToArray')
cmds.connectAttr(node + '.worldSpace', pa + '.inGeometry')
cmds.setAttr(pa + '.pointPosition', 1)
cmds.setAttr(pa + '.pointTangent', 1)
pnt_attr_nodes.append(pa)
positions = cmds.createNode('combineArrays')
tangents = cmds.createNode('combineArrays')
for i, pa in enumerate(pnt_attr_nodes):
cmds.connectAttr(pa + '.outPositionPP', (positions + '.inArrays[{}]').format(i))
cmds.connectAttr(pa + '.outTangentPP', (tangents + '.inArrays[{}]').format(i))
return positions, tangents
def create_hair_system(nucleus=None):
'''Create a hair system, add it to the specified nucleus or active nucleus'''
if not nucleus:
nucleus = get_nucleus()
hair_system = cmds.createNode('hairSystem')
cmds.connectAttr('time1.outTime', hair_system + '.currentTime')
index = cmds.getAttr(nucleus + '.inputActive', size=True)
input_active = '{}.inputActive[{}]'.format(nucleus, index)
input_start = '{}.inputActiveStart[{}]'.format(nucleus, index)
output_object = '{}.outputObjects[{}]'.format(nucleus, index)
cmds.setAttr(hair_system + '.active', 1)
cmds.connectAttr(hair_system + '.currentState', input_active)
cmds.connectAttr(hair_system + '.startState', input_start)
cmds.connectAttr(output_object, hair_system + '.nextState')
cmds.connectAttr(nucleus + '.startFrame', hair_system + '.startFrame')
return hair_system
def recursiveZeroOutControllers(self,node):
if node is not None:
if node.nodeType == 'globalComponent' or node.nodeType == 'hipComponent':
if node.metaNodeName is not None:
controllerName = mel.eval('getMetaNodeConnection -n "'+node.metaNodeName+'" -c "controller";')
cmds.setAttr(controllerName+'.tx',0)
cmds.setAttr(controllerName+'.ty',0)
cmds.setAttr(controllerName+'.tz',0)
cmds.setAttr(controllerName+'.rx',0)
cmds.setAttr(controllerName+'.ry',0)
cmds.setAttr(controllerName+'.rz',0)
cmds.setAttr(controllerName+'.sx',1)
cmds.setAttr(controllerName+'.sy',1)
cmds.setAttr(controllerName+'.sz',1)
for childNode in node.childNodes:
self.recursiveZeroOutControllers(childNode)
def fileLoad(*args):
sel = cmds.ls(sl=True)
origTexture = sel[0]
ctrls = sel[1:]
# get path
path = cmds.getAttr("{0}.fileTextureName".format(origTexture))
if not path:
cmds.warning("No file present in {0}. Cancelling!".format(origTexture))
return
for ctrl in ctrls:
ctrlFile = cmds.connectionInfo("{0}.fileTexture".format(ctrl), sfd=True).partition(".")[0]
# add path to ctrl file
cmds.setAttr("{0}.fileTextureName".format(ctrlFile), path, type="string")
def capReplace(*args):
sel = cmds.ls(sl=True, type="transform")
if sel < 2:
cmds.warning("You don't have two things selected (cap and one ctrl minimum)!")
return
newCap = sel[0]
ctrls = sel[1:]
for ctrl in ctrls:
oldCap = cmds.connectionInfo("{0}.capRig".format(ctrl), sfd=True).partition(".")[0]
dupe = rig.swapDupe(newCap, oldCap, delete=True, name=oldCap)
cmds.connectAttr("{0}.rotateCap".format(ctrl), "{0}.rotateY".format(dupe))
cmds.connectAttr("{0}.message".format(dupe), "{0}.capRig".format(ctrl))
cmds.setAttr("{0}.v".format(dupe), 1)
# if not already, parent cap replace obj in folder and hide
par = cmds.listRelatives(newCap, p=True)
if not par or par[0] != "pastaRigSetupComponents_Grp":
cmds.parent(newCap, "pastaRigSetupComponents_Grp")
cmds.setAttr("{0}.v".format(newCap), 0)
cmds.select(ctrls, r=True)
def softWave(sftmod, arrow, ctrl, *args):
# add values to positions in graph
positions = [0.0, 0.3, 0.6, 0.9, 0.95]
values = [1.0, -0.3, 0.1, -0.05, 0.01]
for i in range(len(positions)):
cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_Position".format(sftmod, i), positions[i])
cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_FloatValue".format(sftmod, i), values[i])
cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_Interp".format(sftmod, i), 2)
cmds.addAttr(arrow, ln="WaveAttrs", at="enum", k=True)
cmds.setAttr("{0}.WaveAttrs".format(arrow), l=True)
# expose these on the control
for j in range(5):
cmds.addAttr(arrow, ln="position{0}".format(j), at="float", min=0.0, max=1.0, dv=positions[j], k=True)
cmds.connectAttr("{0}.position{1}".format(arrow, j),
"{0}.falloffCurve[{1}].falloffCurve_Position".format(sftmod, j))
for j in range(5):
cmds.addAttr(arrow, ln="value{0}".format(j), at="float", min=-1.0, max=1.0, dv=values[j], k=True)
cmds.connectAttr("{0}.value{1}".format(arrow, j),
"{0}.falloffCurve[{1}].falloffCurve_FloatValue".format(sftmod, j))
cmds.setAttr("{0}.position{1}".format(arrow, j), l=True)
cmds.setAttr("{0}.value{1}".format(arrow, j), l=True)
def stripToTranslate(first="none", *args):
"""strips for all selected or entered as args, sets all attrs but translate to locked and hidden"""
attrs = ["rx", "ry", "rz", "sx", "sy", "sz", "visibility"]
objs = []
if first=="none":
objs = getSelection()
else:
objs.append(first)
if args:
for each in args:
objs.append(each)
## print(objs)
for me in objs:
for attr in attrs:
objAttr = me + "." + attr
cmds.setAttr(objAttr, lock=True, k=False)
def stripTransforms(first="none", *args):
"""locks and hides all transforms from channel box. can call multiple objs as arguments or use selection of objects"""
attrs = ["rx", "ry", "rz", "tx", "ty", "tz", "sx", "sy", "sz", "visibility"]
objs = []
if first=="none":
objs = getSelection()
else:
objs.append(first)
if args:
for each in args:
objs.append(each)
print(objs)
for me in objs:
for attr in attrs:
objAttr = me + "." + attr
cmds.setAttr(objAttr, lock=True, k=False)
def positionsAlongCurve(crv="", numPts = 3, *args):
"""
returns list of numPts evenly distributed world positions along given nurbs crv
"""
if not crv:
return
if isType(crv, "nurbsCurve"):
posList = []
shp = cmds.listRelatives(crv, s=True)[0]
poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo")
cmds.connectAttr("{}.local".format(shp), "{}.inputCurve".format(poc))
cmds.setAttr("{}.turnOnPercentage".format(poc), 1)
lineLen = cmds.arclen(crv, ch=False)
dist = float(numPts)/lineLen
for x in range(0, numPts+1):
perc = 1.0/numPts
cmds.setAttr("{}.parameter".format(poc),x*perc)
print x*perc
pos = cmds.getAttr("{}.position".format(poc))[0]
posList.append(pos)
cmds.delete(poc)
return(posList)
def setValues(*args):
"""sets the values from window on all selected objs for appropriate channels"""
sel = cmds.ls(sl=True)
attrs = cmds.checkBoxGrp(widgets["transCBG"], q=True, va3=True)
trans = attrs[0]
rots = attrs[1]
scls = attrs[2]
for obj in sel:
if cmds.objectType(obj)=="transform":
if trans:
t = cmds.floatFieldGrp(widgets["trnFFG"], q=True, v=True)
cmds.setAttr("{}.translate".format(obj), t[0], t[1], t[2])
if rots:
r = cmds.floatFieldGrp(widgets["rotFFG"], q=True, v=True)
cmds.setAttr("{}.rotate".format(obj), r[0],r[1], r[2])
if scls:
s = cmds.floatFieldGrp(widgets["sclFFG"], q=True, v=True)
cmds.setAttr("{}.scale".format(obj), s[0], s[1], s[2])
def changeValue(attr, slider, *args):
value = cmds.floatSliderGrp(slider, q=True, v=True)
cmds.setAttr(attr, value)
# def focusToCamera():
#get camera from focus window
# panel = cmds.getPanel(wf=True)
# cam = cmds.modelEditor(panel, q=True, camera=True)
#----------get camera from focus . . .
#----------have camera list to select from . . .
# (coverageX)
# (coverageY)
def createJointsAlongCurve(crv="", numJnts=3, *args):
jnts = []
crvShp = cmds.listRelatives(crv, s=True)[0]
poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo")
cmds.connectAttr("{}.local".format(crvShp), "{}.inputCurve".format(poc))
cmds.setAttr("{}.turnOnPercentage".format(poc), 1)
lineLen = cmds.arclen(crv)
dist = float(numJnts)/lineLen
for x in range(0, numJnts+1):
perc = 1.0/numJnts
cmds.setAttr("{}.parameter".format(poc),x*perc)
print x*perc
pos = cmds.getAttr("{}.position".format(poc))[0]
jnt = cmds.joint(p=pos)
jnts.append(jnt)
# add one joint at the end to orient
return(jnts)
def hideArnoldAttrs(*args):
"""
will hide the arnold attributes from the channelbox
"""
crvAttrs = [".ai_curve_shaderb", ".ai_curve_shaderg", ".ai_curve_shaderr", ".srate", ".cwdth", ".rcurve"]
meshAttrs = [".emitSpecular", ".emitDiffuse", ".intensity", ".scb", ".scg", ".scr", ".ai_color_temperature", ".ai_use_color_temperature", ".ai_volume", ".ai_indirect", ".ai_sss", ".ai_specular", ".ai_diffuse", ".ai_exposure", ".ai_shadow_density"]
octaneAttrs = [".octGeoType", ".octGenVis", ".octCamVis", ".octShVis", ".octLayerId", ".octBakGrId", ".octRandomSeed", ".octRPassColorR", ".octRPassColorG", ".octRPassColorB", ".octConstTopology", ".octMergeUnweldedVert", ".octSubdLevel", ".octSubdSharpness", ".octSubdBoundInterp", ".octSubdSceme"]
meshes = cmds.ls(type="mesh")
if meshes:
for m in meshes:
for attr in meshAttrs:
cmds.setAttr("{0}.{1}".format(m, attr), keyable=False, channelBox=False)
crvs = cmds.ls(type="nurbsCurve")
if crvs:
for c in crvs:
for attr in crvAttrs:
cmds.setAttr("{0}.{1}".format(c, attr), keyable=False, channelBox=False)
def toggle_sel_shape_vis(*args):
"""toggles the selected transforms' shape visibility"""
sel = cmds.ls(sl=True, type="transform")
if sel:
for obj in sel:
shp = cmds.listRelatives(obj, s=True)
if not shp:
return ()
for s in shp:
currVal = cmds.getAttr("{0}.visibility".format(s))
newVal = 0
if currVal == 0:
newVal = 1
elif currVal == 1:
newVal = 0
cmds.setAttr("{0}.visibility".format(s), newVal)
def JntSegScl(*args):
"""turns on/off selected jnts seg scale compensate attr"""
jnts = cmds.ls(sl=True, type="joint")
if not jnts:
cmds.warning("No joints selected!")
return ()
for jnt in jnts:
currVal = cmds.getAttr("{0}.segmentScaleCompensate".format(jnt))
if currVal == 0:
newVal = 1
elif currVal == 1:
newVal = 0
cmds.setAttr("{0}.segmentScaleCompensate".format(jnt), newVal)