我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用maya.cmds.createNode()。
def _output_node(source, type, suffix): newname = lib.unique(name=source.rsplit("_", 1)[0] + suffix) node = cmds.createNode(type) node = [cmds.listRelatives(node, parent=True) or node][0] node = cmds.rename(node, newname) try: cmds.parent(node, source) match_transform(node, source) except Exception: cmds.warning("Could not create %s" % node) cmds.delete(node) return node
def _maintained_selection_context(): """Maintain selection during context Example: >>> scene = cmds.file(new=True, force=True) >>> node = cmds.createNode("transform", name="Test") >>> cmds.select("persp") >>> with maintained_selection(): ... cmds.select("Test", replace=True) >>> "Test" in cmds.ls(selection=True) False """ previous_selection = cmds.ls(selection=True) try: yield finally: if previous_selection: cmds.select(previous_selection, replace=True, noExpand=True) else: cmds.select(deselect=True, noExpand=True)
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 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 setUp(self): self.group = cmds.createNode('transform', name='skeleton_grp') cmds.select(cl=True) j1 = cmds.joint(p=(0, 10, 0)) cmds.joint(p=(1, 9, 0)) cmds.joint(p=(2, 8, 0)) j = cmds.joint(p=(3, 9, 0)) cmds.joint(p=(4, 6, 0)) cmds.joint(p=(5, 5, 0)) cmds.joint(p=(6, 3, 0)) self.cube = cmds.polyCube()[0] cmds.parent(self.cube, j) cmds.parent(j1, self.group) self.translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')] self.rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')] self.orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')]
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 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 curve_to_hair(curve_shape, hair_system): curve = cmds.listRelatives(curve_shape, parent=True, f=True)[0] curve_name = curve.split('|')[-1] # Create follicle follicle_shape = cmds.createNode('follicle') follicle = cmds.listRelatives(follicle_shape, parent=True, f=True)[0] follicle = cmds.rename(follicle, curve_name + '_follicle#') follicle_shape = cmds.listRelatives(follicle, shapes=True, f=True)[0] cmds.connectAttr(curve + '.worldMatrix', follicle_shape + '.startPositionMatrix') cmds.connectAttr(curve_shape + '.local', follicle_shape + '.startPosition') # # Create output curve out_curve_shape = cmds.createNode('nurbsCurve') out_curve = cmds.listRelatives(out_curve_shape, parent=True, f=True)[0] out_curve = cmds.rename(out_curve, curve_name + '_out#') out_curve_shape = cmds.listRelatives(out_curve, shapes=True, f=True)[0] cmds.connectAttr(follicle + '.outCurve', out_curve_shape + '.create') # Add follicle to hair system add_follicle(follicle_shape, hair_system) return [[follicle, follicle_shape], [out_curve, out_curve_shape]]
def lock(): """Lock scene Add an invisible node to your Maya scene with the name of the current file, indicating that this file is "locked" and cannot be modified any further. """ if not cmds.objExists("lock"): with lib.maintained_selection(): cmds.createNode("objectSet", name="lock") cmds.addAttr("lock", ln="basename", dataType="string") # Permanently hide from outliner cmds.setAttr("lock.verticesOnlySet", True) fname = cmds.file(query=True, sceneName=True) basename = os.path.basename(fname) cmds.setAttr("lock.basename", basename, type="string")
def maintained_selection(): """Maintain selection during context Example: >>> scene = cmds.file(new=True, force=True) >>> node = cmds.createNode("transform", name="Test") >>> cmds.select("persp") >>> with maintained_selection(): ... cmds.select("Test", replace=True) >>> "Test" in cmds.ls(selection=True) False """ previous_selection = cmds.ls(selection=True) try: yield finally: if previous_selection: cmds.select(previous_selection, replace=True, noExpand=True) else: cmds.select(deselect=True, noExpand=True)
def doit(cage_tgt=None): if not cage_tgt: cage_tgt = cmds.ls(sl=True, o=True) cage = cage_tgt[0] tgt = cage_tgt[1:] cmds.loadPlugin('greenCageDeformer.py', qt=True) deformer = cmds.deformer(tgt, type='greenCageDeformer')[0] freezer = cmds.createNode('transformGeometry') cmds.connectAttr(cage + '.o', freezer + '.ig') cmds.connectAttr(cage + '.wm', freezer + '.txf') cmds.connectAttr(freezer + '.og', deformer + '.bc') cmds.disconnectAttr(freezer + '.og', deformer + '.bc') cmds.delete(freezer) cmds.connectAttr(cage + '.w', deformer + '.ic') cmds.dgeval(cmds.listConnections(deformer + '.og', s=False, d=True, sh=True, p=True)) #doit([cmds.polyCube(w=2.5, d=2.5, h=2.5)[0], cmds.polySphere()[0]])
def match_transform(src, dst): """Transform `src` to `dst`, taking worldspace into account Arguments: src (str): Absolute path to source transform dst (str): Absolute path to destination transform """ try: parent = cmds.listRelatives(src, parent=True)[0] except Exception: parent = None node_decompose = cmds.createNode("decomposeMatrix") node_multmatrix = cmds.createNode("multMatrix") connections = { dst + ".worldMatrix": node_multmatrix + ".matrixIn[0]", node_multmatrix + ".matrixSum": node_decompose + ".inputMatrix", node_decompose + ".outputTranslate": src + ".translate", node_decompose + ".outputRotate": src + ".rotate", node_decompose + ".outputScale": src + ".scale", } if parent: connections.update({ parent + ".worldInverseMatrix": node_multmatrix + ".matrixIn[1]" }) for s, d in connections.iteritems(): cmds.connectAttr(s, d, force=True) cmds.refresh() cmds.delete([node_decompose, node_multmatrix])
def combine(nodes): """Produce a new mesh with the contents of `nodes` Arguments: nodes (list): Path to shapes """ unite = cmds.createNode("polyUnite", n=nodes[0] + "_polyUnite") count = 0 for node in nodes: # Are we dealing with transforms, or shapes directly? shapes = cmds.listRelatives(node, shapes=True) or [node] for shape in shapes: try: cmds.connectAttr(shape + ".outMesh", unite + ".inputPoly[%s]" % count, force=True) cmds.connectAttr(shape + ".worldMatrix", unite + ".inputMat[%s]" % count, force=True) count += 1 except Exception: cmds.warning("'%s' is not a polygonal mesh" % shape) if count: output = cmds.createNode("mesh", n=nodes[0] + "_combinedShape") cmds.connectAttr(unite + ".output", output + ".inMesh", force=True) return output else: cmds.delete(unite) return None
def connect_matching_attributes(source, target): """Connect matching attributes from source to target Arguments: source (str): Absolute path to node from which to connect target (str): Target node Example: >>> # Select two matching nodes >>> source = cmds.createNode("transform", name="source") >>> target = cmds.createNode("transform", name="target") >>> cmds.select([source, target], replace=True) >>> source, target = cmds.ls(selection=True) >>> connect_matching_attributes(source, target) """ dsts = cmds.listAttr(target, keyable=True) for src in cmds.listAttr(source, keyable=True): if src not in dsts: continue try: src = "." + src cmds.connectAttr(source + src, target + src, force=True) except RuntimeError as e: cmds.warning("Could not connect %s: %s" % (src, e))
def create_ncloth(input_mesh): """Replace Create nCloth menu item This performs the identical option of nCloth -> Create nCloth with the following changes. 1. Input mesh not made intermediate 2. Current mesh and shape named "currentMesh" Arguments: input_mesh (str): Path to shape """ assert cmds.nodeType(input_mesh) == "mesh", ( "%s was not of type mesh" % input_mesh) nucleus = cmds.createNode("nucleus", name="nucleus1") ncloth = cmds.createNode("nCloth", name="nClothShape1") current_mesh = cmds.createNode("mesh", name="currentMesh") cmds.connectAttr(input_mesh + ".worldMesh[0]", ncloth + ".inputMesh") cmds.connectAttr(ncloth + ".outputMesh", current_mesh + ".inMesh") cmds.connectAttr("time1.outTime", nucleus + ".currentTime") cmds.connectAttr("time1.outTime", ncloth + ".currentTime") cmds.connectAttr(ncloth + ".currentState", nucleus + ".inputActive[0]") cmds.connectAttr(ncloth + ".startState", nucleus + ".inputActiveStart[0]") cmds.connectAttr(nucleus + ".outputObjects[0]", ncloth + ".nextState") cmds.connectAttr(nucleus + ".startFrame", ncloth + ".startFrame") # Assign default shader cmds.sets(current_mesh, addElement="initialShadingGroup") return current_mesh
def template_joints(joints=None, reorient_children=True, reset_orientation=True): if joints is None: joints = cmds.ls(sl=True, type='joint') if not joints: raise RuntimeError('No joint selected to orient.') if reorient_children: children = cmds.listRelatives(fullPath=True, allDescendents=True, type='joint') joints.extend(children) red, green, blue = create_shaders() orient_group = cmds.createNode('transform', name=ORIENT_GROUP) manips = [] for joint in joints: if reset_orientation: cmds.makeIdentity(joint, apply=True) cmds.joint(joint, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', children=False, zeroScaleOrient=True) if not cmds.listRelatives(joint, children=True): zero_orient([joint]) continue group, manip = create_orient_manipulator(joint, blue) manips.append(manip) cmds.parent(group, orient_group) cmds.parentConstraint(joint, group) cmds.setAttr(joint + '.template', 1) cmds.select(manips)
def create_orient_manipulator(joint, material): joint_scale = cmds.jointDisplayScale(query=True) joint_radius = cmds.getAttr('{0}.radius'.format(joint)) radius = joint_scale * joint_radius children = cmds.listRelatives(joint, children=True, path=True) if children: p1 = cmds.xform(joint, q=True, ws=True, t=True) p1 = OpenMaya.MPoint(*p1) p2 = cmds.xform(children[0], q=True, ws=True, t=True) p2 = OpenMaya.MPoint(*p2) radius = p1.distanceTo(p2) arrow_cvs = [[-1, 0, 0], [-1, 2, 0], [-2, 2, 0], [0, 4, 0], [2, 2, 0], [1, 2, 0], [1, 0, 0], [-1, 0, 0]] arrow_cvs = [[x[0]*radius, x[1]*radius, x[2]*radius] for x in arrow_cvs] shape = cmds.curve(name='{0}_zForward'.format(joint), degree=1, point=arrow_cvs) # shape = cmds.sphere(n='{0}_zForward'.format(joint), p=(0, 0, 0), ax=(0, 0, -1), ssw=0, esw=180, r=radius, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0)[0] # cmds.setAttr('{0}.sz'.format(shape), 0) # cmds.select(shape) # cmds.hyperShade(assign=material) group = cmds.createNode('transform', name='{0}_grp'.format(shape)) cmds.parent(shape, group) cmds.makeIdentity(shape, apply=True) cmds.addAttr(shape, longName=MESSAGE_ATTRIBUTE, attributeType='message') cmds.connectAttr('{0}.message'.format(joint), '{0}.{1}'.format(shape, MESSAGE_ATTRIBUTE)) for attr in ['tx', 'ty', 'tz', 'ry', 'rz', 'v']: cmds.setAttr('{0}.{1}'.format(shape, attr), lock=True, keyable=False) return group, shape
def get_knots(curve): """Gets the list of knots of a curve so it can be recreated. :param curve: Curve to query. :return: A list of knot values that can be passed into the curve creation command. """ curve = shortcuts.get_shape(curve) info = cmds.createNode('curveInfo') cmds.connectAttr('{0}.worldSpace'.format(curve), '{0}.inputCurve'.format(info)) knots = cmds.getAttr('{0}.knots[*]'.format(info)) cmds.delete(info) return knots
def BT_Setup(set = None): if not set: return False transforms = cmds.listConnections(set +'.dagSetMembers') if not transforms: return False if not cmds.attributeQuery('Blend_Node', n = set, ex = True): cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string') else: return False btNode = cmds.createNode("BlendTransforms") cmds.setAttr(set +'.Blend_Node', btNode, type = "string") for i in range(0, len(transforms)): baseMatrix = cmds.xform(transforms[i], q = True, m = True) baseScale = cmds.getAttr(transforms[i] +'.scale')[0] baseRotOffset = [0.0, 0.0, 0.0] if cmds.objectType(transforms[i], isType = 'joint'): baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0] btAttr = 'transforms[' +str(i) +'].baseMatrix' btScaleAttr = 'transforms[' +str(i) +'].baseScale' btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset' BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr) BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr) BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr) BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i]) return True
def BT_DisconnectSetup(set = None): if not set: return False if not BT_IsSetupConnected(set = set): cmds.warning('Setup already disconnected!') return False btNode = cmds.getAttr(set +'.Blend_Node') if not btNode or not cmds.objExists(btNode): return False numOutputs = cmds.getAttr(btNode +'.output', size = True) print numOutputs tempMult = None for i in range(0, numOutputs): conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1') conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1') conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1') cmds.select(cl = True) return True
def _plotBendHV(node_or, node_h, node_v, name, radius, num): assert MAngle.uiUnit() == MAngle.kDegrees top = cmds.createNode('transform', n=name) #_createInsideSphere('insideSphere', radius, top) bone = MVector.kXaxisVector * radius invNum = 1. / float(num) angles = [360. * x * invNum - 180. for x in range(num + 1)] def evalPos(attr, val): cmds.setAttr(attr, val) return bone.rotateBy(MEulerRotation([x * _TO_RAD for x in cmds.getAttr(node_or)[0]])) grp = cmds.createNode('transform', n='plotBendH', p=top) for v in angles: cmds.setAttr(node_v, v) _createCurve('plogH', v, [evalPos(node_h, h) for h in angles], grp) grp = cmds.createNode('transform', n='plotBendV', p=top) for h in angles: cmds.setAttr(node_h, h) _createCurve('plotV', h, [evalPos(node_v, v) for v in angles], grp) return top #------------------------------------------------------------------------------
def conform_curve(source, destination): point_on_curve = cmds.createNode('nearestPointOnCurve') cmds.connectAttr(destination + '.worldSpace', point_on_curve + '.inputCurve') for i, point in enumerate(cmds.getAttr(source + '.cv[*]')): cmds.setAttr(point_on_curve + '.inPosition', point[0], point[1], point[2]) result_point = cmds.getAttr(point_on_curve + '.result.position')[0] cmds.setAttr('{}.cv[{}]'.format(source, i), result_point[0], result_point[1], result_point[2]) cmds.delete(point_on_curve)
def multi_curve_field(curve_shapes): positions, tangents = combine_curves(curve_shapes) field = cmds.createNode('pointCloudToField') cmds.connectAttr(positions + '.outArray', field + '.inPositionPP') cmds.connectAttr(tangents + '.outArray', field + '.inDirectionPP')
def toggle_burnin(value): '''Toggle default viewport burnin''' viewport_burnin = get_viewport_burnin() if viewport_burnin: cmds.setAttr(viewport_burnin + '.v', value) return if not value: return if not cmds.pluginInfo(burnin.type_name, q=True, loaded=True): cmds.loadPlugin(burnin.type_name) viewport_burnin = cmds.createNode('burnin') cmds.addAttr(viewport_burnin, ln='viewport_burnin', at='bool', dv=True) cmds.setAttr(viewport_burnin + '.fontSize', 16) cmds.setAttr(viewport_burnin + '.fontWeight', 75) cmds.setAttr(viewport_burnin + '.fontAlpha', 0.75) t0 = viewport_burnin + '.textArray[0]' cmds.setAttr(t0 + '.textString', '{frame:0>3d}\n{camera}', type='string') cmds.setAttr(t0 + '.textColor', 1, 1, 1) cmds.setAttr(t0 + '.textAlign', 7) t1 = viewport_burnin + '.textArray[1]' cmds.setAttr(t1 + '.textString', '{user}\n{scene}', type='string') cmds.setAttr(t1 + '.textColor', 1, 1, 1) cmds.setAttr(t1 + '.textAlign', 6)
def new_strand(hair_system=None): if not hair_system: selection = cmds.ls(sl=True, dag=True, leaf=True, type='hairSystem') if selection: hair_system = selection[0] start = om.MVector(0, 0, 0) end = om.MVector(0, 0, 24) start_loc = cmds.spaceLocator(name='strand_start#')[0] end_loc = cmds.spaceLocator(name='strand_end#')[0] cmds.xform(end_loc, ws=True, translation=end) tta = cmds.createNode('transformsToArrays') cmds.connectAttr(start_loc + '.worldMatrix', tta + '.inTransforms[0].inMatrix') cmds.connectAttr(end_loc + '.worldMatrix', tta + '.inTransforms[1].inMatrix') pcc = cmds.createNode('pointCloudToCurve') cmds.connectAttr(tta + '.outPositionPP', pcc + '.inArray') expand_grp = cmds.group([start_loc, end_loc], name='strand_expand_grp#') curve, curve_shape = curve_between(start, end, name='strand_curve#') cmds.connectAttr(pcc + '.outCurve', curve_shape + '.create') root_grp = cmds.group(empty=True, name='strand_grp#') cmds.parent([expand_grp, curve], root_grp) follicle_nodes, out_curve_nodes = add_curve_to_system(curve_shape, hair_system) follicle_shape = follicle_nodes[1] cmds.setAttr(follicle_shape + '.pointLock', 3) cmds.setAttr(follicle_shape + '.sampleDensity', 24)
def unique_name(name, format="%02d", namespace="", prefix="", suffix=""): """Return unique `name` The function takes into consideration an optional `namespace` and `suffix`. The suffix is included in evaluating whether a name exists - such as `name` + "_GRP" - but isn't included in the returned value. If a namespace is provided, only names within that namespace are considered when evaluating whether the name is unique. Arguments: format (str, optional): The `name` is given a number, this determines how this number is formatted. Defaults to a padding of 2. E.g. my_name01, my_name02. namespace (str, optional): Only consider names within this namespace. suffix (str, optional): Only consider names with this suffix. Example: >>> name = cmds.createNode("transform", name="MyName") >>> cmds.objExists(name) True >>> unique = unique_name(name) >>> cmds.objExists(unique) False """ iteration = 1 unique = prefix + (name + format % iteration) + suffix while cmds.objExists(namespace + ":" + unique): iteration += 1 unique = prefix + (name + format % iteration) + suffix if suffix: return unique[:-len(suffix)] return unique
def connect_transform(driver, driven, source=WorldSpace, compensate=False): """Connect translation, rotation and scale via decomposeMatrix Arguments: driver (str): Absolute path to driver driven (str): Absolute path to driven source (str, optional): Either WorldSpace or LocalSpace, default WorldSpace compensate (bool, optional): Whether or not to take into account the current transform, default False. Returns: output (list): Newly created nodes """ outputattr = ".matrix" if source == LocalSpace else ".worldMatrix[0]" assert cmds.objExists(driver), "%s not found" % driver assert cmds.objExists(driven), "%s not found" % driven decompose = driver + "_decompose" output = [decompose] if not cmds.objExists(decompose): decompose = cmds.createNode("decomposeMatrix", name=decompose) if compensate: multMatrix = cmds.createNode( "multMatrix", name=driver + "_multMatrix") # Compensate for drivens parentMatrix. cmds.connectAttr(driver + outputattr, multMatrix + ".matrixIn[0]") cmds.connectAttr(driven + ".parentInverseMatrix", multMatrix + ".matrixIn[1]") cmds.connectAttr(multMatrix + ".matrixSum", decompose + ".inputMatrix") output.append(multMatrix) else: cmds.connectAttr(driver + outputattr, decompose + ".inputMatrix") # Drive driven with compensated driver. cmds.connectAttr(decompose + ".outputTranslate", driven + ".t") cmds.connectAttr(decompose + ".outputRotate", driven + ".r") cmds.connectAttr(decompose + ".outputScale", driven + ".s") return output
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 create_spine(start_joint, end_joint, lower_control, upper_control, name='spine'): spline_chain, original_chain = shortcuts.duplicate_chain(start_joint, end_joint, prefix='ikSpine_') # Create the spline ik ikh, effector, curve = cmds.ikHandle( name='{0}_ikh'.format(name), solver='ikSplineSolver', startJoint=spline_chain[0], endEffector=spline_chain[-1], parentCurve=False, simplifyCurve=False) effector = cmds.rename(effector, '{0}_eff'.format(name)) curve = cmds.rename(curve, '{0}_crv'.format(name)) # Create the joints to skin the curve curve_start_joint = cmds.duplicate(start_joint, parentOnly=True, name='{0}CurveStart_jnt'.format(name)) cmds.parent(curve_start_joint, lower_control) curve_end_joint = cmds.duplicate(end_joint, parentOnly=True, name='{0}CurveEnd_jnt'.format(name)) cmds.parent(curve_end_joint, upper_control) # Skin curve cmds.skinCluster(curve_start_joint, curve_end_joint, curve, name='{0}_scl'.format(name), tsb=True) # Create stretch network curve_info = cmds.arclen(curve, constructionHistory=True) mdn = cmds.createNode('multiplyDivide', name='{0}Stretch_mdn'.format(name)) cmds.connectAttr('{0}.arcLength'.format(curve_info), '{0}.input1X'.format(mdn)) cmds.setAttr('{0}.input2X'.format(mdn), cmds.getAttr('{0}.arcLength'.format(curve_info))) cmds.setAttr('{0}.operation'.format(mdn), 2) # Divide # Connect to joints for joint in spline_chain[1:]: tx = cmds.getAttr('{0}.translateX'.format(joint)) mdl = cmds.createNode('multDoubleLinear', name='{0}Stretch_mdl'.format(joint)) cmds.setAttr('{0}.input1'.format(mdl), tx) cmds.connectAttr('{0}.outputX'.format(mdn), '{0}.input2'.format(mdl)) cmds.connectAttr('{0}.output'.format(mdl), '{0}.translateX'.format(joint)) # Setup advanced twist cmds.setAttr('{0}.dTwistControlEnable'.format(ikh), True) cmds.setAttr('{0}.dWorldUpType'.format(ikh), 4) # Object up cmds.setAttr('{0}.dWorldUpAxis'.format(ikh), 0) # Positive Y Up cmds.setAttr('{0}.dWorldUpVectorX'.format(ikh), 0) cmds.setAttr('{0}.dWorldUpVectorY'.format(ikh), 1) cmds.setAttr('{0}.dWorldUpVectorZ'.format(ikh), 0) cmds.setAttr('{0}.dWorldUpVectorEndX'.format(ikh), 0) cmds.setAttr('{0}.dWorldUpVectorEndY'.format(ikh), 1) cmds.setAttr('{0}.dWorldUpVectorEndZ'.format(ikh), 0) cmds.connectAttr('{0}.worldMatrix[0]'.format(lower_control), '{0}.dWorldUpMatrix'.format(ikh)) cmds.connectAttr('{0}.worldMatrix[0]'.format(upper_control), '{0}.dWorldUpMatrixEnd'.format(ikh)) # Constrain original chain back to spline chain for ik_joint, joint in zip(spline_chain, original_chain): if joint == end_joint: cmds.pointConstraint(ik_joint, joint, mo=True) cmds.orientConstraint(upper_control, joint, mo=True) else: cmds.parentConstraint(ik_joint, joint)
def test_types(self): print("start : node type test.") cmds.file(new=True, f=True) m = mtn.M(cmds.polyCube()[0]) _name = m.name() m2 = mtn.M(_name) assert(m.nodeType() == u'transform') assert(hash(m) == hash(m2)) assert(hash(m.t) == hash(m2.attr("t"))) assert(hash(m.translate) == hash(m2.attr("t"))) assert(hash(m.t) == hash(m2.attr("translate"))) assert(hash(m.t.tx) == hash(m2.attr("translate").tx)) assert(hash(m.tx) == hash(m2.attr("translate").attr("tx"))) assert(hash(m.translateX) == hash(m2.attr("translate").attr("tx"))) assert(hash(m.pim) == hash(m2.attr("pim"))) assert(hash(m.pim) == hash(m2.pim)) assert(hash(m.pim[0]) != hash(m2.pim)) assert(hash(m.pim[0]) == hash(m2.pim[0])) assert(hash(mtn.M(_name+".translateX")) == hash(mtn.M(_name).attr("t").attr("tx"))) assert(hash(mtn.M(_name+".translateX")) == hash(mtn.M(_name).attr("t.translateX"))) assert(m == m2) assert(m.t == m2.attr("t")) assert(m.translate == m2.attr("t")) assert(m.t == m2.attr("translate")) assert(m.t.tx == m2.attr("translate").tx) assert(m.tx == m2.attr("translate").attr("tx")) assert(m.translateX == m2.attr("translate").attr("tx")) assert(m.pim == m2.attr("pim")) assert(m.pim == m2.pim) assert(m.pim[0] != m2.pim) assert(m.pim[0] == m2.pim[0]) assert(mtn.M(_name+".translateX") == mtn.M(_name).attr("t").attr("tx")) assert(mtn.M(_name+".translateX") == mtn.M(_name).attr("t.translateX")) j = mtn.M(cmds.createNode(u"joint")) assert(j.nodeType() == u'joint') t = mtn.M(u"time1") assert(t.nodeType() == u'time') print("end : node type test.")
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 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()