def createArrow(name=None, thickness=0.1, length=2, vector=[1,0,0], point=[0,0,0]): ''' Creates an arrow in the direction of the vector Example: arrow = createArrow(vector=[0,1,0], length=4) ''' if not name: name = 'arrow_CTRL' #calc length for thickness ratio = length/thickness cyl = cmds.cylinder(radius=thickness, sections=4, heightRatio=ratio, pivot=[length/2, 0, 0], ch=0)[0] cone = cmds.cone(radius=thickness*2, sections=4, ch=0, pivot=(length*1.0005,0,0))[0] xform = cmds.createNode('transform', ss=1, name=name) shapes = [] transforms = [] for node in [cone,cyl]: shapes.append(cmds.listRelatives(node, fullPath=1, shapes=1)[0]) transforms.append(node) cmds.parent(shapes, xform, r=1, s=1) rotateBy = cmds.angleBetween(euler=True, v1=(1,0,0), v2=vector) cmds.rotate(rotateBy[0], rotateBy[1], rotateBy[2], xform) cmds.xform(xform, t=point) cmds.delete(transforms) return xform
def calcMidPointMVector(posA, posB, aim, offset): midpoint = (posA + posB) /2 dir = om.MVector.normal(posA - posB) offset = dir * offset offMidPoint = midpoint + offset rotate = mc.angleBetween( euler=True, v1=(aim[0], aim[1], aim[2]), v2=(dir.x, dir.y, dir.z) ) cut = (offMidPoint, rotate) return cut
def do_rotate( p1, p2, p3, p4, group): v1 = [] v2 = [] for k in range( 3 ): v1.append( cmds.xform( p2, worldSpace = True, translation = True, query = True )[k] - cmds.xform( p1, worldSpace = True, translation = True, query = True )[k]) v2.append( cmds.xform( p4, worldSpace = True, translation = True, query = True )[k] - cmds.xform( p3, worldSpace = True, translation = True, query = True )[k]) angle = cmds.angleBetween( v1 = (v1[0], v1[1], v1[2]), v2 = (v2[0], v2[1], v2[2]), euler = True ) rpX, rpY, rpZ = cmds.xform( p1, worldSpace = True, translation = True, query = True ) cmds.xform( group, rotatePivot = ( rpX, rpY, rpZ ), rotation = ( angle[0], angle[1], angle[2] ), relative = True )
def doDrag(self, *args, **kwargs): if not self.newJoint: return None intersectPoint, intersectNormal = self.getIntersectPointAndNormal() if not intersectPoint: return None cmds.move( intersectPoint.x, intersectPoint.y, intersectPoint.z, self.newJoint, ws=1 ) angle = cmds.angleBetween( v1=[0,0,1], v2=[intersectNormal.x,intersectNormal.y,intersectNormal.z], er=1 ) cmds.rotate( angle[0], angle[1], angle[2], self.newJoint, ws=1 ) cmds.refresh() self.movedPosition = intersectPoint
def doPress( self, *args, **kwargs ): self.newJoint = None intersectPoint, intersectNormal = self.getIntersectPointAndNormal() if not intersectPoint: return None self.newJoint = self.getJoint() cmds.undoInfo( swf=0 ) cmds.select( self.newJoint ) cmds.setAttr( self.newJoint+'.dla', 1 ) self.origPosition = OpenMaya.MPoint( *cmds.xform( self.newJoint, q=1, ws=1, t=1 ) ) cmds.move( intersectPoint.x, intersectPoint.y, intersectPoint.z, self.newJoint, ws=1 ) angle = cmds.angleBetween( v1=[0,0,1], v2=[intersectNormal.x,intersectNormal.y,intersectNormal.z], er=1 ) cmds.rotate( angle[0], angle[1], angle[2], self.newJoint, ws=1 ) cmds.refresh()
def createLRA(node=None, matrix=None, name=None, color=True, thickness=0.1, length=2, vector=[1,0,0], point=[0,0,0], arrowRadiusMult=2): ''' Creates an LRA at the origin, or at a node, or a mmx Example: createLRA(length=2, thickness=0.05, arrowRadiusMult=3) ''' if not name: name = 'arrow_CTRL' nodes = [] x,y,z = [],[],[] #calc length for thickness ratio = length/thickness xform = cmds.createNode('transform', ss=1, name=name) x.append(cmds.cylinder(radius=thickness, sections=4, heightRatio=ratio, pivot=[length/2, 0, 0], ch=0, axis=[1,0,0])[0]) x.append(cmds.cone(radius=thickness*arrowRadiusMult, sections=4, ch=0, pivot=(length*1.0005,0,0))[0]) y.append(cmds.cylinder(radius=thickness, sections=4, heightRatio=ratio, pivot=[0, length/2, 0], ch=0, axis=[0,1,0])[0]) y.append(cmds.cone(radius=thickness*arrowRadiusMult, sections=4, ch=0, pivot=(0,length*1.0005,0), axis=[0,1,0])[0]) z.append(cmds.cylinder(radius=thickness, sections=4, heightRatio=ratio, pivot=[0, 0, length/2], ch=0, axis=[0,0,1])[0]) z.append(cmds.cone(radius=thickness*arrowRadiusMult, sections=4, ch=0, pivot=(0,0,length*1.0005), axis=[0,0,1])[0]) nodes.extend(x) nodes.extend(y) nodes.extend(z) if color: for node in x: colorControl(node, name='red_m', color=(1,0,0)) for node in y: colorControl(node, name='green_m', color=(0,1,0)) for node in z: colorControl(node, name='blue_m', color=(0,0,1)) shapes = [] transforms = [] for node in nodes: shapes.append(cmds.listRelatives(node, fullPath=1, shapes=1)[0]) transforms.append(node) cmds.parent(shapes, xform, r=1, s=1) rotateBy = cmds.angleBetween(euler=True, v1=(1,0,0), v2=vector) cmds.rotate(rotateBy[0], rotateBy[1], rotateBy[2], xform) cmds.xform(xform, t=point) cmds.delete(transforms) return xform
def __init__(self,*args,**keywords): # default options self.name='limb' self.stretch=20 self.squash=0 self.twist=True # performs auto detect self.sway=True self.switch='ik' # initial ik/fk switch state self.handleOptions=[{'type':'doubleEllipse','spin':-180},{'type':'doubleEllipse','spin':-90},{'type':'doubleEllipse'},{'type':'locator'}] self.tol=1.0 # angle tolerance for preferred angles self.parent='' self.shortNames=\ { 'n':'name', 'p':'parent', 'sp':'softParent', 'co':'controlObjects', 'ho':'handleOptions' } # attributes self.controlObjects=['','','',''] self.bindPoses=[] self.joints=[] self.group='' self.orientAxis='' self.bendAxis='' self.poleAxis='' self.ctrlJoints=[] self.handles=[] self.endEffector='' self.ikHandle='' self.jointParent='' self.jointParent='' self.originalRotations={} self.bendDirection=0 self.poleVector=[] self.poleVectorWorld=[] self.upVector=[] self.aimVector=[] self.parentSpaces=[] for k in keywords: if k in self.__dict__: exec('self.'+k+'=keywords[k]') elif k in self.shortNames: exec('self.'+self.shortNames[k]+'=keywords[k]') uniqueNames(re=True) if len(args)==0: args=mc.ls(sl=True) sel=[] for a in args: sel.extend(iterable(a)) sel=hierarchyOrder(sel) # parse options defualtHandleOptions=[{'type':'doubleEllipse','spin':-180},{'type':'doubleEllipse','spin':-90},{'type':'doubleEllipse'},{'type':'locator'}] i=len(self.handleOptions) while len(self.handleOptions)<4: self.handleOption.append(defualtHandleOptions[i]) i+=1 if isinstance(self.handleOptions,dict): self.handleOptions=[self.handleOptions,self.handleOptions,self.handleOptions] elif isIterable(self.handleOptions): if len(self.handleOptions)==0: self.handleOptions.append({}) while len(self.handleOptions)<3: self.handleOptions.append(self.handleOptions[-1]) else: self.handleOptions=[{},{},{}] self.controlObjects=iterable(self.controlObjects) self.orientAxis=self.orientAxis.lower() self.baseTwist='' self.hierarchy=[] if len(sel)>2: for j in sel[:-1]: if len(hierarchyBetween(j,sel[-1]))>len(self.hierarchy): self.hierarchy=hierarchyBetween(j,sel[-1]) closest=9e999 for s in removeAll([self.hierarchy[0],self.hierarchy[-1]],sel): if\ ( len(iterable(mc.listRelatives(self.hierarchy[0],p=True)))==0 or s in mc.listRelatives(mc.listRelatives(self.hierarchy[0],p=True)[0],c=True,type='joint') ): dist=distanceBetween(s,self.hierarchy[0]) if dist<closest: closest=dist self.baseTwist=s else: self.hierarchy=hierarchyBetween(sel[0],sel[-1]) self.bindPoses=iterable(getBindPoses(self.hierarchy)) self.joints=['','',''] if len(self.hierarchy)<3: raise Exception('There are no joints between your start and end joint. No IK created.') self.joints[0]=self.hierarchy[0] self.joints[-1]=self.hierarchy[-1] # find the orientation axis self.orientAxis='x' axisLen={'x':0,'y':0,'z':0} for j in self.hierarchy[1:]: for a in ['x','y','z']: axisLen[a]+=abs(mc.getAttr(j+'.t'+a)) if axisLen[a]>axisLen[self.orientAxis]: self.orientAxis=a # find bend joint and pole vector self.originalRotations={} for j in self.hierarchy[1:-1]: # check to see if any have a non-zero preferred angle for a in removeAll(self.orientAxis,['x','y','z']): if abs(mc.getAttr(j+'.pa'+a))>=self.tol: self.originalRotations[j+'.r'+a]=mc.getAttr(j+'.r'+a) mc.setAttr(j+'.r'+a,mc.getAttr(j+'.pa'+a)) greatestAngle=0 for j in self.hierarchy[1:-1]: jPos=mc.xform(j,q=True,ws=True,rp=True) prevJPos=mc.xform(self.hierarchy[self.hierarchy.index(j)-1],q=True,ws=True,rp=True) nextJPos=mc.xform(self.hierarchy[self.hierarchy.index(j)+1],q=True,ws=True,rp=True) vAngle=mc.angleBetween(v1=normalize(jPos[0]-prevJPos[0],jPos[1]-prevJPos[1],jPos[2]-prevJPos[2]),v2=normalize(nextJPos[0]-jPos[0],nextJPos[1]-jPos[1],jPos[2]-jPos[2]))[-1] if abs(vAngle)>greatestAngle: greatestAngle=abs(vAngle) self.joints[1]=j mp=midPoint\ ( self.hierarchy[0],self.hierarchy[-1], bias=\ ( distanceBetween(self.hierarchy[0],self.joints[1])/ (distanceBetween(self.hierarchy[0],self.joints[1])+distanceBetween(self.joints[1],self.hierarchy[-1])) ) ) bendPoint=mc.xform(self.joints[1],q=True,ws=True,rp=True) self.poleVectorWorld=normalize\ ( bendPoint[0]-mp[0], bendPoint[1]-mp[1], bendPoint[2]-mp[2] ) pmm=mc.createNode('pointMatrixMult') mc.setAttr(pmm+'.vm',True) mc.connectAttr(self.joints[1]+'.worldInverseMatrix',pmm+'.im') mc.setAttr(pmm+'.ip',*self.poleVectorWorld) self.poleVector=mc.getAttr(pmm+'.o')[0] disconnectNodes(pmm) mc.delete(pmm) greatestLength=0.0 for i in [0,1,2]: if abs(self.poleVector[i])>greatestLength and ['x','y','z'][i]!=self.orientAxis: self.poleAxis=['x','y','z'][i] greatestLength=abs(self.poleVector[i]) self.bendDirection=-abs(self.poleVector[i])/self.poleVector[i] for r in self.originalRotations: mc.setAttr(r,self.originalRotations[r]) preferredAngleWarning=False if not mc.objExists(self.joints[1]): preferredAngleWarning=True mp=midPoint(self.hierarchy[0],self.hierarchy[-1]) cd=9e999 dist=0 for j in self.hierarchy[1:-1]: dist=distanceBetween(j,mp) if dist<cd: cd=dist self.joints[1]=j self.bendAxis=removeAll(self.orientAxis,['z','y','x'])[0] if self.poleAxis=='': self.poleAxis=removeAll([self.orientAxis,self.bendAxis],['x','y','z'])[0] if self.bendAxis=='': self.bendAxis=removeAll([self.orientAxis,self.poleAxis],['x','y','z'])[0] if self.orientAxis=='': self.orientAxis=removeAll([self.bendAxis,self.poleAxis],['x','y','z'])[0] if self.poleAxis=='x': self.poleVector=[-self.bendDirection,0.0,0.0] if self.poleAxis=='y': self.poleVector=[0.0,-self.bendDirection,0.0] if self.poleAxis=='z': self.poleVector=[0.0,0.0,-self.bendDirection] if self.bendAxis=='x': self.upVector=[-self.bendDirection,0.0,0.0] if self.bendAxis=='y': self.upVector=[0.0,-self.bendDirection,0.0] if self.bendAxis=='z': self.upVector=[0.0,0.0,-self.bendDirection] if self.orientAxis=='x': self.aimVector=[self.bendDirection,0.0,0.0] if self.orientAxis=='y': self.aimVector=[0.0,self.bendDirection,0.0] if self.orientAxis=='z': self.aimVector=[0.0,0.0,self.bendDirection] if mc.objExists(self.baseTwist): conn=False for a in ['.r','.rx','.ry','.rz']: if mc.connectionInfo(self.baseTwist+a,id=True): conn=True if not conn: mc.orientConstraint(self.joints[0],self.baseTwist,sk=self.orientAxis) # load ik2Bsolver - ikRPSolver does not work well with this setup mel.eval('ik2Bsolver') self.create() if preferredAngleWarning: raise Warning('Warning: Joints are co-linear and no preferred angles were set. Results may be unpredictable.')
def do_align_rot_axis(p1, p2, trackGrp): v1 = cmds.xform( p1, worldSpace = True, translation = True, query = True ) v2 = cmds.xform( p2, worldSpace = True, translation = True, query = True ) axis = ( v2[0]-v1[0], v2[1]-v1[1], v2[2]-v1[2] ) angle = cmds.angleBetween( v1= axis, v2 = (1, 0, 0), euler = True ) cmds.rotate( angle[0], angle[1], angle[2], trackGrp+'.rotateAxis')
for chain_child in cmds.listRelatives(child, ad=True, type='joint'): c_length += cmds.getAttr( chain_child+'.tx' ) length_dict[child] = c_length if (c_length < length_dict[shortest]): shortest = child # now we have the shortest chain (thumb), we can start finding other fingers # I will use two vectors, v1 will be the shortest chain (thumb), and v2 every other finger # then compare the angle between the two for each of them v1 = cmds.getAttr(shortest+'.translate')[0] angle_dict = dict() for child in im_children: if child != shortest: v2 = cmds.getAttr(child+'.translate')[0] ab = cmds.angleBetween(v1=v1,v2=v2)[-1] angle_dict[child] = ab # sort angles in a list angle_list = angle_dict.values() angle_list.sort() # match angles to names based on their distance from the thumb if (hand_ctrl.lower()).find('right') >= 0: side = 'right' else: side = 'left' for child, angle in angle_dict.iteritems():
####################################################################################################################### ## YOU CAN USE THIS METHOD FOR LINES AND VERTS ## ####################################################################################################################### import maya.cmds as cmds sl=cmds.ls(selection=True, flatten=True) toVerts = cmds.polyListComponentConversion(sl, tv=True) verts = cmds.ls(toVerts, flatten = True) flatnormals = cmds.polyNormalPerVertex(verts, q=True, xyz=True) normals = [] normals = zip(*[iter(flatnormals)]*3) xNorm = [x[0] for x in normals]; xVector = sum(xNorm)/len(xNorm) yNorm = [x[1] for x in normals]; yVector = sum(yNorm)/len(yNorm) zNorm = [x[2] for x in normals]; zVector = sum(zNorm)/len(zNorm) finalAngle = cmds.angleBetween( euler=True, v2= [xVector, yVector, zVector], v1=[0, 1, 0] ) ## TEST OBJECT ALIGNMENT cmds.xform('pCone1', ws = 1, ro = [ finalAngle[0], finalAngle[1] , finalAngle[2] ] ) ####################################################################################################################### ### USE THIS METHOD FOR FACE SELECTION. STILL AN ISSUES IF OBJECT IS ROTATED, NEED TO CALCUATE THAT IN AS WELL SOMEHOW. ####################################################################################################################### import maya.cmds as cmds import decimal ## Poluate Vars sl = cmds.ls(selection=True, flatten=True) faceList = [] xValue = [] yValue = [] zValue = []