我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.xform()。
def add_top_level_ctrl(origCtrl, type, geo, *args): """ creates a new ctrl, orients it to the geo and parent constrains the orig ctrl rig under itself :param origCtrl: the control we're working from :param type: the ctrl type of shape see zbw_rig.createControl for options :param geo: the geo to orient to :param args: :return: topCtrl (the new ctrl), grp (the top ctrl grp freeze grp) """ # THIS IS THE XTRA CTRL LAYER, THIS ORIENTS CTRL AND CONNECTS ORIG CTRL TO THE NEW CTRL origCtrlPos = cmds.xform(origCtrl, q=True, ws=True, rp=True) topCtrl = rig.createControl(name="{0}_moveCtrl".format(origCtrl.rpartition("_")[0]), type=type, axis="z", color="yellow") grp = rig.groupFreeze(topCtrl) cmds.xform(grp, ws=True, t=origCtrlPos) nc = cmds.normalConstraint(geo, grp, worldUpType="vector", upVector=(0, 1, 0)) cmds.delete(nc) pc = cmds.parentConstraint(topCtrl, origCtrl, mo=True) sc = cmds.scaleConstraint(topCtrl, origCtrl, mo=True) return(topCtrl, grp)
def make_position_planar(*args): sel = cmds.ls(sl=True, type='joint') if len(sel) <= 3: raise RuntimeError('Select 3 joints to make a plane and then additional joints to move onto that plane.') a, b, c = [get_position(sel[i]) for i in range(3)] ab = (b - a).normal() ac = (c - a).normal() normal = (ab ^ ac).normal() joints = sel[3:] for joint in joints: children = _unparent_children(joint) p = get_position(joint) pa = a - p dot = pa*normal p = p + (normal*dot) cmds.xform(joint, ws=True, t=(p.x, p.y, p.z)) _reparent_children(joint, children) if sel: cmds.select(sel)
def __init__(self, controls=None, **kwargs): """Constructor :param controls: A list of dictionaries describing the contorls nodes that need to be created. See cmt.rig.control.dump. { 'name': node, 'cvs': cmds.getAttr('{0}.cv[*]'.format(node)), 'degree': cmds.getAttr('{0}.degree'.format(node)), 'form': cmds.getAttr('{0}.form'.format(node)), 'xform': cmds.xform(node, q=True, matrix=True), 'knots': get_knots(node), 'pivot': cmds.xform(node, q=True, rp=True), 'overrideEnabled': cmds.getAttr('{0}.overrideEnabled'.format(node)), 'overrideRGBColors': cmds.getAttr('{0}.overrideRGBColors'.format(node)), 'overrideColorRGB': cmds.getAttr('{0}.overrideColorRGB'.format(node))[0], 'overrideColor': cmds.getAttr('{0}.overrideColor'.format(node)), } """ super(Component, self).__init__(**kwargs) self.controls = controls or [] self.control_list = fields.ListField(name='controls', value=[control['name'] for control in self.controls], help_text='Controls that will be created.', parent=self)
def create_bounding_box(self, meshName="bounding_GEO"): """ Create the bounding box mesh. :param meshName(string): Name of created mesh. Raises: None Returns: (string) Cube Transform """ obbCube = cmds.polyCube(constructionHistory=False, name="obb_GEO")[0] for ind, pnt in enumerate(self.boundPoints): cmds.xform("%s.vtx[%s]" % (obbCube, ind), translation=[pnt.x, pnt.y, pnt.z]) return obbCube
def getLocalValues(obj, *args): """use the matrix(xform) to get world space vals, convert to trans and rots""" # get values # add as key in dict obj_values = [] obj_wRot = cmds.xform(obj, q=True, ws=True, ro=True) obj_wTrans = cmds.xform(obj, q=True, ws=True, t=True) for tval in obj_wTrans: obj_values.append(tval) for rval in obj_wRot: obj_values.append(rval) return obj_values # return (tx, ty, tz, rx, ry, rz) # @zbw_undoable.undoable
def huddleExec(*args): """ from first selection, moves the next selected objects closer or farther from first selection based on slider values (as a percentage) """ factor = cmds.floatSliderGrp(widgets["slider"], q=True, v=True) sel = cmds.ls(sl=True, type="transform") center = sel[0] objs = sel[1:] centerPos = cmds.xform(center, q=True, ws=True, rp=True) centerVec = om.MVector(centerPos[0], centerPos[1], centerPos[2]) for obj in objs: objPos = cmds.xform(obj, ws=True, q=True, rp=True) objVec = om.MVector(objPos[0], objPos[1], objPos[2]) diffVec = objVec-centerVec scaledVec = diffVec * factor newVec = scaledVec + centerVec cmds.xform(obj, ws=True, t=(newVec[0], newVec[1], newVec[2]))
def insertGroupAbove(obj, *args): par = cmds.listRelatives(obj, p=True) grp = cmds.group(em=True, n="{}_Grp".format(obj)) pos = cmds.xform(obj, q=True, ws=True, rp=True) rot = cmds.xform(obj, q=True, ws=True, ro=True) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) cmds.parent(obj, grp) if par: cmds.parent(grp, par[0]) return (grp)
def scale_the_objects(scaleVal, *args): """ does the scaling bits """ sel = cmds.ls(sl=True, type="transform") if sel: for obj in sel: if (rig.isType(obj, "nurbsSurface")) or (rig.isType(obj, "nurbsCurve")): piv = cmds.xform(obj, q=True, ws=True, rp=True) cvs = cmds.select((obj + ".cv[*]")) cmds.scale(scaleVal, scaleVal, scaleVal, cvs, pivot=piv) elif rig.isType(obj, "mesh"): piv = cmds.xform(obj, q=True, ws=True, rp=True) vs = cmds.select((obj + ".vtx[*]")) cmds.scale(scaleVal, scaleVal, scaleVal, vs, pivot=piv) else: cmds.warning("{0} isn't a nurbs or poly object, so it was skipped".format(obj)) # clear and reselect all if sel: cmds.select(cl=True) cmds.select(sel) return (True) return (False)
def move_pivot(end, *args): """ Args: end (int): parameter value (0 or 1 from buttons) the point on curve will return, start or end *args: """ check = False sel = cmds.ls(sl=True, exactType = "transform") if sel: for x in sel: check = rig.isType(x, "nurbsCurve") if check: # get curve info pos = cmds.pointOnCurve(x, parameter = end, position = True) cmds.xform(x, ws=True, piv=pos) else: cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))
def insertGroupAbove(*args): sel = cmds.ls(sl=True) for obj in sel: par = cmds.listRelatives(obj, p=True) grp = cmds.group(em=True, n="{}_Grp".format(obj)) # grp = nameCheck(grp) pos = cmds.xform(obj, q=True, ws=True, rp=True) rot = cmds.xform(obj, q=True, ws=True, ro=True) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) cmds.parent(obj, grp) if par: cmds.parent(grp, par[0])
def addGroupBelow(*args): ############----------fix lots of stuff here, but basic idea works sel = cmds.ls(sl=True) for obj in sel: pos = cmds.xform(obj, ws=True, q=True, rp=True) rot = cmds.xform(obj, ws=True, q=True, ro=True) children = cmds.listRelatives(obj, children=True) grp = cmds.group(em=True, name=obj.replace("Auto", "Manual")) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) cmds.parent(grp, obj) for child in children: cmds.parent(child, grp)
def insertGroupAbove(obj, *args): par = cmds.listRelatives(obj, p=True) grp = cmds.group(em=True, n="{}_Grp".format(obj)) # grp = nameCheck(grp) pos = cmds.xform(obj, q=True, ws=True, rp=True) rot = cmds.xform(obj, q=True, ws=True, ro=True) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) cmds.parent(obj, grp) if par: cmds.parent(grp, par[0]) return(grp)
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_position(node): p = cmds.xform(node, q=True, ws=True, t=True) return OpenMaya.MPoint(p)
def create_arrow(jointName): curve = cmds.curve(name='%s_ForwardDirection' % jointName, degree=1, point=[(-1, 0, 0), (-1, 2, 0), (-2, 2, 0), (0, 4, 0), (2, 2, 0), (1, 2, 0), (1, 0, 0), (-1, 0, 0)]) group = cmds.group() cmds.xform(objectSpace=True, pivots=(0, 0, 0)) jointScale = cmds.jointDisplayScale(query=True) jointRadius = cmds.getAttr('%s.radius' % jointName) jointScale *= jointRadius cmds.xform(scale=(jointScale, jointScale, jointScale)) return group
def rotate_components(rx, ry, rz, nodes=None): """Rotate the given nodes' components the given number of degrees about each axis. :param rx: Degrees around x. :param ry: Degrees around y. :param rz: Degrees around z. :param nodes: Optional list of curves. """ if nodes is None: nodes = cmds.ls(sl=True) or [] for node in nodes: pivot = cmds.xform(node, q=True, rp=True, ws=True) cmds.rotate(rx, ry, rz, '{0}.cv[*]'.format(node), r=True, p=pivot, os=True, fo=True)
def dump(curves=None, stack=False): """Get a data dictionary representing all the given curves. :param curves: Optional list of curves. :return: A json serializable list of dictionaries containing the data required to recreate the curves. """ if curves is None: curves = cmds.ls(sl=True) or [] data = [] for node in curves: shape = shortcuts.get_shape(node) if cmds.nodeType(shape) == 'nurbsCurve': control = { 'name': node, 'cvs': cmds.getAttr('{0}.cv[*]'.format(node)), 'degree': cmds.getAttr('{0}.degree'.format(node)), 'form': cmds.getAttr('{0}.form'.format(node)), 'xform': cmds.xform(node, q=True, ws=True, matrix=True), 'knots': get_knots(node), 'pivot': cmds.xform(node, q=True, rp=True), 'overrideEnabled': cmds.getAttr('{0}.overrideEnabled'.format(node)), 'overrideRGBColors': cmds.getAttr('{0}.overrideRGBColors'.format(node)), 'overrideColorRGB': cmds.getAttr('{0}.overrideColorRGB'.format(node))[0], 'overrideColor': cmds.getAttr('{0}.overrideColor'.format(node)), } if stack: control['stack'] = get_stack_count(node) control['parent'] = get_stack_parent(node) data.append(control) if curves: cmds.select(curves) return data
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 align_to_curve(xforms, curve): curve_fn = to_curve_fn(curve) num_xforms = len(xforms) param_step = curve_fn.numSpans / float(num_xforms - 1) for i, xform in enumerate(xforms): param = i * param_step normal = curve_fn.normal(param, om.MSpace.kWorld) tangent = -curve_fn.tangent(param, om.MSpace.kWorld) position = curve_fn.getPointAtParam(param, om.MSpace.kWorld) matrix = build_matrix(normal, tangent, position) cmds.xform(xform, ws=True, matrix=matrix)
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 dm2skin_getVertexPositionsOverRange(mesh, startFrame=0, endFrame=1): """Gets a list of lists of vertex positions for the given mesh. One list for each frame between startFrame and endFrame.""" numVerts = cmds.polyEvaluate(mesh, v=True) resultList = [] for i in range(startFrame, endFrame + 1): tempList = [] cmds.currentTime(i) for j in range(0, numVerts): tempPos = cmds.xform(mesh + '.vtx[' + str(j) + ']', q=True, ws=True, t=True) tempList.append(np.array([tempPos[0], tempPos[1], tempPos[2]])) resultList.append(tempList) return resultList
def dm2skin_getVertexLocationList(mesh, frame=0): """Gets a list of vertex locations on the given frame.""" numVerts = cmds.polyEvaluate(mesh, v=True) resultList = [] cmds.currentTime(frame) for v in range(0, numVerts): pos = cmds.xform(mesh + '.vtx[' + str(v) + ']', q=True, ws=True, t=True) resultList.append(np.array([pos[0], pos[1], pos[2], 1.0])) return resultList
def dm2skin_getNeighbouringJoints(joint, vertexString=None, cluster=None, influences=3): """This gets a list of nearby joints in the skin cluster to joint up to the number of influences. These will be the ones we use in our minimization later""" if not cmds.objExists(joint): return False if influences < 3: return False if not cluster: return False clusterJoints = cmds.skinCluster(cluster, q=True, inf=True) pos1 = cmds.xform(vertexString, q=True, ws=True, t=True) parentJoint = cmds.listRelatives(joint, parent=True) subtract = 1 # add the main joint resultList = [joint] # i've found it works best to always include the parent if parentJoint and parentJoint in clusterJoints: resultList.insert(0, parentJoint[0]) subtract = 2 # for the rest of the available influences get a list of nearby joints in space measureList = [] for measureJnt in clusterJoints: if measureJnt not in resultList: jntPos2 = cmds.xform(measureJnt, q=True, ws=True, t=True) #this just gets the length of the vector between the two joints dist = math.sqrt(reduce(lambda x, y: x + y, [math.pow(jntPos2[i] - pos1[i], 2) for i in range(len(pos1))])) measureList.append((measureJnt, dist)) # sort the list in ascending order so we get the closest joints first measureList.sort(key=lambda dist: dist[1]) ascendingList = [entry[0] for entry in measureList[0:influences - subtract]] return resultList + ascendingList
def zbw_FK2IKSnap(*args): """ select FK wrist joint(or control), fk elbow joint (or ctrl), FK shoulder joint (or ctrl), IK wrist ctl and IK pole vector in that order """ sel = cmds.ls(sl=True) fkEndC = cmds.listConnections((sel[0]+".fkEndCtrl")) fkMidC = cmds.listConnections((sel[0]+".fkMidCtrl")) fkTopC = cmds.listConnections((sel[0]+".fkTopCtrl")) ikTopJ = cmds.listConnections((sel[0]+".ikTopJnt")) ikMidJ = cmds.listConnections((sel[0]+".ikMidJnt")) ikEndJ = cmds.listConnections((sel[0]+".ikEndJnt")) #get FK wrist joint position & rot ikEndPos = cmds.xform(ikEndJ, q=True, ws=True, t=True) iep = om.MVector(ikEndPos[0], ikEndPos[1], ikEndPos[2]) ikEndRot = cmds.xform(ikEndJ, q=True, ro=True) ier = om.MVector(ikEndRot[0], ikEndRot[1], ikEndRot[2]) #get FK shoulder position & rot ikTopPos = cmds.xform(ikTopJ, q=True, ws=True, t=True) itp = om.MVector(ikTopPos[0], ikTopPos[1], ikTopPos[2]) ikTopRot = cmds.xform(ikTopJ, q=True, ro=True) itr = om.MVector(ikTopRot[0], ikTopRot[1], ikTopRot[2]) #get midJnt pos & rot ikMidPos = cmds.xform(ikMidJ, q=True, ws=True, t=True) imp = om.MVector(ikMidPos[0], ikMidPos[1], ikMidPos[2]) ikMidRot = cmds.xform(ikMidJ, q=True, ro=True) imr = om.MVector(ikMidRot[0], ikMidRot[1], ikMidRot[2]) #rotate joints to rotations cmds.xform(fkEndC, ro=(ier.x, ier.y, ier.z)) cmds.xform(fkMidC, ro=(imr.x, imr.y, imr.z)) cmds.xform(fkTopC, ro=(itr.x, itr.y, itr.z)) #snap FK ctrl to positions #-------try:except this part . . . Will only work if the channels aren't locked . . . cmds.move(iep.x, iep.y, iep.z, fkEndC, ws=True) cmds.move(imp.x, imp.y, imp.z, fkMidC, ws=True) cmds.move(iep.x, iep.y, iep.z, fkEndC, ws=True)
def createJointFromObj(objs = [], *args): """ creates a joint at obj location/orientation. Can be arg[list] or selection :param objs: a list of objects to operate on :param args: :return: """ if not objs: objs = cmds.ls(sl=True, type="transform") if objs: for obj in objs: pos = cmds.xform(obj, q=True, ws=True, rp=True) rot = cmds.xform(obj, q=True, ws=True, ro=True) jnt = cmds.joint(name="{0}_JNT".format(obj)) grp = cmds.group(jnt, n="{0}_JNT_GRP".format(obj)) if cmds.listRelatives(grp, p=True): cmds.parent(grp, w=True) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) else: cmds.warning("You need to select object(s)")
def get_center_point(objs): positions = [] for obj in objs: positions.append(cmds.xform(obj, ws=True, q=True, rp=True)) center = [sum(y)/len(y) for y in zip(*positions)] return(center)
def switchMatchSpace(index, *args): #get the obj and attr obj = cmds.textFieldGrp(widgets["objTFG"], q=True, tx=True) #print("switchMatch obj val :%s"%obj) attr = "%s.follow"%obj #get the space value that was selected? why? #get the existing ws xform values of obj ws1Pos = cmds.xform(obj, q=True, ws=True, t=True) ws1Rot = cmds.xform(obj, q=True, ws=True, ro=True) #(maybe also key it a frame before at previous value?) #set and key the switch cmds.setAttr("%s.follow"%obj, index) #-------------setKey here? #set the old ws xform of obj ws2Pos = cmds.xform(obj, ws=True, t=ws1Pos) ws2Rot = cmds.xform(obj, ws=True, ro=ws1Rot) print("changed space of %s to index %s"%(obj,index)) #set and key the space pass
def smoothPoints(num = 5, push = 0.05): """ tries to smooth the surrounding pts around an outlier cv num = number of points on either side to affect push = amount to push out along tangent """ tgtPts = cmds.ls(sl=True, fl=True) for tgtPt in tgtPts: tgtPtPos = cmds.pointPosition(tgtPt) tgtNum = int(tgtPt.partition("[")[2].rpartition("]")[0]) tgtBase = tgtPt.partition("[")[0] #crv = tgtBase.partition(".")[0] tgtTan = getNormalizedTangent(tgtPt) for x in range(-num, num+1): if x != 0: origPt = "{0}[{1}]".format(tgtBase, tgtNum + x) origPtPos = cmds.pointPosition(origPt) perc = (float(abs(x))/(num + 1.0)) #print origPt, perc newPosRaw = om.MVector(*lerp(tgtPtPos, origPtPos, math.sin(perc*3.14*0.5))) tan = om.MVector(tgtTan[0]*math.pow(1-perc/num, num)*push, tgtTan[1]*math.pow(1-perc/num, num)*push, tgtTan[2]*math.pow(1-perc/num, num)*push) #tan = om.MVector(tgtTan[0]*push, tgtTan[1]*push, tgtTan[2]*push) if x<0: newPos = newPosRaw + tan if x>0: newPos = newPosRaw - tan #print origPt, newPosRaw.x, newPosRaw.y, newPosRaw.z cmds.xform(origPt, ws=True, t=newPos)
def center_locator(*args): """creates a center loc on the avg position""" sel = cmds.ls(sl=True, fl=True) if sel: ps = [] for vtx in sel: ps.append(cmds.xform(vtx, q=True, ws=True, rp=True)) # this is cool! center = [sum(y)/len(y) for y in zip(*ps)] loc = cmds.spaceLocator(name="center_locator") cmds.xform(loc, ws=True, t=center)
def jointFromList(xformList=[], orient="xyz", secAxis="zup", strip="", suffix="", *args): """ uses the xformlist arg (a list of transforms in scene) to create a joint chain in order. Arguments: xformList (a list), orient ("xyz", etc), secAxis ("xup", "zdown", etc), strip (string to strip off), suffix (string to add to the joints) """ jointList = [] #if no list is provided, get the list from selection order if not xformList: sel = getSelection() if sel: xformList = sel #if no list && no selection then throw error else: cmds.error("you must provide a list of transforms or have the transforms selected in order") #clear selection cmds.select(cl=True) #for each thing in the list create a joint at that location (they'll be parented to the previous) for xform in xformList: xformPos = cmds.xform(xform, q=True, ws=True, t=True) jointName = "%s%s"%(xform.rstrip(strip), suffix) thisJoint = cmds.joint(n=jointName, p=xformPos) jointList.append(thisJoint) #now orient the joint chain based on args and return a list of the joints cmds.joint(jointList[0], e=True, ch=True, oj=orient, sao=secAxis) return(jointList)
def alignToUV(targetObj="none", sourceObj="none", sourceU=0.0, sourceV=0.0, mainAxis="+z", secAxis="+x", UorV="v"): """ inputs should be 1. targetObj 2. sourceObj 3. sourceU 4. sourceV 5. mainAxis(lowerCase, + or -, i.e."-x" 8. secAxis (lowcase, + or -) 7, UorV ("u" or "v" for the direction along surface for the sec axis) """ axisDict = {"+x":(1,0,0), "+y":(0,1,0), "+z":(0,0,1), "-x":(-1,0,0), "-y":(0,-1,0), "-z":(0,0,-1)} #Does this create a new node? no To create a node, use the flag "ch=True". That creates a pointOnSurface node pos = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, position=True) posVec = om.MVector(pos[0], pos[1], pos[2]) cmds.xform(targetObj, ws=True, t=pos) #get normal, tanU and tanV at selected UV position on source surface tanV = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tv=True) tanU = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tu=True) norm = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, nn=True) #decide where up axis is on normal constraint, u or v tangent if UorV == "v": wup = tanV elif UorV == "u": wup = tanU #create normal constraint nc = cmds.normalConstraint(sourceObj, targetObj, aimVector=axisDict[mainAxis], upVector=axisDict[secAxis], worldUpVector=(wup)) cmds.delete(nc) #delete constraint
def snapTo(target, obj): pos = cmds.xform(target, q=True, ws=True, rp=True) rot = cmds.xform(target, q=True, ws=True, ro=True) cmds.xform(obj, ws=True, t=pos) cmds.xform(obj, ws=True, ro=rot)
def swapDupe(obj, target, delete = True, name="", *args): """ replaces an target with a duplicate of the obj select the object you want to duplicate, then the target(s), delete bool, name optional [obj] is the object to duplicate [target] is the target to match and delete(?) [delete] is bool to tell whether to delete the target or not [name] is string to rename to """ if not name: name = obj # get pos, rot, scale of target pos = cmds.xform(target, q=True, ws=True, rp=True) rot = cmds.xform(target, q=True, ws=True, ro=True) scl = cmds.getAttr("{0}.scale".format(target)) # duplicate the object and rename to name, if no name just use unique names dupe = cmds.duplicate(obj, name=name, returnRootsOnly=True, renameChildren=True) cmds.xform(dupe, ws=True, t=pos) cmds.xform(dupe, ws=True, ro=rot) cmds.xform(dupe, ws=True, s=scl[0]) parent = cmds.listRelatives(target, parent=True) if parent: cmds.parent(dupe, parent[0]) if delete: cmds.delete(target) return(dupe[0])
def closest_pt_on_mesh_rotation(point, mesh, *args): # TODO - generalize for various orientations, and various rotation orders """ takes a point (can be name of transform or iterable(3) of rotations and a poly mesh and gives the rotation [rot order xyz] (for aim along y) align to surface of the xform at that point """ if isinstance(point, basestring): if isType(point, "transform"): cmds.select(point, r=True) ptPos = cmds.xform(point, ws=True, q=True, rp=True) name = point else: cmds.warning("zbw_rig.closest_pt_on_mesh_position: the string you gave me isn't a transform") return () elif isinstance(point, (list, tuple)): if len(point) == 3: ptPos = point name = mesh else: cmds.warning("zbw_rig.closest_pt_on_mesh_position: there are not the right number of entries in the " "list you gave me") # get the rotations to align to normal at this point loc = cmds.spaceLocator() CPOMesh = closest_pt_on_mesh_position(point, mesh) cmds.xform(loc, ws=True, t=CPOMesh) aimVec = (0, 1, 0) upVec = (0, 1, 0) nc = cmds.normalConstraint(mesh, loc, aim=aimVec, upVector=upVec) rot = cmds.xform(loc, ws=True, q=True, ro=True) cmds.delete(nc, loc) return (rot)
def calibrate_size(xform, scale=0.2, *args): """ will take the bounding box of given transform and return *scale it's longest edge or option to do volume and return some portion of that. . . just to give scale factor for controls and such :param xform: :param args: :return: """ if not isType(xform, "transform"): cmds.warning("zbw_rig.calibrate_size: You didn't pass me a transform ({0})".format(xform)) return(None) box = cmds.exactWorldBoundingBox(xform) # [xmin, ymin, zmin, xmax, ymax, zmax] X = om.MVector(box[0], box[3]) Y = om.MVector(box[1], box[4]) Z = om.MVector(box[2], box[5]) # get bbox lengths along axes lenX = (X.y - X.x) lenY = (Y.y - Y.x) lenZ = (Z.y - Z.x) lgst = max([lenX, lenY, lenZ]) outScale = float(lgst)*float(scale) return(outScale)
def new_joint_bind_at_center(tform, *args): """ create a new joint at the boudnign box center of pts and bind all pts to 1 :param tform - string - the geo to bind :param args: :return: string - skinCluster """ cmds.select(cl=True) jnt = cmds.joint(name="{0}_base_JNT".format(tform)) center = bounding_box_center(tform) cmds.xform(jnt, ws=True, t=center) skinCl = cmds.skinCluster(jnt, tform, normalizeWeights=1)[0] return(jnt, skinCl)
def dupeIt(*args): """uses the first selection and duplicates it to the transforms of the rest of the selected objects, with or without connections""" sel=cmds.ls(sl=True, type="transform", l=True) inputs = cmds.radioButtonGrp("inputsRBG", q=True, sl=True) if sel: base=sel[0] if len(sel)>1: objs=sel[1:] transforms = {} x=0 for obj in objs: #get pos, rot, scale pos = cmds.xform(obj, ws=True, q=True, t=True) rot = cmds.xform(obj, ws=True, q=True, ro=True) scal = cmds.getAttr("%s.scale"%obj)[0] transforms[x] = [pos, rot, scal] #delete the obj cmds.delete(obj) x=x+1 for key in transforms.keys(): if inputs == 1: dupe = cmds.duplicate(base)[0] elif inputs == 3: dupe = cmds.duplicate(base, un=True, rr=True)[0] elif inputs == 2: dupe = cmds.duplicate(base, ic=True)[0] print dupe cmds.xform(dupe, ws=True, t=transforms[key][0]) cmds.xform(dupe, ws=True, ro=transforms[key][1]) cmds.setAttr("%s.scale"%dupe, transforms[key][2][0], transforms[key][2][1], transforms[key][2][2]) #TODO - checkbox to copy inputs on orig objects to corresponding inputs on top level of duplicates else: cmds.warning("You need to select more than one object in order to swap!") else: cmds.warning("Please select some transform nodes to dupe!")
def matchPoleVectorControl(jointChain, pv=None, doSnap=True): ''' Position a pole vector based on a 3-joint chain ''' def distanceBetween(a,b): difference = [x-y for x,y in zip(a,b)] return math.sqrt(sum([x**2 for x in difference])) p1 = mc.xform(jointChain[0], query=True, rotatePivot=True, worldSpace=True) p2 = mc.xform(jointChain[1], query=True, rotatePivot=True, worldSpace=True) p3 = mc.xform(jointChain[2], query=True, rotatePivot=True, worldSpace=True) mag1 = distanceBetween(p2,p1) mag2 = distanceBetween(p3,p2) #these are all temporary nodes loc = mc.spaceLocator(name='TEMP#')[0] mc.pointConstraint(jointChain[0], loc, weight=mag2) mc.pointConstraint(jointChain[2], loc, weight=mag1) mc.aimConstraint(jointChain[1], loc, aimVector=(1,0,0), upVector=(0,1,0), worldUpType='object', worldUpObject=jointChain[0]) pCenter = mc.xform(loc, query=True, rotatePivot=True, worldSpace=True) pPV = mc.xform(pv, query=True, rotatePivot=True, worldSpace=True) pvDist = distanceBetween(pPV,pCenter) loc2 = mc.spaceLocator(name='TEMP#')[0] loc2 = mc.parent(loc2, loc)[0] mc.setAttr(loc2+'.translate', (pvDist),0,0) if doSnap: snap(pv, loc2) mc.delete(loc) else: #for matching a range return loc, loc2
def testAllRotateOrdersForGimbal(obj): #duplicate node without children dup = mc.duplicate(obj, name='temp#', parentOnly=True)[0] tolerences = list() for roo in ROTATE_ORDERS: mc.xform(dup, preserve=True, rotateOrder=roo) tolerences.append(gimbalTolerence(dup)) #delete node mc.delete(dup) return tolerences
def softSelectionClusterWeights(*args): sel = mc.ls(sl=True, o=True) if not sel: raise RuntimeError('Please select some vertices.') weights = getSoftSelectionWeights() if not weights: raise RuntimeError('Please select some vertices.') #get manipulator position for pivot mc.setToolTo('Move') moveMode = mc.manipMoveContext('Move', query=True, mode=True) mc.manipMoveContext('Move', edit=True, mode=0) position = mc.manipMoveContext('Move', query=True, position=True) mc.manipMoveContext('Move', edit=True, mode=moveMode) clusterNode, clusterHandle = mc.cluster(sel[0]) for vert in mc.ls(sel[0]+'.vtx[*]', fl=True, l=True): weight = 0.0 if vert in weights.keys(): weight = weights[vert] mc.percent(clusterNode, vert, v=weight) #set cluster pivot mc.xform(clusterHandle, a=True, ws=True, piv=(position[0], position[1], position[2])) clusterShape = mc.listRelatives(clusterHandle, c=True, s=True) mc.setAttr(clusterShape[0] + '.origin', position[0], position[1], position[2])
def edge_length(self, vertex_list): #find distance between two points. numpy required. need to rework this so numpy not required vtx_p=cmds.xform(vertex_list,q=True,t=True,ws=True) ''' this is numpy version. reuse for machines with numpy for quicker calculations: vtx_p_array_a = np.array([[vtx_p[0]], [vtx_p[1]], [vtx_p[2]]]) vtx_p_array_b = np.array([[vtx_p[3]], [vtx_p[4]], [vtx_p[5]]]) dist = np.linalg.norm(vtx_p_array_a-vtx_p_array_b) ''' dist = math.sqrt((vtx_p[3] - vtx_p[0])**2 + (vtx_p[4] - vtx_p[1])**2 + (vtx_p[5] - vtx_p[2])**2) return dist
def BT_SetPose(set = None, index = None): if not set: return False if BT_IsSetupConnected(set = set): cmds.warning('Disconnect setup first!') return False if not cmds.attributeQuery('Blend_Node', ex = True, n = set): return False node = cmds.getAttr(set +'.Blend_Node') transforms = cmds.listConnections(set +'.dagSetMembers') if not transforms: return False unitResult = BT_SetUnits() if unitResult: QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay") for i in range(0, len(transforms)): baseM = cmds.getAttr(node +'.transforms[' +str(i) +'].baseMatrix') baseS = cmds.getAttr(node +'.transforms[' +str(i) +'].baseScale')[0] baseRO = cmds.getAttr(node +'.transforms[' +str(i) +'].baseRotOffset')[0] poseM = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] poseS = [0,0,0] if index is not None: numPoses = cmds.getAttr(node +'.transforms[0].poses', size = True) if not index < numPoses: return False poseM = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].matrix') poseS = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].scale')[0] finalM = [x+y for x, y in zip(poseM, baseM)] finalS = [x+y for x, y in zip(poseS, baseS)] cmds.xform(transforms[i], m = finalM) cmds.setAttr(transforms[i] +'.scale', finalS[0], finalS[1], finalS[2], type = 'double3') #hack to fix joint orient stuff if cmds.objectType(transforms[i], isType = 'joint'): cmds.setAttr(transforms[i] +'.jointOrient', baseRO[0], baseRO[1], baseRO[2], type = 'double3') currentRot = cmds.getAttr(transforms[i] +'.rotate')[0] cmds.setAttr(transforms[i] +'.rotate', currentRot[0] - baseRO[0], currentRot[1] - baseRO[1], currentRot[2] - baseRO[2], type = 'double3') return True
def BT_AddPose(set = None, poseName = '', index = None): prefixedPoseName = 'BT_' +poseName if not set: return False if not cmds.attributeQuery('Blend_Node', ex = True, n = set): return False if BT_IsSetupConnected(set = set): cmds.warning('Disconnect setup first!') return False blendNode = cmds.getAttr(set +'.Blend_Node') if not cmds.objExists(blendNode) or not cmds.objExists(set): return False if cmds.attributeQuery(prefixedPoseName, ex = True, n = set): return False transforms = cmds.listConnections(set +'.dagSetMembers') numTransforms = len(transforms) poseIndex = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) if index is not None: poseIndex = index if index is None: cmds.addAttr(set, ln = prefixedPoseName, nn = poseName, k = True, min = 0, max = 1.0, at = 'double') # print ('Num poses = ' +str(numPoses)) for i in range(0, numTransforms): #get the base matrix baseScale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseScale')[0] baseMatrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseMatrix') #store the scale and set it transformScale = cmds.getAttr(transforms[i] +'.scale')[0] #set the scale back to 1.0 cmds.setAttr(transforms[i] +'.scale', 1.0, 1.0, 1.0, type = 'double3') transformMatrix = cmds.xform(transforms[i], q = True, m = True) poseMatrix = [x-y for x, y in zip(transformMatrix, baseMatrix)] poseScale = [x-y for x, y in zip(transformScale, baseScale)] #set the scale back to what the user had it at cmds.setAttr(transforms[i] +'.scale', transformScale[0], transformScale[1], transformScale[2], type = 'double3') cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].matrix', poseMatrix, type = 'matrix') BT_Double3ValuesToNode(values = poseScale, node = blendNode, attr = 'transforms[' +str(i) +'].poses[' +str(poseIndex) +'].scale' ) if index is None: cmds.connectAttr(set +'.' +prefixedPoseName, blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].weight') return True