本文整理汇总了Python中pymel.core.addAttr函数的典型用法代码示例。如果您正苦于以下问题:Python addAttr函数的具体用法?Python addAttr怎么用?Python addAttr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了addAttr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RigFK
def RigFK( jnts=None, side='L', ctrlSize=1.0, stretch=True, color='r' ):
if not jnts:
jnts = pm.ls( sl=True )
else:
jnts = pm.ls( jnts )
# find color of the ctrls
color = 'y'
if side == 'L':
color = 'r'
elif side == 'R':
color = 'b'
shapes = []
for jnt in jnts:
if not jnt or not jnt.type()=='joint':
pm.warning('ehm_tools...RigFK: %s was not a joint, skipped!'%jnt)
shapes.append( (JntToCrv ( jnts = jnt , size = ctrlSize )).newShapes )
LockHideAttr( objs=jnt, attrs='t' )
LockHideAttr( objs=jnt, attrs='radius' )
if stretch == True:
# add length attribute and connect it to scale
pm.addAttr ( jnt , ln = "length" , at = "double" , min = 0 , dv = 1 , k = True )
jnt.length >> jnt.scaleX
LockHideAttr( objs=jnt, attrs='s' )
Colorize( shapes=shapes, color=color )
return shapes
示例2: stretchyBack
def stretchyBack( ikHandleTorso, jntList ):
pymelLogger.debug('Starting: stretchyBack()...')
#Stretchy process
# ArcLen to create curveInfo
curveInfoNodeBack = pm.arclen( ikHandleTorso[2], ch=True )
# add attr to curveinfo Node (normalizedScale)
# this will have a value coming from a multiply divide node that will be
# dividing the current length by the initial length of the curve
# this will be used later to scale the joints
pm.addAttr(curveInfoNodeBack, longName='normalizedScale', attributeType='double')
# get initial length of the curve
iniLen = pm.getAttr( curveInfoNodeBack + '.arcLength' )
# create a node multiplydivide, operation set to division
MDCurveBack = pm.shadingNode( 'multiplyDivide', asUtility=True )
pm.setAttr( MDCurveBack+'.operation', 2 ) # divide
# Connect curve arcLength to input1X
pm.connectAttr( curveInfoNodeBack + '.arcLength', MDCurveBack + '.input1X', force=True )
# Set input2X to initial length of the curve
pm.setAttr(MDCurveBack+'.input2X', iniLen)
# connect outpux x from multiplydivide to normalized scale of the curve info
pm.connectAttr(MDCurveBack + '.outputX', curveInfoNodeBack + '.normalizedScale', force=True)
returnList = [curveInfoNodeBack,MDCurveBack]
pymelLogger.debug('End: stretchyBack()...')
return returnList
示例3: __addInfo__
def __addInfo__(master, slave, channel, mo):
# create master name attribut
if slave.hasAttr('cstTgtName') == False:
pmc.addAttr(slave, longName = 'cstTgtName', dataType = 'string', hidden = False)
attribut = slave.cstTgtName
attribut.setLocked(False)
attribut.set(master.name())
attribut.setLocked(True)
# create channel array attribut
if channel != [1,1,1,1] or slave.hasAttr('cstOptStr'):
if slave.hasAttr('cstOptStr') == False:
pmc.addAttr(slave, longName = 'cstOptStr', dataType = 'string', hidden = False)
attribut = slave.cstOptStr
attribut.setLocked(False)
# create a better information looking
word = ['tr', 'ro', 'sc', 'sh']
s = ''
for i in range(0, len(channel)):
s=s + word[i] + '=' + str(channel[i]) + ' '
attribut.set(s)
attribut.setLocked(True)
# delete previous mo info if no need anymore
if mo==False and slave.hasAttr('cstOffMat'):
slave.cstOffMat.delete()
示例4: __finalizeFkChainShape
def __finalizeFkChainShape(self):
reversedList = list(self.controlsArray)
reversedList.reverse()
#parent shape
for num,ctrl in enumerate(self.controlsArray):
# for shape in ctrl.control.getShapes():
# pm.parent(shape,self.chain[num],r=1,s=1)
pm.parent(ctrl.control.getShape(),self.chain[num],r=1,s=1)
#stretch
#Add attr
pm.addAttr(self.chain[num],ln = 'stretch',at = 'double',dv = 0)
pm.setAttr(self.chain[num] + '.stretch',e = 1,k = 1)
#create node
fkStrectchPMANodeName = nameUtils.getUniqueName(self.side,'fkStrectch','MDN')
fkStrectchPMANode = pm.createNode('plusMinusAverage',n = fkStrectchPMANodeName)
#connect
oriTx = self.chain[num].tx.get()
fkStrectchPMANode.input3D[0].input3Dx.set(oriTx)
self.chain[num].stretch.connect(fkStrectchPMANode.input3D[1].input3Dx)
fkStrectchPMANode.operation.set(1)
fkStrectchPMANode.output3Dx.connect(self.chain[num].tx)
#lock and hide
control.lockAndHideAttr(self.chain[num],["tx","ty","tz","sy","sz","sx"])
#delete grp
for i in range(len(reversedList)):
pm.delete(reversedList[i].controlGrp)
示例5: spineFKIK
def spineFKIK():
'''
Spine FK/IK feature
'''
import pymel.core as pm
pCns = {1:'HIP_CTRL',
2:'HIP_CTRL',
3:'SPINE_LOWER_CTRL',
4:'SPINE_MIDDLE_CTRL',
5:'SPINE_MIDDLE_CTRL',
6:'SPINE_UPPER_CTRL'}
pm.addAttr('WORLD', sn='SpineIKFKSwitch', at='enum', en='IK:FK')
newAttr = pm.PyNode('WORLD.SpineIKFKSwitch')
newAttr.set(0, keyable=True, lock=False)
for i in range(1,7):
pm.parent('jSpine%02d'%i, 'bindSkelSpine')
cnsNode = pm.parentConstraint(pCns[i], 'jSpine%02d'%i, mo=True)
wtAttr = cnsNode.listAttr()[-2:]
condNode = pm.createNode('condition', name='cond_spine%02s_parent'%i)
condNode.colorIfTrueR.set(1)
condNode.colorIfFalseR.set(0)
condNode.colorIfTrueG.set(0)
condNode.colorIfFalseG.set(1)
newAttr >> condNode.firstTerm
condNode.outColorR >> wtAttr[0]
condNode.outColorG >> wtAttr[1]
示例6: rad_load_associations
def rad_load_associations():
someFailures = False
targetFile = ""
files = cmds.fileDialog2(dialogStyle=2, fileFilter="*.radpw", fileMode=1, caption="Load Pickwalk Configuration", okCaption="Load")
if files:
if len(files) > 0:
targetFile = files[0]
if not targetFile:
return
allNodes = cmds.ls(recursive=True)
with open(targetFile) as f:
for line in f:
if not line.startswith("This"):
infoArray = line.split()
# node-name dir dir dir dir
nodeName = infoArray[0]
if pm.objExists(nodeName):
infoIndex = 1
for direction in DIRECTIONS:
dirNode = infoArray[infoIndex]
infoIndex += 1
if dirNode != "null":
try:
if not pm.attributeQuery(dir_to_attr(direction), node=nodeName, exists=True):
pm.addAttr(nodeName, longName=dir_to_attr(direction), attributeType="message")
make_pick_walk(nodeName, dirNode, direction)
except:
print "Error during load of " + nodeName + " -> " + direction + " -> " + dirNode
someFailures = True
if someFailures:
pm.warning("Some relationships failed to load (possibly due to different set of nodes)")
示例7: bdConnectChains
def bdConnectChains():
selection = pm.ls(sl=True)
bindChainChildren = []
if len(selection) == 2:
bindChain = selection[0]
ikfkCon = selection[1]
if ikfkCon.hasAttr('IKFK'):
print 'has attr already'
else:
pm.addAttr(ikfkCon ,ln='IKFK',nn='IKFK',at='float' )
ikfkCon.attr('IKFK').setMin(0)
ikfkCon.attr('IKFK').setMax(1)
ikfkCon.attr('IKFK').setKeyable(True)
fkJnt = pm.ls(bindChain.name().replace('JNT','FK'))[0]
ikJnt = pm.ls(bindChain.name().replace('JNT','IK'))[0]
bdCreateBlend(bindChain,fkJnt,ikJnt,ikfkCon)
bindChainChildren = bindChain.listRelatives(c=True, type= 'joint',ad=True)
bindChainChildren.reverse()
bindChainChildren = bindChainChildren[:3]
for child in bindChainChildren :
fkJnt = pm.ls(child.name().replace('JNT','FK'))[0]
ikJnt = pm.ls(child.name().replace('JNT','IK'))[0]
print child
bdCreateBlend(child,fkJnt,ikJnt,ikfkCon)
示例8: rig_attachToCurve
def rig_attachToCurve(obj, crv, createGroup=True, constrainParent=False):
''' attaches an object to a curve
Args:
obj (pm.PyNode): Object to constrain to
crv (pm.nt.NurbsCurve): Curve to get info from
constrainParent (bool): if we constrain to the object's parent instead of the object
Returns (pm.shadingNode.pointOnCurveInfo): pointOnCurveInfo node that results
Usage:
rig_attachToCurve(pm.ls(sl=True), pm.PyNode('curve1'), createGroup=False, constrainParent=False)
for obj in pm.ls(sl=True):
rig_attachToCurve(obj, pm.PyNode('curve1'), createGroup=False, constrainParent=False)
'''
passArgs=[None,None]
if constrainParent and obj.getParent():
passArgs = [obj.getParent(),obj.getParent()]
elif not obj.getParent() and constrainParent:
pm.error('Could not find a parent for object %s'%obj)
return None
elif createGroup:
grp=pm.group(em=True, n='_'.join([obj.name(),crv.name(),'Offset_GRP']))
grp.inheritsTransform.set(0)
grp.t.set(obj.getRotatePivot(space='world'))
grp.r.set(pm.xform(obj, q=True, ro=True, a=True, ws=True))
pm.addAttr(grp, ln='connectPCObj', dt='string', k=True)
passArgs=[obj,grp]
else:
passArgs=[obj, obj]
poci = rig_getClosestPointNode(passArgs[0], crv, cpoc=True)
mdpma = rig_connectPociWithOffset(poci, passArgs[1])
pm.tangentConstraint(crv, passArgs[1])
return [passArgs[1], poci] + mdpma
示例9: loadTranslationControl
def loadTranslationControl(root_joint, module_name, container, module_control_grp, control_type = "translation", color = [1, 0, 0]):
""" loads translation control onto the root_joint """
path = os.path.join(environ.ControlObjectsPath, "translation_control.ma")
pm.importFile(path, renameAll = True, loadReferenceDepth = "all", namespace =":") # renamePrefix == namespace
# rename default module
translation_control = pm.rename("translation_control", module_name + ":" + root_joint.stripNamespace() + "_translation_control", ignoreShape = False)
translation_control_grp = pm.group(translation_control, name = module_name + ":" + root_joint.stripNamespace() + "_translation_controlGrp")
# move control to root root_joint
pm.delete(pm.pointConstraint(root_joint, translation_control_grp, maintainOffset=False))
translation_control_grp.setParent(module_control_grp)
pm.addAttr(translation_control, longName="ControlType", dataType="string", keyable=False)
pm.addAttr(translation_control, longName="ParentObject", at="message", multi = True)
translation_control.ControlType.set(control_type, type = "string", lock = True)
utils.addNodeToContainer(container, [translation_control, translation_control_grp], ihb = True, includeNetwork = True)
pm.container(container, edit=True, publishAndBind=[translation_control + ".rotate", translation_control.stripNamespace() + "_rotate"])
pm.container(container, edit=True, publishAndBind=[translation_control + ".translate", translation_control.stripNamespace() + "_translate"])
return translation_control, translation_control_grp
示例10: makePolygonsWithAttr
def makePolygonsWithAttr(listOfGeomAttDictTuples):
"""This function takes a list of tuples, each
tuple containing first a point list, and second
a dictionary of attributes where the keys are the
names of the attributes and the values are the
corresponding values for each attribute, then the
function creates a polygon from each point list and
for that polygon, creates an attribute for each
attribute in the attribute dictionary. The return value
is a list of the names of all the created polygons."""
# create an empty list to hold results
curves = []
for item in listOfGeomAttDictTuples:
# each item consists of a point list, and
# an attribute dictionary
pointList, attDict = item[0], item[1]
# this should return the name of the item
curve = ptListToPolyline(pointList)
for key in attDict:
# ln and sn, are long name and short name respectively
pm.addAttr(curve, ln=key, sn=key, dt="string")
# attKey creates a handle that whould point direclty to
# the attribute on that specific object
attKey = '%s.%s' % (curve, key)
# and here we set the attribute to the corresponding
# value.
pm.setAttr(attKey, attDict[key], typ="string")
# finally add the name of the object to the list
# of results.
curves.append(curve)
return curves
示例11: setup_look_at
def setup_look_at(camera):
"""sets up the look at locator for the given camera
"""
# just create a locator under the camera
# and move it to -10
loc = pm.spaceLocator(n=camera.name() + "vertigo_loc#")
# create a new attribute under the camera
global vertigo_attr_name
camera_shape = camera.getShape()
if not camera.hasAttr(vertigo_attr_name):
pm.addAttr(camera, ln=vertigo_attr_name, at="message")
# connect the message attribute of the locator to the camera
loc.message >> camera.attr(vertigo_attr_name)
pm.parent(loc, camera)
loc.t.set(0, 0, -10)
loc.r.set(0, 0, 0)
# lock locators tx, ty and rotate channels
loc.tx.lock()
loc.ty.lock()
loc.r.lock()
示例12: rigBook
def rigBook(containers):
center = createJointChain(name='center')
left = createJointChain(name='left')
right = createJointChain(name='right')
ctrl = containers["ctrl"]
pm.addAttr(containers["ctrl"],
ln="_",
at="enum",
en="______"
)
pm.setAttr(containers["ctrl"]+"._", e=1, keyable=1)
for page in range(pages):
pageName = 'page'+str(page)
skin = createJointChain(pageName+"_")
rigPage(skin, center, left, right, ctrl, pageName)
paper = createPaper(pageName)
pm.select(skin, r=1, hi=1)
pm.select(paper, add=1, )
pm.bindSkin(toAll = 1, colorJoints = 1)
pm.select(cl=1)
pm.parent(paper, containers["paper_grp"])
pm.parent(skin[0], containers["pages_grp"])
pm.select(cl=1)
print "rigged: %s" % pageName
pm.parent(center[0], containers["pageTargets_grp"])
pm.parent(left[0], containers["pageTargets_grp"])
pm.parent(right[0], containers["pageTargets_grp"])
示例13: sumAttr
def sumAttr(sumCtrl=None,
ctrlAttrA=None, ctrlAttrB=None,
ctrlAttrResult=None,
scaleA=None, scaleB=None):
pmaNode = pm.shadingNode('plusMinusAverage',n='%s_Sum'%sumCtrl, asUtility=1)
if scaleA:
scaleA_node = pm.shadingNode('multiplyDivide',n='%s_ScaleA'%sumCtrl, asUtility=1)
pm.setAttr('%s.input1X'%scaleA_node,scaleA)
pm.connectAttr(ctrlAttrA,'%s.input2X'%scaleA_node,f=1)
pm.connectAttr('%s.outputX'%scaleA_node,'%s.input1D[0]'%pmaNode,f=1)
else:
pm.connectAttr(ctrlAttrA,'%s.input1D[0]'%pmaNode,f=1)
if scaleB:
scaleB_node = pm.shadingNode('multiplyDivide',n='%s_ScaleB'%sumCtrl, asUtility=1)
pm.setAttr('%s.input1X'%scaleB_node,scaleB)
pm.connectAttr(ctrlAttrB,'%s.input2X'%scaleB_node,f=1)
pm.connectAttr('%s.outputX'%scaleB_node,'%s.input1D[1]'%pmaNode,f=1)
else:
pm.connectAttr(ctrlAttrB,'%s.input1D[1]'%pmaNode,f=1)
try:
pm.addAttr(sumCtrl, ln=ctrlAttrResult.split('.')[1], k=1)
except Exception, e:
raise( e )
示例14: updateAOVStrAttr
def updateAOVStrAttr( *args ):
strAttr = 'object_list'
sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True)
# filter AOV
id_aov_sets = [ node for name, node in sceneAOVs if node.find('_id_') == 5 ]
for aov in id_aov_sets:
if( not( pm.PyNode(aov).hasAttr(strAttr) ) ):
pm.addAttr( aov, longName=strAttr, dataType='string' )
pm.PyNode(aov+'.'+strAttr).set('')
listMesh = pm.ls(type='mesh')
amount = 0.0
maxValue = len(listMesh)
pm.progressWindow( title='AOV Update Calculation', progress=amount, maxValue=maxValue , isInterruptable=True, status='calculating: 0%' )
for mesh in listMesh:
amount = amount + 1
pm.progressWindow( edit=True, progress=amount, status=('calculating: ' + str( 100 * amount/ maxValue) + '%') )
if( mesh.hasAttr('mtoa_constant_Id') ):
idName = mesh.mtoa_constant_Id.get()
currAOVStrAttr = 'aiAOV_' + idName + '.' + strAttr
pm.PyNode(currAOVStrAttr).set( pm.PyNode(currAOVStrAttr).get() + mesh + ';' )
pm.progressWindow(endProgress=1)
return 1
示例15: add_attr
def add_attr(node, attr_name, debug=False, **kwargs):
"""
Assign attributes to the given object.
>>> import pymel.core as pm
>>> FOO = pm.sphere()
# Result: [nt.Transform(u'nurbsSphere1'),
t.MakeNurbSphere(u'makeNurbSphere2')] #
>>> shapeNode = FOO[-1]
# Get the shape of the FOO
>>> add_attr(shapeNode, "newAttributeName", attributeType='float')
# Create a new attribute called "newAttributeName", type float
:param node: (PyMel nodes) Object to assign new attributes to.
:param attr_name: (String) attributes name
:param debug: (Boolean) Set True if you want to print out the result.
:param kwargs: attribute keywords. ex:
"""
# Add the attribute if it already doesn't exist
if not node.hasAttr(attr_name):
pm.addAttr(node, longName=attr_name, **kwargs)
if debug:
logging.info("Attribute '{}' is added to {}".format(attr_name,
node))
else:
logging.warning("Attribute '{}' already exists on {}".format(attr_name,
node))