Python源码示例:pymel.core.addAttr()
示例1
def getBaseCtrl(self, sCtrlType, sAttrName, sCtrlName, fRadius, iDegree = 1, iSection = 8):
nCtrl = None
self.ctrlCreated = False
try:
nCtrl= self.masterGrp.getAttr(sAttrName)
except pymel.MayaAttributeError:
try:
nCtrl = pymel.PyNode(self.prefix + sCtrlName)
except pymel.MayaNodeError:
if (sCtrlName != (self.prefix + "Option_Ctrl")):
nCtrl = pymel.PyNode(self.ctrls.cvControl(sCtrlType, sCtrlName, r=fRadius, d=iDegree, dir="+X"))
else:
nCtrl = pymel.PyNode(self.ctrls.cvCharacter(sCtrlType, sCtrlName, r=(fRadius*0.2)))
self.ctrlCreated = True
finally:
#Since there is no connection between the master and the node found, create the connection
self.masterGrp.addAttr(sAttrName, attributeType='message')
nCtrl.message.connect(self.masterGrp.attr(sAttrName))
return nCtrl
示例2
def create(self):
# reverse_foot_controller = pm.selected()[0]
# foot_ik_ankle_joint = pm.selected()[0]
# foot_ik_ball_joint = pm.selected()[0]
# foot_ik_tip_joint = pm.selected()[0]
#
# attrs = [
# 'tipHeading',
# 'tipRoll',
# 'tipBank',
# 'ballRoll',
# 'ballBank'
# ]
#
#
# for attr in attrs:
# pm.addAttr(reverse_foot_controller, ln=attr, at='float', k=1)
#
# reverse_foot_controller.tipHeading >> foot_ik_tip_joint.ry
# reverse_foot_controller.tipRoll >> foot_ik_tip_joint.rx
# reverse_foot_controller.tipBank >> foot_ik_tip_joint.rz
#
# reverse_foot_controller.ballRoll >> foot_ik_ball_joint.rx
# reverse_foot_controller.ballBank >> foot_ik_ball_joint.rz
pass
示例3
def set_finalGatherHide(cls, value):
"""sets the finalGatherHide to on or off for the given list of objects
"""
attr_name = "miFinalGatherHide"
objects = pm.ls(sl=1)
for obj in objects:
shape = obj
if isinstance(obj, pm.nt.Transform):
shape = obj.getShape()
if not isinstance(shape, (pm.nt.Mesh, pm.nt.NurbsSurface)):
continue
# add the attribute if it doesn't already exists
if not shape.hasAttr(attr_name):
pm.addAttr(shape, ln=attr_name, at="long", min=0, max=1, k=1)
obj.setAttr(attr_name, value)
示例4
def getBaseGrp(self, sAttrName, sGrpName):
nGrpNode = None
try:
nGrpNode = self.masterGrp.getAttr(sAttrName)
except pymel.MayaAttributeError:
try:
nGrpNode = pymel.PyNode(sGrpName)
except pymel.MayaNodeError:
nGrpNode = pymel.createNode("transform", name=sGrpName)
finally:
#Since there is no connection between the master and the node found, create the connection
self.masterGrp.addAttr(sAttrName, attributeType='message')
nGrpNode.message.connect(self.masterGrp.attr(sAttrName))
return nGrpNode
示例5
def export_network(_data, **kwargs):
log.debug('CreateNetwork {0}'.format(_data))
# We'll deal with two additional attributes, '_network' and '_uid'.
# Thoses two attributes allow us to find the network from the value and vice-versa.
# Note that since the '_uid' refer to the current python context, it's value could be erroned when calling import_network.
# However the change of collisions are extremely improbable so checking the type of the python variable is sufficient.
# Please feel free to provide a better design if any if possible.
# Optimisation: Use existing network if already present in scene
if hasattr(_data, '_network') and libPymel.is_valid_PyNode(_data._network):
network = _data._network
else:
# Automaticly name network whenever possible
if hasattr(_data, '__getNetworkName__') and _data.__getNetworkName__ is None:
networkName = _data.__class__.__name__
else:
networkName = _data.__getNetworkName__() if hasattr(_data, '__getNetworkName__') else _data.__class__.__name__
_data._network = networkName
network = pymel.createNode('network', name=networkName)
# Ensure the network have the current python id stored
if not network.hasAttr('_uid'):
pymel.addAttr(network, longName='_uid', niceName='_uid', at='long') # todo: validate attributeType
# network._uid.set(id(_data))
# Convert _pData to basic data dictionary (recursive for now)
dicData = core._export_basicData(_data, _bRecursive=False, **kwargs)
assert(isinstance(dicData, dict))
fnNet = network.__apimfn__()
for key, val in dicData.items():
if val is not None:
if key == '_class' or key[0] != '_': # Attributes starting with '_' are protected or private
_addAttr(fnNet, key, val)
return network
# todo: add an optimisation to prevent recreating the python variable if it already exist.
示例6
def _create_data_attribute(self):
"""creates attribute in self._object to hold the data
"""
if not self._object.hasAttr("pivotData"):
pm.addAttr(self._object, ln="pivotData", at="compound", nc=1)
if not self._object.hasAttr("futurePivot"):
pm.addAttr(
self._object,
ln="futurePivot",
at="message",
p="pivotData"
)
示例7
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()
示例8
def setup_vertigo(camera):
"""sets up the vertigo for the given camera
"""
# camera should have the vertigo locator
global vertigo_attr_name
global vertigo_global_attr_name
vertigo_loc = camera.attr(vertigo_attr_name).inputs()[0]
# get the initial distance of the vertigo locator
z1 = vertigo_loc.tz.get()
f1 = camera.focalLength.get()
# create a locator under world to hold the locator at the same place
world_loc = pm.spaceLocator(n=camera.name() + "vertigo_space_loc#")
# connect world_loc to camera
if not camera.hasAttr(vertigo_global_attr_name):
pm.addAttr(camera, ln=vertigo_global_attr_name, at="message")
world_loc.message >> camera.attr(vertigo_global_attr_name)
# position the world_loc to the correct place
pm.parent(world_loc, vertigo_loc)
world_loc.t.set(0, 0, 0)
world_loc.r.set(0, 0, 0)
pm.parent(world_loc, w=True)
# unlock vertigo_loc's translate
vertigo_loc.tx.unlock()
vertigo_loc.ty.unlock()
pm.pointConstraint(world_loc, vertigo_loc)
# create the expression
expr_str = camera.name() + ".focalLength = (" + vertigo_loc.name() + \
".tz / " + str(z1) + ") * " + str(f1) + ";"
expr = pm.expression(s=expr_str)
示例9
def store_data(self, data):
"""stores the given data
"""
if not self.light.hasAttr(self.custom_data_storage_attr_name):
pm.addAttr(
self.light,
ln=self.custom_data_storage_attr_name,
dt='string'
)
self.light.setAttr(self.custom_data_storage_attr_name, data)
示例10
def store_node(self, node):
"""stores the node in the storage attribute
"""
if not self.light.hasAttr(self.message_storage_attr_name):
pm.addAttr(
self.light,
ln=self.message_storage_attr_name,
m=1
)
node.message >> self.light.attr(self.message_storage_attr_name).next_available
示例11
def create_switch_setup(self):
"""Creates the required IK/FK blend setup
"""
if self.ik_hierarchy is None:
raise RuntimeError("No IK hierarchy!")
if self.fk_hierarchy is None:
raise RuntimeError("No FK_hierarchy!")
self.ik_fk_switch_handle, shape = pm.circle(normal=(1, 0, 0), radius=0.5)
pm.parent(self.ik_fk_switch_handle, self.base_hierarchy.joints[0], r=1)
pm.parent(self.ik_fk_switch_handle, self.base_hierarchy.joints[0].getParent())
pm.addAttr(self.ik_fk_switch_handle, sn="ikFkSwitch", dv=0, at="float", min=0, max=1, k=True)
# reverser
reverser = pm.nt.Reverse()
self.ik_fk_switch_handle.ikFkSwitch >> reverser.inputX
for i in range(len(self.base_hierarchy.joints)):
bj = self.base_hierarchy.joints[i]
ikj = self.ik_hierarchy.joints[i]
fkj = self.fk_hierarchy.joints[i]
parent_constraint1 = pm.parentConstraint(ikj, bj)
parent_constraint2 = pm.parentConstraint(fkj, bj)
# get the weight alias list
wal = pm.parentConstraint(parent_constraint1, q=1, wal=1)
reverser.outputX >> wal[0]
self.ik_fk_switch_handle.ikFkSwitch >> wal[1]
# lock the transforms
self.ik_fk_switch_handle.t.setKeyable(False)
self.ik_fk_switch_handle.t.lock()
self.ik_fk_switch_handle.r.setKeyable(False)
self.ik_fk_switch_handle.r.lock()
self.ik_fk_switch_handle.s.setKeyable(False)
self.ik_fk_switch_handle.s.lock()
self.ik_fk_switch_handle.v.setKeyable(False)
示例12
def add_miLabel(cls):
selection = pm.ls(sl=1)
for node in selection:
if node.type() == 'Transform':
if node.hasAttr('miLabel'):
pass
else:
pm.addAttr(node, ln='miLabel', at='long', keyable=True)
示例13
def addAttributes(target, attrList):
"""
Add attributes to target.
:param target: `PyNode` target node
:param attrList: `list` list of dictionaries defining attribute properties
[{ "ln": `string` - name of the attribtue,
"at": `string` - type of the attribute,
... - other pm.addAttr funtion flags,
"cb": `bool` - display in channelBox
},
{
}
...
]
:return:
"""
if not isinstance(attrList, list):
attrList = [attrList]
for attrDict in attrList:
paramDict = attrDict.copy()
cb = 0
if "cb" in attrDict.keys():
cb = attrDict["cb"]
del paramDict["cb"]
pm.addAttr(target, **paramDict)
if "cb" in attrDict.keys():
pm.setAttr("{0}.{1}".format(target.name(), attrDict["ln"]), cb=cb)
示例14
def addBreakLine(ctrl, contentString):
"""
add a breakline to object's channelbox, usually for ctrlers
:param ctrl: `PyNode` object to add breakline to
:param contentString: `string` breakline content
:return:
"""
attrName = "_"
while pm.objExists("{0}.{1}".format(ctrl.name(), attrName)):
attrName = attrName + "_"
pm.addAttr(ctrl, ln=attrName, at="enum", en=contentString)
pm.setAttr("{0}.{1}".format(ctrl.name(), attrName), e=1, channelBox=1)
示例15
def addEnumAttribute(node,
longName,
value,
enum,
niceName=None,
shortName=None,
keyable=True,
readable=True,
storable=True,
writable=True):
"""
Add an enumerate attribute to a node
Arguments:
node (dagNode): The object to add the new attribute.
longName (str): The attribute name.
value (int): The default value.
enum (list of str): The list of elements in the enumerate control
niceName (str): The attribute nice name. (optional)
shortName (str): The attribute short name. (optional)
keyable (bool): Set if the attribute is keyable or not. (optional)
readable (bool): Set if the attribute is readable or not. (optional)
storable (bool): Set if the attribute is storable or not. (optional)
writable (bool): Set if the attribute is writable or not. (optional)
Returns:
str: The long name of the new attribute
"""
if node.hasAttr(longName):
mgear.log("Attribute '" + longName + "' already exists",
mgear.sev_warning)
return
data = {}
if shortName is not None:
data["shortName"] = shortName
if niceName is not None:
data["niceName"] = niceName
data["attributeType"] = "enum"
data["en"] = ":".join(enum)
data["keyable"] = keyable
data["readable"] = readable
data["storable"] = storable
data["writable"] = writable
node.addAttr(longName, **data)
node.setAttr(longName, value)
return node.attr(longName)
示例16
def addProxyAttribute(sourceAttrs, targets, duplicatedPolicy=None):
"""Add proxy paramenter to a list of target dagNode
Duplicated channel policy, stablish the rule in case the channel already
exist on the target.
Duplicate policy options
================ =======================================================
index This policy will add an index to avoid clashing channel
names
fullName This policy will add the name of the source object to
the channel
merge This policy will merge the channels
================ =======================================================
Arguments:
sourceAttrs (attr or list of attr): The parameters to be connected as
proxy
targets (dagNode or list of dagNode): The list of dagNode to add the
proxy paramenter
duplicatedPolicy (string, optional): Set the duplicated channel policy
"""
if not isinstance(targets, list):
targets = [targets]
if not isinstance(sourceAttrs, list):
sourceAttrs = [sourceAttrs]
for sourceAttr in sourceAttrs:
for target in targets:
attrName = sourceAttr.longName()
if target.hasAttr(sourceAttr.longName()):
if duplicatedPolicy == "index":
i = 0
while target.hasAttr(sourceAttr.longName() + str(i)):
i += 1
attrName = sourceAttr.longName() + str(i)
elif duplicatedPolicy == "fullName":
attrName = "{}_{}".format(sourceAttr.nodeName(),
sourceAttr.longName())
if not target.hasAttr(attrName):
target.addAttr(attrName, pxy=sourceAttr)
else:
pm.displayWarning(
"The proxy channel %s already exist on: %s."
% (sourceAttr.longName(), target.name()))
示例17
def create_ik_setup(self, solver='ikRPsolver', controller_radius=0.5):
"""Creates IK setup
"""
self.ik_handle, self.ik_end_effector = \
pm.ikHandle(sj=self.start_joint, ee=self.end_joint, solver=solver)
self.ik_end_controller, shape = pm.circle(
normal=(0, 1, 0),
radius=controller_radius
)
pm.parent(self.ik_end_controller, self.ik_end_effector)
self.ik_end_controller.t.set(0, 0, 0)
self.ik_end_controller.r.set(0, 0, 0)
# create default scale attribute
pm.addAttr(self.ik_end_controller, sn="minScale", at="float", dv=1.0, k=True)
pm.addAttr(self.ik_end_controller, sn="maxScale", at="float", dv=2.0, k=True)
for j in self.joints[:-1]: # do not scale the last joint
self.ik_end_controller.minScale >> j.sx
pm.parent(self.ik_end_controller, w=1)
from anima.env.mayaEnv import auxiliary
auxiliary.axial_correction_group(self.ik_end_controller)
# constraint the orientation of the last joint to the controller
pm.orientConstraint(self.ik_end_controller, self.joints[-1], mo=1)
# create the point constraint
pm.pointConstraint(self.ik_end_controller, self.ik_handle)
# create pole controller
self.ik_pole_controller = pm.spaceLocator(name='ikPoleController#')
# place it to the extension of the pole vector
pm.parent(self.ik_pole_controller, self.joints[1], r=1)
pm.parent(self.ik_pole_controller, w=1)
# I don't like this but it will help a lot
move_amount = [0, -1, 0]
if pm.xform(self.ik_pole_controller, q=1, ws=1, t=1)[0] < 0:
move_amount = [0, 1, 0]
pm.move(self.ik_pole_controller, move_amount, r=1, os=1, wd=1)
pm.poleVectorConstraint(self.ik_pole_controller, self.ik_handle)
auxiliary.axial_correction_group(self.ik_pole_controller)
# group everything under the main_group
self.main_group = pm.nt.Transform(name='IKLimbJointHierarchy_Grp#')
pm.parent(self.ik_handle, self.main_group)
pm.parent(self.ik_end_controller.getParent(), self.main_group)
pm.parent(self.ik_pole_controller.getParent(), self.main_group)
if self.do_stretchy:
self.create_stretch_setup()