Python maya.cmds.rename() Examples
The following are 29
code examples of maya.cmds.rename().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
maya.cmds
, or try the search function
.
Example #1
Source File: dpControls.py From dpAutoRigSystem with GNU General Public License v2.0 | 7 votes |
def renameShape(self, transformList, *args): """Find shapes, rename them to Shapes and return the results. """ resultList = [] for transform in transformList: # list all children shapes: childShapeList = cmds.listRelatives(transform, shapes=True, children=True, fullPath=True) if childShapeList: # verify if there is only one shape and return it renamed: if len(childShapeList) == 1: shape = cmds.rename(childShapeList[0], transform+"Shape") cmds.select(clear=True) resultList.append(shape) # else rename and return one list of renamed shapes: elif len(childShapeList) > 1: for i, child in enumerate(childShapeList): shape = cmds.rename(child, transform+str(i)+"Shape") resultList.append(shape) cmds.select(clear=True) else: print "There are not children shape to rename inside of:", transform return resultList
Example #2
Source File: go.py From SIWeightEditor with MIT License | 6 votes |
def maya_import(): temp = __name__.split('.')#nameは自分自身のモジュール名。splitでピリオドごとに3分割。 folderPath = os.path.join(os.getenv('MAYA_APP_DIR'),'Scripting_Files','go') if not os.path.exists(folderPath): os.makedirs(os.path.dirname(folderPath+os.sep)) # 末尾\\が必要なので注意 #print folderPath files = os.listdir(folderPath) if files is not None: for file in files: print file nameSpace = file.replace('.ma', '') cmds.file(folderPath+os.sep+file, i=True, typ="mayaAscii", iv=True, mnc=False, options="v=0;", pr=True) #重複マテリアルにファイル名が頭に付与されてしまうのを修正 allMat = cmds.ls(mat=True) fileName = file.split('.')[0] for mat in allMat: if mat.startswith(fileName+'_'): cmds.rename(mat, mat.replace(fileName+'_', '')) cmds.inViewMessage( amg='<hl>Go Maya</hl> : Imoprt objects', pos='midCenterTop', fade=True, ta=0.75, a=0.5) else: cmds.inViewMessage( amg='<hl>Go Maya</hl> : There is no exported object', pos='midCenterTop', fade=True, ta=0.75, a=0.5)
Example #3
Source File: obj.py From cmt with MIT License | 6 votes |
def import_obj(file_path): old_nodes = set(cmds.ls(assemblies=True)) cmds.file( file_path, i=True, type="OBJ", ignoreVersion=True, mergeNamespacesOnClash=False, options="mo=0", ) new_nodes = set(cmds.ls(assemblies=True)) new_nodes = new_nodes.difference(old_nodes) new_mesh = list(new_nodes)[0] name = os.path.splitext(os.path.basename(file_path))[0] return cmds.rename(new_mesh, name)
Example #4
Source File: curve.py From maya-spline-ik with GNU General Public License v3.0 | 6 votes |
def createCurveShape(name, points): """ Create a curve and rename the shapes to be unique. :param str name: Name of curve :param list points: List of points. """ # create curve curve = cmds.curve(p=points, d=1, n=name) # rename shapes shapes = [] for shape in cmds.listRelatives(curve, s=True, f=True) or []: shape = cmds.rename(shape, "{0}Shape".format(name)) shapes.append(shape) return curve, shapes
Example #5
Source File: manager.py From spore with MIT License | 6 votes |
def name_changed(self, widget, name): """ triggered by one of the spore widgets when the user requests a name change :param widget: the source of the signal :param name: the new name """ node_name = widget.long_name if cmds.objExists(node_name): if re.match('^[A-Za-z0-9_-]*$', name) and not name[0].isdigit(): # transform = cmds.listRelatives(node_name, p=True, f=True)[0] instancer = node_utils.get_instancer(node_name) cmds.rename(instancer, '{}Instancer'.format(name)) cmds.rename(node_name, '{}Shape'.format(name)) # cmds.rename(transform, name) else: self.io.set_message('Invalid Name: Use only A-Z, a-z, 0-9, -, _', 2) return self.refresh_spore()
Example #6
Source File: orientjoints.py From cmt with MIT License | 6 votes |
def orient_to_world(joints): """Orients the given joints with the world. @param joints: Joints to orient. """ for joint in joints: children = _unparent_children(joint) parent = cmds.listRelatives(joint, parent=True, path=True) orig_joint = joint.split("|")[-1] if parent: joint = cmds.parent(joint, world=True)[0] cmds.joint(joint, e=True, oj="none", zso=True) if parent: joint = cmds.parent(joint, parent)[0] joint = cmds.rename(joint, orig_joint) _reparent_children(joint, children) if joints: cmds.select(joints)
Example #7
Source File: go.py From SISideBar with MIT License | 6 votes |
def maya_import(): temp = __name__.split('.')#nameは自分自身のモジュール名。splitでピリオドごとに3分割。 folderPath = os.path.join(os.getenv('MAYA_APP_DIR'),'Scripting_Files','go') if not os.path.exists(folderPath): os.makedirs(os.path.dirname(folderPath+'\\')) # 末尾\\が必要なので注意 #print folderPath files = os.listdir(folderPath) if files is not None: for file in files: print file nameSpace = file.replace('.ma', '') cmds.file(folderPath+'\\'+file, i=True, typ="mayaAscii", iv=True, mnc=False, options="v=0;", pr=True) #重複マテリアルにファイル名が頭に付与されてしまうのを修正 allMat = cmds.ls(mat=True) fileName = file.split('.')[0] for mat in allMat: if mat.startswith(fileName+'_'): cmds.rename(mat, mat.replace(fileName+'_', '')) cmds.inViewMessage( amg='<hl>Go Maya</hl> : Imoprt objects', pos='midCenterTop', fade=True, ta=0.75, a=0.5) else: cmds.inViewMessage( amg='<hl>Go Maya</hl> : There is no exported object', pos='midCenterTop', fade=True, ta=0.75, a=0.5)
Example #8
Source File: mayascene.py From cross3d with MIT License | 6 votes |
def _createNativeCamera(self, name='Camera', type='Standard', target=None, rotationOrder=None): """ Implements the AbstractScene._createNativeCamera method to return a new Studiomax camera :param name: <str> :return: <variant> nativeCamera || None """ if type == 'V-Ray': cross3d.logger.debug('V-Ray cameras are not supported currently') return None else: if target != None: cross3d.logger.debug('Target not supported currently.') tform, shape = cmds.camera() # Set the rotation order for the camera. if rotationOrder == None: rotationOrder = cross3d.SceneCamera.defaultRotationOrder() cross3d.SceneObject._setNativeRotationOrder(tform, rotationOrder) nativeCamera = cross3d.SceneWrapper._asMOBject(shape) cmds.rename(tform, name) return nativeCamera
Example #9
Source File: mayasceneobject.py From cross3d with MIT License | 6 votes |
def setNamespace(self, namespace): # I am not re-using the name method on purpose. name = self._mObjName(self._nativeTransform, False) displayName = name.split(':')[-1] if not namespace: cmds.rename(self.path(), self.displayName()) else: if not cmds.namespace(exists=namespace): cmds.namespace(add=namespace) cmds.rename(self.path(), ':'.join([namespace, displayName])) return True
Example #10
Source File: uExport.py From uExport with zlib License | 6 votes |
def convertSkelSettingsToNN(delete=1): orig = 'SkeletonSettings_Cache' if cmds.objExists(orig): if cmds.nodeType(orig) == 'unknown': new = cmds.createNode('network') for att in cmds.listAttr(orig): if not cmds.attributeQuery(att, node=new, exists=1): typ = cmds.attributeQuery(att, node=orig, at=1) if typ == 'typed': cmds.addAttr(new, longName=att, dt='string') if cmds.getAttr(orig + '.' + att): cmds.setAttr(new + '.' + att, cmds.getAttr(orig + '.' + att), type='string') elif typ == 'enum': cmds.addAttr(new, longName=att, at='enum', enumName=cmds.attributeQuery(att, node=orig, listEnum=1)[0]) cmds.delete(orig) cmds.rename(new, 'SkeletonSettings_Cache')
Example #11
Source File: mayascenewrapper.py From cross3d with MIT License | 5 votes |
def setNamespace(self, namespace): # I am not re-using the name method on purpose. name = self._mObjName(self._nativePointer, False) displayName = name.split(':')[-1] if not namespace: cmds.rename(self.path(), self.displayName()) else: if not cmds.namespace(exists=namespace): cmds.namespace(add=namespace) cmds.rename(self.path(), ':'.join([namespace, displayName])) return True
Example #12
Source File: plotBendHV.py From maya_rotationDriver with MIT License | 5 votes |
def _createCurve(name, angle, cvs, parent): node = cmds.curve(d=1, p=cvs) cmds.parent(node, parent) name += '_n%03d' if angle < 0. else '_p%03d' cmds.rename(node, name % abs(round(angle))) return node
Example #13
Source File: plotBendHV.py From maya_rotationDriver with MIT License | 5 votes |
def _createInsideSphere(name, radius, parent): node = cmds.sphere(r=radius * .999)[0] cmds.parent(node, parent) cmds.rename(node, name) return node
Example #14
Source File: control.py From cmt with MIT License | 5 votes |
def create(self, transform=None, as_controller=True): """Create a curve. :param transform: Name of the transform to create the curve shape under. If the transform does not exist, it will be created. :param as_controller: True to mark the curve transform as a controller. :return: The transform of the new curve shapes. """ transform = transform or self.transform if not cmds.objExists(transform): transform = cmds.createNode("transform", name=transform) periodic = self.form == 2 points = self._get_transformed_points() points = points + points[: self.degree] if periodic else points curve = cmds.curve(degree=self.degree, p=points, per=periodic, k=self.knots) shape = shortcuts.get_shape(curve) if self.color is not None: cmds.setAttr("{}.overrideEnabled".format(shape), True) if isinstance(self.color, int): cmds.setAttr("{}.overrideColor".format(shape), self.color) else: cmds.setAttr("{}.overrideRGBColors".format(shape), True) cmds.setAttr("{}.overrideColorRGB".format(shape), *self.color) cmds.parent(shape, transform, r=True, s=True) shape = cmds.rename(shape, "{}Shape".format(transform)) cmds.delete(curve) if as_controller: cmds.controller(transform) logger.info("Created curve {} for transform {}".format(shape, transform)) return transform
Example #15
Source File: maya_PasteFromExternal.py From OD_CopyPasteExternal with Apache License 2.0 | 5 votes |
def fn_createObject_openMaya(): global importedObj cmds.select( all = True, hierarchy = True) currentObjs = cmds.ls(selection = True ) newMesh = om.MFnMesh() mergeVertices = True pointTolerance = 0.0001 for p in range(0, len(importedObj.polys), 1): polylist = [] vCount = len(importedObj.polys[p]) polylist = om.MPointArray() polylist.setLength(vCount) for i in range(vCount): polylist.set(importedObj.omVertices[int(importedObj.polys[p][i])], i) newMesh.addPolygon(polylist, mergeVertices, pointTolerance) if len(importedObj.weightMap) > 0: for v in range(0, importedObj.vertexCount , 1): c = importedObj.weightMap[v] vColor = om.MColor(c,c,c,c ) newMesh.setVertexColor(vColor,v) newMesh.updateSurface() cmds.select( all = True, hierarchy = True) cmds.select(currentObjs, deselect = True) newObjs = cmds.ls(selection = True, transforms = True ) cmds.select(newObjs, replace = True) cmds.sets( newObjs, e=True,forceElement='initialShadingGroup') cmds.rename (newObjs, importObjectName)
Example #16
Source File: mayaGeom.py From tutorials with MIT License | 5 votes |
def setName(self, name): if name: self.name = cmds.rename(self.name, name)
Example #17
Source File: mayascenewrapper.py From cross3d with MIT License | 5 votes |
def setDisplayName(self, name): """ Set the display name for this wrapper instance to the inputed name - if not reimplemented, then it will set the object's actual name to the inputed name """ cmds.rename(self.path(), ':'.join([self.namespace(), name]))
Example #18
Source File: mayascene.py From cross3d with MIT License | 5 votes |
def _createNativeModel(self, name='Model', nativeObjects=[], referenced=False): name = 'Model' if not name else name # Create a "model" namespace and add the locator to it # TODO: Make this a context currentNamespace = cmds.namespaceInfo(currentNamespace=True) namespace = cmds.namespace(addNamespace=name) cmds.namespace(setNamespace=namespace) # Create the transform node then the shape node so the transform is properly named parent = cmds.createNode('transform', name='Model') #name = cmds.createNode('locator', name='{}Shape'.format(name), parent=parent) output = cross3d.SceneWrapper._asMOBject(parent) userProps = cross3d.UserProps(output) userProps['model'] = True if referenced: userProps['referenced'] = referenced # Create the Active_Resolution enum if it doesn't exist # cmds.addAttr(name, longName="Active_Resolution", attributeType="enum", enumName="Offloaded:") # userProps['Resolutions'] = OrderedDict(Offloaded='') cmds.namespace(setNamespace=currentNamespace) # Add each of nativeObjects to the model namespace if nativeObjects: for nativeObject in nativeObjects: nativeObject = cross3d.SceneWrapper._getTransformNode(nativeObject) objName = cross3d.SceneWrapper._mObjName(nativeObject) # cmds.parent(objName, cross3d.SceneWrapper._mObjName(nativeParent)) nameInfo = cross3d.SceneWrapper._namespace(nativeObject) newName = '{namespace}:{name}'.format(namespace=namespace, name=nameInfo['name']) cmds.rename(objName, newName) nativeObjects.append(output) return output
Example #19
Source File: texture.py From SISideBar with MIT License | 5 votes |
def rename_textures(delUnuseTex=True): attrPort = [ '.outColor', '.outAlpha', '.outTransparency' ] textures = cmds.ls(tex=True) #テクスチャを一括リネーム、未使用のものは削除 for tex in textures: deleteFlag = True#削除フラグ for portName in attrPort: #接続されたノードを返す。pフラグでアトリビュート名を合わせて取得。 try: connectItems = cmds.listConnections(tex+portName, p=True) except: print 'Get Attribute Error : '+texA+'.'+portName continue #接続を取得した変数がnoneTypeでなければ(接続があれば) if connectItems is not None: #if not isinstance(connectItems,type(None)): deleteFlag = False#削除フラグをFalseに if deleteFlag and delUnuseTex:#削除フラグがTrueなら cmds.delete(tex)#テクスチャ削除 continue#以降のリネーム処理を行わずfor文の最初に戻る try: sourceName = cmds.getAttr(tex+'.fileTextureName') fileExpName = sourceName.split('/')[-1] fileExpName = fileExpName.split('\\')[-1] fileName = fileExpName.split('.')[0] cmds.rename(tex,fileName) except: print 'Rename Error : '+tex continue
Example #20
Source File: dpControls.py From dpAutoRigSystem with GNU General Public License v2.0 | 5 votes |
def cvCharacter(self, ctrlType, ctrlName, r=1, d=1, dir="+Y", rot=(0, 0, 0), *args): """ Create and return a curve to be used as a control. """ # get radius by checking linear unit r = self.dpCheckLinearUnit(r) curve = self.cvControl(ctrlType, ctrlName, r, d, dir, rot) # edit a minime curve: cmds.addAttr(curve, longName="rigScale", attributeType='float', defaultValue=1, keyable=True) cmds.addAttr(curve, longName="rigScaleMultiplier", attributeType='float', defaultValue=1, keyable=False) # create Option_Ctrl Text: try: optCtrlTxt = cmds.group(name="Option_Ctrl_Txt", empty=True) try: cvText = cmds.textCurves(name="Option_Ctrl_Txt_TEMP_Grp", font="Source Sans Pro", text="Option Ctrl", constructionHistory=False)[0] except: cvText = cmds.textCurves(name="Option_Ctrl_Txt_TEMP_Grp", font="Arial", text="Option Ctrl", constructionHistory=False)[0] txtShapeList = cmds.listRelatives(cvText, allDescendents=True, type='nurbsCurve') if txtShapeList: for s, shape in enumerate(txtShapeList): # store CV world position curveCVList = cmds.getAttr(shape+'.cp', multiIndices=True) vtxWorldPosition = [] for i in curveCVList : cvPointPosition = cmds.xform(shape+'.cp['+str(i)+']', query=True, translation=True, worldSpace=True) vtxWorldPosition.append(cvPointPosition) # parent the shapeNode : cmds.parent(shape, optCtrlTxt, r=True, s=True) # restore the shape world position for i in curveCVList: cmds.xform(shape+'.cp['+str(i)+']', a=True, worldSpace=True, t=vtxWorldPosition[i]) cmds.rename(shape, optCtrlTxt+"Shape"+str(s)) cmds.delete(cvText) cmds.parent(optCtrlTxt, curve) cmds.setAttr(optCtrlTxt+".template", 1) cmds.setAttr(optCtrlTxt+".tx", -0.72*r) cmds.setAttr(optCtrlTxt+".ty", 1.1*r) except: # it will pass if we don't able to find the font to create the text pass return curve
Example #21
Source File: dpControls.py From dpAutoRigSystem with GNU General Public License v2.0 | 5 votes |
def cvJointLoc(self, ctrlName, r=0.3, d=1, rot=(0, 0, 0), guide=True, *args): """Create and return a cvJointLocator curve to be usually used in the guideSystem and the clusterHandle to shapeSize. """ # create locator curve: cvLoc = self.cvLocator(ctrlName+"_CvLoc", r, d) # create arrow curves: cvArrow1 = cmds.curve(n=ctrlName+"_CvArrow1", d=3, p=[(-0.1*r, 0.9*r, 0.2*r), (-0.1*r, 0.9*r, 0.23*r), (-0.1*r, 0.9*r, 0.27*r), (-0.1*r, 0.9*r, 0.29*r), (-0.1*r, 0.9*r, 0.3*r), (-0.372*r, 0.9*r, 0.24*r), (-0.45*r, 0.9*r, -0.13*r), (-0.18*r, 0.9*r, -0.345*r), (-0.17*r, 0.9*r, -0.31*r), (-0.26*r, 0.9*r, -0.41*r), (-0.21*r, 0.9*r, -0.41*r), (-0.05*r, 0.9*r, -0.4*r), (0, 0.9*r, -0.4*r), (-0.029*r, 0.9*r, -0.33*r), (-0.048*r, 0.9*r, -0.22*r), (-0.055*r, 0.9*r, -0.16*r), (-0.15*r, 0.9*r, -0.272*r), (-0.12*r, 0.9*r, -0.27*r), (-0.35*r, 0.9*r, -0.1*r), (-0.29*r, 0.9*r, 0.15*r), (-0.16*r, 0.9*r, 0.21*r), (-0.1*r, 0.9*r, 0.2*r)] ) cvArrow2 = cmds.curve(n=ctrlName+"_CvArrow2", d=3, p=[(0.1*r, 0.9*r, -0.2*r), (0.1*r, 0.9*r, -0.23*r), (0.1*r, 0.9*r, -0.27*r), (0.1*r, 0.9*r, -0.29*r), (0.1*r, 0.9*r, -0.3*r), (0.372*r, 0.9*r, -0.24*r), (0.45*r, 0.9*r, 0.13*r), (0.18*r, 0.9*r, 0.345*r), (0.17*r, 0.9*r, 0.31*r), (0.26*r, 0.9*r, 0.41*r), (0.21*r, 0.9*r, 0.41*r), (0.05*r, 0.9*r, 0.4*r), (0, 0.9*r, 0.4*r), (0.029*r, 0.9*r, 0.33*r), (0.048*r, 0.9*r, 0.22*r), (0.055*r, 0.9*r, 0.16*r), (0.15*r, 0.9*r, 0.272*r), (0.12*r, 0.9*r, 0.27*r), (0.35*r, 0.9*r, 0.1*r), (0.29*r, 0.9*r, -0.15*r), (0.16*r, 0.9*r, -0.21*r), (0.1*r, 0.9*r, -0.2*r)] ) cvArrow3 = cmds.curve(n=ctrlName+"_CvArrow3", d=3, p=[(-0.1*r, -0.9*r, 0.2*r), (-0.1*r, -0.9*r, 0.23*r), (-0.1*r, -0.9*r, 0.27*r), (-0.1*r, -0.9*r, 0.29*r), (-0.1*r, -0.9*r, 0.3*r), (-0.372*r, -0.9*r, 0.24*r), (-0.45*r, -0.9*r, -0.13*r), (-0.18*r, -0.9*r, -0.345*r), (-0.17*r, -0.9*r, -0.31*r), (-0.26*r, -0.9*r, -0.41*r), (-0.21*r, -0.9*r, -0.41*r), (-0.05*r, -0.9*r, -0.4*r), (0, -0.9*r, -0.4*r), (-0.029*r, -0.9*r, -0.33*r), (-0.048*r, -0.9*r, -0.22*r), (-0.055*r, -0.9*r, -0.16*r), (-0.15*r, -0.9*r, -0.272*r), (-0.12*r, -0.9*r, -0.27*r), (-0.35*r, -0.9*r, -0.1*r), (-0.29*r, -0.9*r, 0.15*r), (-0.16*r, -0.9*r, 0.21*r), (-0.1*r, -0.9*r, 0.2*r)] ) cvArrow4 = cmds.curve(n=ctrlName+"_CvArrow4", d=3, p=[(0.1*r, -0.9*r, -0.2*r), (0.1*r, -0.9*r, -0.23*r), (0.1*r, -0.9*r, -0.27*r), (0.1*r, -0.9*r, -0.29*r), (0.1*r, -0.9*r, -0.3*r), (0.372*r, -0.9*r, -0.24*r), (0.45*r, -0.9*r, 0.13*r), (0.18*r, -0.9*r, 0.345*r), (0.17*r, -0.9*r, 0.31*r), (0.26*r, -0.9*r, 0.41*r), (0.21*r, -0.9*r, 0.41*r), (0.05*r, -0.9*r, 0.4*r), (0, -0.9*r, 0.4*r), (0.029*r, -0.9*r, 0.33*r), (0.048*r, -0.9*r, 0.22*r), (0.055*r, -0.9*r, 0.16*r), (0.15*r, -0.9*r, 0.272*r), (0.12*r, -0.9*r, 0.27*r), (0.35*r, -0.9*r, 0.1*r), (0.29*r, -0.9*r, -0.15*r), (0.16*r, -0.9*r, -0.21*r), (0.1*r, -0.9*r, -0.2*r)] ) cvArrow5 = cmds.curve(n=ctrlName+"_CvArrow5", d=1, p=[(0, 0, 1.2*r), (0.09*r, 0, 1*r), (-0.09*r, 0, 1*r), (0, 0, 1.2*r)] ) cvArrow6 = cmds.curve(n=ctrlName+"_CvArrow6", d=1, p=[(0, 0, 1.2*r), (0, 0.09*r, 1*r), (0, -0.09*r, 1*r), (0, 0, 1.2*r)] ) # rename curveShape: locArrowList = [cvLoc, cvArrow1, cvArrow2, cvArrow3, cvArrow4, cvArrow5, cvArrow6] self.renameShape(locArrowList) # create ball curve: cvTemplateBall = self.cvControl("Ball", ctrlName+"_CvBall", r=0.7*r, d=3) # parent shapes to transform: locCtrl = cmds.group(name=ctrlName, empty=True) ballChildrenList = cmds.listRelatives(cvTemplateBall, shapes=True, children=True) for ballChildren in ballChildrenList: cmds.setAttr(ballChildren+".template", 1) self.transferShape(True, False, cvTemplateBall, [locCtrl]) for transform in locArrowList: self.transferShape(True, False, transform, [locCtrl]) # set rotation direction: cmds.setAttr(locCtrl+".rotateX", rot[0]) cmds.setAttr(locCtrl+".rotateY", rot[1]) cmds.setAttr(locCtrl+".rotateZ", rot[2]) cmds.makeIdentity(locCtrl, rotate=True, apply=True) # create an attribute to be used as guide by module: cmds.addAttr(locCtrl, longName="nJoint", attributeType='long') cmds.setAttr(locCtrl+".nJoint", 1) # colorize curveShapes: self.colorShape([locCtrl], 'blue') # shapeSize setup: shapeSizeCluster = self.shapeSizeSetup(locCtrl) cmds.select(clear=True) return [locCtrl, shapeSizeCluster]
Example #22
Source File: channelBox.py From tutorials with MIT License | 4 votes |
def itemChanged(self, item): """ itemChanged(QTableWidgetItem item) Slot called when an item in the attributes table is changed. Performs validation of the value by checking the recorded types. Recursively triggers setting the same value on all other selected items if a multiple selection was made. """ row = item.row() col = item.column() # we are updating the node name if row == 0: newname = cmds.rename(self._currentNode, str(item.text())) self.showAttributes(newname) return # we are updating an attribute value field elif col == 1: txt = str(item.text()) attrType = type(item.attrVal) # try to convert the entered value to the type we had # recorded for this attribute. If it fails to convert, # then it is an invalid type. try: if attrType is bool: attrVal = txt.lower() in ('1', 'on', 'yes', 'y', 'true') else: attrVal = attrType(txt) except ValueError: cmds.warning("'%s' is not a valid attribute type. Expected %s" % (txt, attrType)) with noSignals(self.table): item.setAttrValue(item.attrVal) return # set the attribute value on the actual node cmds.setAttr(item.attrName, attrVal) # let our item reformat the text value with noSignals(self.table): item.setAttrValue(attrVal) # Also update every other selected item with the same # value. This will trigger itemChanged signals so we # set a flag for the first item. Subsequent calls won't # run this block again. if not self._is_updating: self._is_updating = True for i in self.table.selectedItems(): if i.column() != 1: continue if i is item: continue i.setAttrValue(attrVal) self._is_updating = False
Example #23
Source File: sqStickyLipsSetup.py From dpAutoRigSystem with GNU General Public License v2.0 | 4 votes |
def sqGenerateCurves(self, *args): self.edgeList = cmds.ls(selection=True, flatten=True) if not self.edgeList == None and not self.edgeList == [] and not self.edgeList == "": self.baseCurve = cmds.polyToCurve(name="baseCurve", form=2, degree=1)[0] cmds.select(self.baseCurve+".ep[*]") cmds.insertKnotCurve(cmds.ls(selection=True, flatten=True), constructionHistory=True, curveOnSurface=True, numberOfKnots=1, addKnots=False, insertBetween=True, replaceOriginal=True) pointListA, pointListB, sideA, sideB = self.sqGetPointLists() toDeleteList = [] p = 2 for k in range((sideA+2), (sideB-1)): if p%2 == 0: toDeleteList.append(self.baseCurve+".cv["+str(k)+"]") toDeleteList.append(self.baseCurve+".cv["+str(k+len(pointListA)-1)+"]") p = p+1 q = 2 m = sideA-2 if m >= 0: while m >= 0: if not m == sideA and not m == sideB: if q%2 == 0: toDeleteList.append(self.baseCurve+".cv["+str(m)+"]") m = m-1 q = q+1 cmds.delete(toDeleteList) cmds.insertKnotCurve([self.baseCurve+".u["+str(len(pointListA)-1)+"]", self.baseCurve+".ep["+str(len(pointListA)-1)+"]"], constructionHistory=True, curveOnSurface=True, numberOfKnots=1, addKnots=False, insertBetween=True, replaceOriginal=True) pointListA, pointListB, sideA, sideB = self.sqGetPointLists() posListA, posListB = [], [] for i in range(0, len(pointListA)-1): posListA.append(cmds.xform(pointListA[i], query=True, worldSpace=True, translation=True)) posListB.append(cmds.xform(pointListB[i], query=True, worldSpace=True, translation=True)) self.mainCurveA = cmds.curve(name="StickyLips_Main_A_Crv", degree=1, point=posListA) self.mainCurveB = cmds.curve(name="StickyLips_Main_B_Crv", degree=1, point=posListB) cmds.rename(cmds.listRelatives(self.mainCurveA, children=True, shapes=True)[0], self.mainCurveA+"Shape") cmds.rename(cmds.listRelatives(self.mainCurveB, children=True, shapes=True)[0], self.mainCurveB+"Shape") cmds.select(self.mainCurveA+".cv[*]") self.curveLenght = len(cmds.ls(selection=True, flatten=True)) cmds.select(clear=True) self.sqCheckCurveDirection(self.mainCurveA) self.sqCheckCurveDirection(self.mainCurveB) self.baseCurveA = cmds.duplicate(self.mainCurveA, name=self.mainCurveA.replace("_Main_", "_Base_"))[0] self.baseCurveB = cmds.duplicate(self.mainCurveB, name=self.mainCurveB.replace("_Main_", "_Base_"))[0] cmds.delete(self.baseCurve) self.maxIter = len(posListA) cmds.group(self.mainCurveA, self.mainCurveB, self.baseCurveA, self.baseCurveB, name="StickyLips_StaticData_Grp") else: mel.eval("warning \"Please, select an closed edgeLoop.\";")
Example #24
Source File: skeleton.py From cmt with MIT License | 4 votes |
def insert_joints(joints=None, joint_count=1): """Inserts joints evenly spaced along a bone. :param joints: List of joints to insert child joints to. :param joint_count: Number of joints to insert. :return: List of joints created. """ if joints is None: joints = cmds.ls(sl=True, type="joint") if not joints: raise RuntimeError("No joint selected") if joint_count < 1: raise RuntimeError("Must insert at least 1 joint.") result = [] for joint in joints: children = cmds.listRelatives(joint, children=True, type="joint") if not children: raise RuntimeError( "Joint {} needs a child in order to insert joints".format(joint) ) name = joint end_joint = children[0] d = distance(joint, children[0]) increment = d / (joint_count + 1) direction = vector_to(joint, end_joint) direction.normalize() direction *= increment for i in range(joint_count): position = cmds.xform(joint, query=True, worldSpace=True, translation=True) position = OpenMaya.MPoint(position[0], position[1], position[2]) position += direction joint = cmds.insertJoint(joint) joint = cmds.rename(joint, ("{}_seg#".format(name))) cmds.joint( joint, edit=True, component=True, position=(position.x, position.y, position.z), ) result.append(joint) return result
Example #25
Source File: cluster.py From maya-spline-ik with GNU General Public License v3.0 | 4 votes |
def clusterCurve(curve, name): """ Create a cluster on each cv of a curve. :param str curve: :param str name: :return: List of created clusters :rtype: list of strings """ clusters = [] # get num cvs on curve num = numCVs(curve) # create clusters for i in range(num): # create cluster clusterShape, clusterTransform = cmds.cluster( "{0}.cv[{1}]".format( curve, i ) ) # rename shape and transform clusterShape = cmds.rename( clusterShape, "{0}_clusterShape_{1:03d}".format(name, i+1) ) clusterTransform = cmds.rename( clusterTransform, "{0}_cluster_{1:03d}".format(name, i+1) ) # set and lock visibility cmds.setAttr("{0}.visibility".format(clusterTransform), 0) cmds.setAttr("{0}.visibility".format(clusterTransform), lock=True) # store transform clusters.append(clusterTransform) return clusters
Example #26
Source File: jcRibbon.py From dpAutoRigSystem with GNU General Public License v2.0 | 4 votes |
def createFollicles(self, rib, num, pad=0.5, name='xxxx', horizontal=False, side=0, jointLabelAdd=0, jointLabelName="RibbonName", *args): """ Create follicles to be used by the Ribbon system. Returns a list with joints and follicles created. """ #define variables jnts = [] fols = [] #create joints and follicles based in the choose options from user if horizontal: #calcule the position of the first follicle passo = (1/float(num))/2.0; for i in range(num): #create the follicle and do correct connections to link it to the folShape = cmds.createNode('follicle', name=name+'_%02d_FolShape'%i) folTrans = cmds.rename(cmds.listRelatives(folShape, p=1)[0], name+'_%02d_Fol'%i) fols.append(folTrans) cmds.connectAttr(rib+'.worldMatrix[0]', folShape+'.inputWorldMatrix') cmds.connectAttr(rib+'.local', folShape+'.inputSurface') cmds.connectAttr(folShape+'.outTranslate', folTrans+'.translate') cmds.connectAttr(folShape+'.outRotate', folTrans+'.rotate') cmds.setAttr(folShape+'.parameterU', passo) cmds.setAttr(folShape+'.parameterV', 0.5) #create the joint in the follicle cmds.select(cl=True) jnts.append(cmds.joint(n=name+'_%02d_Jnt'%i)) cmds.setAttr(jnts[i]+'.jointOrient', 0, 0, 0) utils.setJointLabel(name+'_%02d_Jnt'%i, side+jointLabelAdd, 18, jointLabelName+'_%02d'%i) cmds.select(cl=True) #calculate the position of the first follicle passo+=(1/float(num)) results = [jnts, fols] #return the joints and follicles created else: #calculate the position of the first follicle passo = (1/float(num))/2.0; for i in range(num): #create the follicle and do correct connections in order to link it to the ribbon folShape = cmds.createNode('follicle', name=name+'_%02d_FolShape'%i) folTrans = cmds.rename(cmds.listRelatives(folShape, p=1)[0], name+'_%02d_Fol'%i) fols.append(folTrans) cmds.connectAttr(rib+'.worldMatrix[0]', folShape+'.inputWorldMatrix') cmds.connectAttr(rib+'.local', folShape+'.inputSurface') cmds.connectAttr(folShape+'.outTranslate', folTrans+'.translate') cmds.connectAttr(folShape+'.outRotate', folTrans+'.rotate') cmds.setAttr(folShape+'.parameterU', 0.5) cmds.setAttr(folShape+'.parameterV', passo) #create the joint in the follicle cmds.select(cl=True) jnts.append(cmds.joint(n=name+'_%02d_Jnt'%i)) cmds.setAttr(jnts[i]+'.jointOrient', 0, 0, 0) utils.setJointLabel(name+'_%02d_Jnt'%i, side+jointLabelAdd, 18, jointLabelName+'_%02d'%i) cmds.select(cl=True) #calculate the first follicle position passo+=(1/float(num)) results = [jnts, fols] #return the created joints and follicles cmds.parent(fols, rib) return results
Example #27
Source File: ml_parentShape.py From ml_tools with MIT License | 4 votes |
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
Example #28
Source File: ml_stopwatch.py From ml_tools with MIT License | 4 votes |
def addMarksToScene(marks): ''' This is temp and will possibly be rolled into future releases. ''' start,end = utl.frameRange() camera = utl.getCurrentCamera() camShape = mc.listRelatives(camera, shapes=True)[0] aov = mc.getAttr(camShape+'.horizontalFilmAperture') name = 'ml_stopwatch_' numStopwatches = len(mc.ls(name+'*', type='locator')) top = mc.spaceLocator(name=name+'#') ename = ':'.join([str(x) for x in marks]) mc.addAttr(top, longName='keyTimes', at='enum', enumName=ename, keyable=True) markRange = float(marks[-1]-marks[0]) viewWidth = aov*2 viewHeight = -0.4*aov+(numStopwatches*aov*0.08) depth = 5 for mark in marks[1:-1]: ann = mc.annotate(top, text=str(mark)) mc.setAttr(ann+'.displayArrow', 0) #parent annT = mc.parent(mc.listRelatives(ann, parent=True, path=True), top)[0] annT = mc.rename(annT, 'mark_'+str(round(mark))) ann = mc.listRelatives(annT, shapes=True, path=True)[0] #set the position normalX = float(mark-marks[0])/markRange-0.5 mc.setAttr(annT+'.translateX', viewWidth*normalX*2) mc.setAttr(annT+'.translateY', viewHeight) mc.setAttr(annT+'.translateZ', -depth) #keyframe for color mc.setAttr(ann+'.overrideEnabled', 1) mc.setKeyframe(ann, attribute='overrideColor', value=17, time=(int(marks[0]-1),int(mark+1))) mc.setKeyframe(ann, attribute='overrideColor', value=13, time=(int(mark),)) mc.keyTangent(ann+'.overrideColor', ott='step') mc.select(clear=True) mc.parentConstraint(camera, top)
Example #29
Source File: dpBaseClass.py From dpAutoRigSystem with GNU General Public License v2.0 | 4 votes |
def createGuide(self, *args): """ Create the elements to Guide module in the scene, like controls, etc... """ # GUIDE: utils.useDefaultRenderLayer() # create guide base (moduleGrp): guideBaseList = self.ctrls.cvBaseGuide(self.moduleGrp, r=2) self.moduleGrp = guideBaseList[0] self.radiusCtrl = guideBaseList[1] # add attributes to be read when rigging module: baseBooleanAttrList = ['guideBase', 'mirrorEnable', 'displayAnnotation'] for baseBooleanAttr in baseBooleanAttrList: cmds.addAttr(self.moduleGrp, longName=baseBooleanAttr, attributeType='bool') cmds.setAttr(self.moduleGrp+"."+baseBooleanAttr, 1) baseIntegerAttrList = ['guideColor'] for baseIntegerAttr in baseIntegerAttrList: cmds.addAttr(self.moduleGrp, longName=baseIntegerAttr, attributeType='long') baseStringAttrList = ['moduleNamespace', 'customName', 'mirrorAxis', 'mirrorName', 'mirrorNameList', 'hookNode', 'moduleInstanceInfo', 'guideObjectInfo', 'rigType', 'dpARVersion'] for baseStringAttr in baseStringAttrList: cmds.addAttr(self.moduleGrp, longName=baseStringAttr, dataType='string') cmds.setAttr(self.moduleGrp+".mirrorAxis", "off", type='string') cmds.setAttr(self.moduleGrp+".mirrorName", self.langDic[self.langName]['p002_left']+' --> '+self.langDic[self.langName]['p003_right'], type='string') cmds.setAttr(self.moduleGrp+".hookNode", "_Grp", type='string') cmds.setAttr(self.moduleGrp+".moduleInstanceInfo", self, type='string') cmds.setAttr(self.moduleGrp+".guideObjectInfo", self.dpUIinst.guide, type='string') cmds.setAttr(self.moduleGrp+".rigType", self.rigType, type='string') cmds.setAttr(self.moduleGrp+".dpARVersion", self.dpUIinst.dpARVersion, type='string') baseFloatAttrList = ['shapeSize'] for baseFloatAttr in baseFloatAttrList: cmds.addAttr(self.moduleGrp, longName=baseFloatAttr, attributeType='float') cmds.setAttr(self.moduleGrp+".shapeSize", 1) baseIntegerAttrList = ['degree'] for baseIntAttr in baseIntegerAttrList: cmds.addAttr(self.moduleGrp, longName=baseIntAttr, attributeType='short') cmds.setAttr(self.moduleGrp+".degree", self.dpUIinst.degreeOption) # create annotation to this module: self.annotation = cmds.annotate( self.moduleGrp, tx=self.moduleGrp, point=(0,2,0) ) self.annotation = cmds.listRelatives(self.annotation, parent=True)[0] self.annotation = cmds.rename(self.annotation, self.moduleGrp+"_Ant") cmds.parent(self.annotation, self.moduleGrp) cmds.setAttr(self.annotation+'.text', self.moduleGrp[self.moduleGrp.find("__")+2:self.moduleGrp.rfind(":")], type='string') cmds.setAttr(self.annotation+'.template', 1)