def create(self,*args,**keywords): self.type='' self.shape='' self.obj='' self.tr='' self.edges=[] self.faces=[] self.vertices=[] self.uvs=[] self.etcObj=[] self.etc=[] self.ordered=False flatten=False if len(args)==0: args=mc.ls(sl=True) for a in args: self.extend(iterable(mc.ls(a))) #make sure we are using the name maya will use for s in self: if len(s.split('.'))<=1 or len(s.split('['))<=1:#it's an object, stash it in etcObj self.etcObj.append(s) self[:]=removeAll(self.etcObj,self) for k in keywords: if k=='f' or k=='flatten' and keywords[k]: flatten=True elif k in self.__dict__: if type(eval('self.'+k)).__name__==type(keywords[k]).__name__: exec('self.'+k+'=keywords[k]') self.shape=self.getShape() self.obj=self.getObj() self.tr=self.getTr() if self.type=='e' or self.type=='edges': self.etc.extend(removeAll(self.getEdges(),self)) self[:]=self.edges elif self.type=='v' or self.type=='vertices': self.etc.extend(removeAll(self.getVertices(),self)) self[:]=self.vertices elif self.type=='f' or self.type=='faces': self.etc.extend(removeAll(self.getFaces(),self)) self[:]=self.faces elif self.type=='uv' or self.type=='uvs': self.etc.extend(removeAll(self.getUVs(),self)) self[:]=self.uvs if flatten: self.flatten()
def shortestPath(self): "Returns a list of adjacent vertices defining the shortest path from vertA to vertB." vertA=str(self[0]) vertB=str(self[1]) del self[2:]# make sure there are only two vertices in the list vertPath=list([vertA]) vert=str(vertA) distanceList=self.distanceList(vertB,vertA) sizeList=len(distanceList) for i in range(1,sizeList): tempList=distanceList[ sizeList-i-1 ] tempList=mc.ls( tempList, fl=True ) vertices=mc.polyListComponentConversion( vert, te=True ) vertices=mc.polyListComponentConversion( vertices, tv=True ) vertices=mc.ls( vertices, fl=True ) tempA=list([vert]) vertices=removeAll(tempA,vertices) intersectorSet=Set(vertices) intersectorSet.intersection_update(tempList) vertTempArray=list(intersectorSet) vert=str(vertTempArray[0]) vertPath.append( vert ) vertPath.append( vertB ) return vertPath
def distanceList(self,vert,stopVert): """ Used by shortestPathBetween2Verts. returnVal[i] contains a list of vertices which are i edges distant from vert. returnVal will be generated until returnVal[len(returnVal)-1] contains stopVert. """ vertices=[vert] estimate=25 returnVal=[] mc.progressWindow(ii=1,title="Working",status="Sorting",max=estimate,progress=0) for i in range(0,self.getObjVertCount()): tempArray = mc.ls(vertices,fl=True) vertices = mc.polyListComponentConversion(vertices,te=True) vertices = mc.polyListComponentConversion(vertices,tv=True) flattenedListVerts=mc.ls(vertices, fl=True) tempArray=removeAll(tempArray,flattenedListVerts) tempArray=mc.polyListComponentConversion(tempArray,fv=True,tv=True) returnVal.append(tempArray) if(stopVert in flattenedListVerts): break mc.progressWindow(e=True,s=1) if( mc.progressWindow(q=True,ic=True)): mc.progressWindow(ep=True) mc.error("User Interupt.") if( mc.progressWindow(q=True, progress=True)>=mc.progressWindow(q=True, max=True)): mc.progressWindow(ep=True) mc.progressWindow(progress=0) mc.progressWindow( endProgress=True ) return returnVal
def hierarchyOrder(*args, **keywords): reverse = False shortNames = {"r": "reverse"} for k in keywords: if k in locals(): exec(k + "=keywords[k]") elif k in shortNames: exec(shortNames[k] + "=keywords[k]") if len(args) == 0: args = mc.ls(sl=True) sel = [] for a in args: sel.extend(iterable(a)) sel = removeDuplicates(mc.ls(sel, type="dagNode")) if len(sel) < 2: return sel sorted = [] unsorted = list(sel) i = 0 while len(unsorted) > 0: used = [] for x in unsorted: if len(x.split("|")) == i: sorted.append(x) used.append(x) unsorted = removeAll(used, unsorted) i += 1 if reverse: return getReversed(sorted) else: return sorted
def mkControlObjects(self): if not mc.objExists(self.handles[-1]): self.handles[-1]=mc.createNode('transform',n=uniqueNames(self.name[-1])) mc.xform(self.handles[-1],ws=True,a=True,m=mc.xform(self.ArcCtrl.handles[-1],q=True,ws=True,m=True)) mc.xform(self.handles[-1],ws=True,a=True,piv=mc.xform(self.ArcCtrl.handles[-1],q=True,a=True,ws=True,piv=True)[:3]) if 'type' not in self.handleOptions[-1]: self.handleOptions[-1]['type']=self.handleType[-1] if 'radius' not in self.handleOptions[-1]: self.handleOptions[-1]['radius']=self.radius self.handleShape[-1]=Handle(self.handles[-1],**self.handleOptions[-1]) if mc.objExists(self.parent[-1]): mc.parent(self.handles[-1],self.parent[-1]) if mc.objExists(self.softParent[-1]): self.parentSpace[-1]=ParentSpace(self.handles[-1],self.softParent[-1]) for bp in getBindPoses(self.jointHierarchy): mc.dagPose(self.parentSpace[-1],a=True,n=bp) mc.makeIdentity(self.handles[-1],apply=True,t=True)#,r=True) mc.addAttr(self.handles[-1],ln='stretch',at='float',min=0,k=1,dv=self.stretch) mc.addAttr(self.handles[-1],ln='squash',at='float',min=0,max=1,k=1,dv=self.squash) mc.addAttr(self.handles[-1],ln='arcWeight',at='float',min=0,max=1,k=1,dv=self.arcWeight) mc.addAttr(self.handles[-1],ln='width',at='float',min=0.0001,k=1,dv=self.width) mc.connectAttr(self.handles[-1]+'.stretch',self.ArcCtrl.handles[-1]+'.stretch',f=True) mc.connectAttr(self.handles[-1]+'.squash',self.ArcCtrl.handles[-1]+'.squash',f=True) mc.connectAttr(self.handles[-1]+'.arcWeight',self.ArcCtrl.handles[-1]+'.arcWeight',f=True) mc.connectAttr(self.handles[-1]+'.width',self.ArcCtrl.handles[0]+'.width',f=True) if self.curl: mc.addAttr(self.handles[-1],ln='curl',at='doubleAngle',k=1,dv=0) for r in removeAll(self.jointHierarchy,self.rivet): axis='x' longestAxisLen=0 for a in ['x','y','z']: axisLen=abs(mc.getAttr(r+'.t'+a)) if axisLen>longestAxisLen: longestAxisLen=axisLen axis=a behaviorMirrored=False try: parentJoint=mc.listRelatives(r,p=True)[0] oppositeJoint=removeAll(r,mc.listRelatives(parentJoint,c=True,type='joint'))[0] for a in ['x','y','z']: if\ ( abs(180-abs(abs(mc.getAttr(r+'.jo'+a))-abs(mc.getAttr(oppositeJoint+'.jo'+a))))<5 ): behaviorMirrored=True break except: pass pcr=mc.listConnections(r+'.rx',type='parentConstraint')[0] pcTargets=mc.parentConstraint(pcr,q=True,tl=True) pcIDs=[] nsc=listNodeConnections(pcr,s=False,d=True) for n in range(0,len(nsc)): if len(nsc[n])==2 and mc.objExists(nsc[n][-1]): pcID=getIDs(nsc[n][-1]) if isinstance(pcID,int): pcIDs.append(pcID) pcIDs=removeDuplicates(pcIDs) pcIDs.sort() pcID=pcIDs[-1] pma=mc.createNode('plusMinusAverage') if mc.getAttr(r+'.uPos')>50: mc.setAttr(pma+'.op',2) if\ ( (behaviorMirrored and parentJoint!=self.jointHierarchy[-1]) ): mc.setAttr(pma+'.op',1) if mc.getAttr(r+'.uPos')<50: mc.setAttr(pma+'.op',1) if\ ( behaviorMirrored ): mc.setAttr(pma+'.op',2) mc.setAttr(pma+'.i1[0]',mc.getAttr(pcr+'.tg['+str(pcID)+'].tor'+axis)) mc.setAttr(pcr+'.tg['+str(pcID)+'].tor'+axis,lock=False) mc.connectAttr(self.handles[-1]+'.curl',pma+'.i1[1]') mc.connectAttr(pma+'.o1',pcr+'.tg['+str(pcID)+'].tor'+axis) mc.parentConstraint(self.handles[-1],self.ArcCtrl.handles[-1],mo=True) mc.scaleConstraint(self.handles[-1],self.ArcCtrl.handles[-1],sk=('x','y'),mo=True) for bp in getBindPoses(self.jointHierarchy): mc.dagPose(self.handles[-1],a=True,n=bp) mc.setAttr(self.handles[-1]+'.sy',k=False,lock=True) mc.setAttr(self.handles[-1]+'.sx',k=False,lock=True) if not self.spread: mc.setAttr(self.handles[-1]+'.sz',k=False,lock=True) mc.setAttr(self.handles[-1]+'.v',k=False,cb=True) for bp in getBindPoses(self.jointHierarchy): mc.dagPose(self.handles[-1],a=True,n=bp)
def addInfluences(self, *influences, **keywords): controlObjects = [""] baseShapes = [""] wrapSmoothness = [1] nurbsSamples = [10] smooth = -1 smoothType = 0 influences = list(influences) shortNames = {"co": "controlObjects"} for k in keywords: if k in locals(): exec(k + "=keywords[k]") elif k in shortNames: exec(shortNames[k] + "=keywords[k]") controlObjects = iterable(controlObjects) baseShapes = iterable(baseShapes) wrapSmoothness = iterable(wrapSmoothness) nurbsSamples = iterable(nurbsSamples) if self.influences == influences: self.influences = [] else: influencesHold = influences for inf in influencesHold: if inf in self.influences: influences.remove(inf) else: self.influences.append(inf) while len(controlObjects) < len(influences): controlObjects.append(controlObjects[-1]) while len(baseShapes) < len(influences): baseShapes.append(baseShapes[-1]) while len(wrapSmoothness) < len(influences): wrapSmoothness.append(wrapSmoothness[-1]) while len(nurbsSamples) < len(influences): nurbsSamples.append(nurbsSamples[-1]) for i in range(0, len(influences)): bsh = baseShapes[i] inf = influences[i] ctrlObj = controlObjects[i] nurbsSample = self.nurbsSamples[i] wrapSmooth = self.wrapSmoothness[i] infFaces = [] infSourceShape = "" infShape = "" infTr = "" shapeType = "" if isinstance(inf, basestring): if len(inf.split(".")) > 1: shapeType = str(mc.getAttr(inf, type=True)) if ( len(iterable(mc.ls(inf, o=True, type="dagNode"))) > 0 and len(iterable(mc.listRelatives(mc.ls(inf, o=True), p=True))) > 0 ): infTr = mc.listRelatives(mc.ls(inf, o=True), p=True)[0] infShape = shape(infTr) else: infShapeHist = iterable(mc.ls(iterable(mc.listHistory(inf, f=True, af=True)), type="shape")) if len(infShapeHist) > 0: infShape = infShapeHist[0] infTr = mc.listRelatives(infShape, p=True) else: shapeType = mc.nodeType(inf) infShape = infSourceShape = inf infTr = mc.listRelatives(inf, p=True) elif isIterable(inf): infShape = mc.ls(inf, o=True)[0] infTr = mc.listRelatives(infShape, p=True)[0] shapeType = mc.nodeType(infShape) if mc.nodeType(infShape) == "mesh": inf = mc.polyListComponentConversion(inf, tf=True) inputComponents = [] for fStr in inf: inputComponents.append(fStr.split(".")[-1]) pco = mc.createNode("polyChipOff") mc.setAttr(pco + ".dup", True) mc.setAttr(pco + ".inputComponents", len(inputComponents), type="componentList", *inputComponents) mc.connectAttr(infShape + ".outMesh", pco + ".ip") psep = mc.createNode("polySeparate") mc.setAttr(psep + ".ic", 2) mc.connectAttr(pco + ".out", psep + ".ip") inf = psep + ".out[1]" if not (isinstance(bsh, basestring) and mc.objExists(bsh)): bshSource = "" for m in removeAll(infShape, mc.ls(iterable(mc.listHistory(infShape)), type="mesh")): if ( len(mc.ls(m + ".vtx[*]", fl=True)) == len(mc.ls(infShape + ".vtx[*]", fl=True)) and len(mc.ls(m + ".f[*]", fl=True)) == len(mc.ls(infShape + ".f[*]", fl=True)) and len(mc.ls(m + ".e[*]", fl=True)) == len(mc.ls(infShape + ".e[*]", fl=True)) and len(removeAll(m, mc.listHistory(m))) == 0 ): isBSTarget = False for bsConn in iterable(mc.listConnections(m, type="blendShape", p=True)): if "inputTarget" in ".".join(bsConn.split(".")[1:]): isBSTarget = True break if isBSTarget: continue else: bshSource = m break if bshSource == "": bshSource = mc.createNode("mesh", p=infTr) mc.connectAttr(infShape + ".outMesh", bshSource + ".inMesh") mc.blendShape(infShape, bshSource, w=[1, 1]) mc.delete(bshSource, ch=True) mc.setAttr(bshSource + ".io", True) pco = mc.createNode("polyChipOff") mc.setAttr(pco + ".dup", True) mc.setAttr( pco + ".inputComponents", len(inputComponents), type="componentList", *inputComponents ) mc.connectAttr(bshSource + ".outMesh", pco + ".ip") psep = mc.createNode("polySeparate") mc.setAttr(psep + ".ic", 2) mc.connectAttr(pco + ".out", psep + ".ip") bsh = psep + ".out[1]" else: inf = infShape plug = firstOpenPlug(self[0] + ".basePoints") if isinstance(inf, basestring) and mc.objExists(inf): if len(inf.split(".")) <= 1: if mc.nodeType(shape(inf)) == "mesh": inf = shape(inf) + ".outMesh" else: inf = shape(inf) + ".local" if isinstance(bsh, basestring) and mc.objExists(bsh): if len(bsh.split(".")) <= 1: if mc.nodeType(shape(bsh)) == "mesh": bsh = shape(bsh) + ".outMesh" else: bsh = shape(bsh) + ".local" else: bshShape = mc.createNode(shapeType) if shapeType == "mesh": mc.connectAttr(inf, bshShape + ".inMesh") mc.blendShape(infShape, bshShape, w=(1, 1)) mc.delete(bshShape, ch=True) bsh = bsh + ".outMesh" else: mc.connectAttr(inf, bshShape + ".create") mc.blendShape(infShape, bshShape, w=(1, 1)) mc.delete(bshShape, ch=True) bsh = bsh + ".local" mc.setAttr(bshShape + ".io", True) # mc.connectAttr(inf,self[0]+'.driverPoints['+str(plug)+']',f=True) # mc.connectAttr(bsh,self[0]+'.basePoints['+str(plug)+']',f=True # poly smooth if shapeType == "mesh": pspInf = mc.createNode("polySmoothProxy") mc.setAttr(pspInf + ".kb", False) mc.connectAttr(inf, pspInf + ".ip") inf = pspInf + ".out" pspBase = mc.createNode("polySmoothProxy") mc.setAttr(pspBase + ".kb", False) mc.connectAttr(bsh, pspBase + ".ip") bsh = pspBase + ".out" mc.connectAttr(inf, self[0] + ".driverPoints[" + str(plug) + "]", f=True) mc.connectAttr(bsh, self[0] + ".basePoints[" + str(plug) + "]", f=True) # add wrap control attributes if not mc.objExists(ctrlObj): ctrlObj = infTr if shapeType == "mesh": if not "wrapSmoothLevels" in mc.listAttr(ctrlObj): mc.addAttr(ctrlObj, ln="wrapSmoothLevels", at="short", dv=0) mc.setAttr(ctrlObj + ".wrapSmoothLevels", k=False, cb=True) mc.connectAttr(ctrlObj + ".wrapSmoothLevels", pspInf + ".el") mc.connectAttr(ctrlObj + ".wrapSmoothLevels", pspBase + ".el") mc.connectAttr(ctrlObj + ".wrapSmoothLevels", pspInf + ".ll") mc.connectAttr(ctrlObj + ".wrapSmoothLevels", pspBase + ".ll") if not "wrapSmoothType" in mc.listAttr(ctrlObj): mc.addAttr( ctrlObj, ln="wrapSmoothType", at="enum", en="exponential:linear", min=0, max=1, dv=smoothType ) mc.setAttr(ctrlObj + ".wrapSmoothType", k=False, cb=True) mc.connectAttr(ctrlObj + ".wrapSmoothType", pspInf + ".mth") mc.connectAttr(ctrlObj + ".wrapSmoothType", pspBase + ".mth") if not "inflType" in mc.listAttr(ctrlObj): mc.addAttr(ctrlObj, ln="inflType", at="enum", en="none:point:face", min=1, max=2, dv=2) mc.setAttr(ctrlObj + ".inflType", k=False, cb=True) mc.connectAttr(ctrlObj + ".inflType", self[0] + ".inflType[" + str(plug) + "]") else: if not "nurbsSamples" in mc.listAttr(ctrlObj): mc.addAttr(ctrlObj, ln="nurbsSamples", at="short", dv=nurbsSample) mc.setAttr(ctrlObj + ".nurbsSamples", k=False, cb=True) mc.connectAttr(ctrlObj + ".nurbsSamples", self[0] + ".nurbsSamples[" + str(plug) + "]") if self.calculateMaxDistance: greatestDistance = 0.0 if shapeType == "mesh": distCheckMesh = mc.createNode("mesh", p=infTr) mc.connectAttr(inf, distCheckMesh + ".inMesh") deformedCP = "" if mc.nodeType(shape(self.deformed[0])) == "mesh": deformedCP = mc.createNode("closestPointOnMesh") mc.connectAttr(self.deformed[0] + ".worldMesh[0]", deformedCP + ".im") elif mc.nodeType(shape(self.deformed[0])) == "nurbsCurve": deformedCP = mc.createNode("closestPointOnCurve") mc.connectAttr(self.deformed[0] + ".worldSpace", deformedCP + ".ic") elif mc.nodeType(shape(self.deformed[0])) == "nurbsSurface": deformedCP = mc.createNode("closestPointOnSurface") mc.connectAttr(self.deformed[0] + ".worldSpace", deformedCP + ".is") for f in mc.ls(distCheckMesh + ".f[*]", fl=True): center = midPoint(f) mc.setAttr(deformedCP + ".ip", *center) closestPoint = mc.getAttr(deformedCP + ".p")[0] distance = distanceBetween(closestPoint, center) if distance > greatestDistance: greatestDistance = distance mc.disconnectAttr(inf, distCheckMesh + ".inMesh") mc.delete(distCheckMesh) if greatestDistance * 2 > mc.getAttr(self[0] + ".maxDistance"): mc.setAttr(self[0] + ".maxDistance", greatestDistance * 2) if shapeType == "mesh": if smooth >= 0: mc.setAttr(ctrlObj + ".wrapSmoothLevels", smooth) elif mc.nodeType(shape(self.deformed[0])) == "mesh": faceCount = 0 for d in self.deformed: if mc.nodeType(shape(d)) == "mesh": faceCount += len(mc.ls(shape(d) + ".f[*]", fl=True)) smoothSampleMesh = mc.createNode("mesh", p=infTr) mc.connectAttr(inf, smoothSampleMesh + ".inMesh") smoothFaceCount = 0 n = 0 while len(mc.ls(smoothSampleMesh + ".f[*]", fl=True)) < faceCount: mc.setAttr(ctrlObj + ".wrapSmoothLevels", n) n += 1 if len(mc.ls(smoothSampleMesh + ".f[*]", fl=True)) > faceCount * 1.5: mc.setAttr(ctrlObj + ".wrapSmoothLevels", mc.getAttr(ctrlObj + ".wrapSmoothLevels") - 1) mc.disconnectAttr(inf, smoothSampleMesh + ".inMesh") mc.delete(smoothSampleMesh)
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 create(self): mc.cycleCheck(e=False) if mc.objExists(self.parent): self.group=mc.createNode('transform',n=uniqueNames(self.name),p=self.parent) else: self.group=mc.createNode('transform',n=uniqueNames(self.name)) self.jointParent='' if len(iterable(mc.listRelatives(self.joints[0],p=True)))>0: self.jointParent=mc.listRelatives(self.joints[0],p=True)[0] else: self.jointParent=mc.createNode('transform',n=uniqueNames(self.name+'CtrlJointGroup')) mc.parent(self.joints[0],self.jointParent) cMuscleObjects=[] # create control joints self.ctrlJoints=[] for j in self.joints: cj=mc.createNode('joint',p=j,n=uniqueNames(self.name+'CtrlJoint')) if len(self.ctrlJoints)==0: mc.parent(cj,self.group) if mc.objExists(self.jointParent): self.jointParent=mc.rename(ParentSpace(cj,self.jointParent)[0],self.name+'CtrlJoints') else: self.jointParent=mc.rename(ParentSpace(cj)[0],self.name+'CtrlJoints') else: mc.parent(cj,self.ctrlJoints[-1]) mc.setAttr(cj+'.r',*mc.getAttr(j+'.r')[0]) mc.setAttr(cj+'.jo',*mc.getAttr(j+'.jo')[0]) self.originalRotations[cj+'.r']=list(mc.getAttr(cj+'.r')[0]) mc.setAttr(j+'.r',0,0,0) mc.setAttr(cj+'.r',0,0,0) mc.setAttr(cj+'.s',1,1,1) mc.setAttr(cj+'.radius',mc.getAttr(j+'.radius')*1.5)#0) mc.setAttr(cj+'.ovc',10) mc.connectAttr(j+'.pa',cj+'.pa') if self.joints.index(j)<len(self.joints)-1: childList=removeAll\ ( iterable(mc.listRelatives(self.joints[self.joints.index(j)+1],c=True,ad=True))+[self.joints[self.joints.index(j)+1]], iterable(mc.listRelatives(j,c=True,ad=True))+[j] ) chList=childList for c in chList: if mc.nodeType(c) not in ['transform','joint','cMuscleObject']: childList.remove(c) if mc.nodeType(c) in ['transform','joint']: for a in ['.t','.tx','.ty','.tz','.r','.rx','.ry','.rz']: if mc.connectionInfo(c+a,id=True) or mc.getAttr(c+a,l=True) or mc.getAttr(c+'.io'): childList.remove(c) break if j==self.joints[-2]: childList.append(self.joints[-1]) for jc in childList: if mc.nodeType(jc)=='transform' or mc.nodeType(jc)=='joint': if jc in self.joints[:-1]: mc.parentConstraint(cj,jc,mo=True) else: mc.parentConstraint(cj,jc,sr=('x','y','z'),mo=True) elif 'cMuscle' in mc.nodeType(jc): cMuscleObjects.append(jc) else: mc.parentConstraint(cj,j,st=('x','y','z'),mo=True) self.ctrlJoints.append(cj) mc.hide(self.jointParent) mc.setAttr(self.ctrlJoints[1]+'.ssc',False) # create ik self.ikHandle,self.endEffector=mc.ikHandle(sol='ik2Bsolver',sj=self.ctrlJoints[0],ee=self.ctrlJoints[-1],n=uniqueNames(self.name+'Handle')) self.endEffector=mc.rename(self.endEffector,self.name+'Effector') mc.setAttr(self.ikHandle+'.snapEnable',False) mc.hide(self.ikHandle) mc.setAttr(self.ikHandle+'.ikBlend',0) for j in self.originalRotations: if isIterable(self.originalRotations[j]): mc.setAttr(j,*self.originalRotations[j]) else: mc.setAttr(j,self.originalRotations[j]) # look for twist joints if self.twist: skipAxis=removeAll(self.orientAxis,['x','y','z']) twistJoints=removeAll([self.joints[-2],self.joints[-1]],hierarchyBetween(self.joints[-2],self.joints[-1],type='joint')) for i in range(0,len(twistJoints)): tj=twistJoints[i] oc=mc.orientConstraint(self.ctrlJoints[-1],tj,sk=skipAxis,mo=True) if i>0: oc=mc.orientConstraint(self.ctrlJoints[-2],tj,sk=skipAxis,mo=True) wal=mc.orientConstraint(oc,q=True,wal=True) distToBend=distanceBetween(self.ctrlJoints[-2],tj) distToEnd=distanceBetween(self.ctrlJoints[-1],tj) mc.setAttr(oc+'.'+wal[-1],distToEnd/(distToBend+distToEnd)) mc.setAttr(oc+'.'+wal[-2],distToBend/(distToBend+distToEnd)) # make stretchy db=mc.createNode('distanceBetween') mc.connectAttr(self.ctrlJoints[0]+'.t',db+'.p1') pmm1=mc.createNode('pointMatrixMult') pmm2=mc.createNode('pointMatrixMult') mc.connectAttr(self.ikHandle+'.t',pmm1+'.ip') mc.connectAttr(self.ikHandle+'.pm[0]',pmm1+'.im') mc.connectAttr(pmm1+'.o',pmm2+'.ip') mc.connectAttr(self.ctrlJoints[0]+'.pim[0]',pmm2+'.im') mc.connectAttr(pmm2+'.o',db+'.p2') mdl=mc.createNode('multDoubleLinear') mc.connectAttr(db+'.d',mdl+'.i1') mc.setAttr(mdl+'.i2',1.0/mc.getAttr(db+'.d')) cn=mc.createNode('clamp') for i in range(0,3): c=['r','g','b'][i] a=['x','y','z'][i] mc.connectAttr(mdl+'.o',cn+'.ip'+c) mc.setAttr(cn+'.mn'+c,1) mc.connectAttr(mdl+'.o',cn+'.mx'+c) mc.connectAttr(cn+'.op'+c,self.ctrlJoints[0]+'.s'+a) for cmo in cMuscleObjects: mdlcm=mc.createNode('multDoubleLinear') mc.setAttr(mdlcm+'.i1',mc.getAttr(cmo+'.length')) mc.connectAttr(cn+'.op'+['r','g','b'][['x','y','z'].index(self.orientAxis)],mdlcm+'.i2') mc.connectAttr(mdlcm+'.o',cmo+'.length') # create control objects or set control object pivots poleOffset=distanceBetween(self.ctrlJoints[1],self.ctrlJoints[0])*2 for i in range(0,len(self.controlObjects)-1): if mc.objExists(self.controlObjects[i]): mc.xform(self.controlObjects[i],ws=True,piv=mc.xform(self.ctrlJoints[-1],q=True,ws=True,rp=True)) else: if 'r' not in self.handleOptions[i] and 'radius' not in self.handleOptions[i]: self.handleOptions[i]['r']=distanceBetween(self.ctrlJoints[-1],self.ctrlJoints[0])/4 if 'name' not in self.handleOptions[i] and 'n' not in self.handleOptions[i]: self.handleOptions[i]['n']=self.joints[i]+'_ctrl' if 'x' not in self.handleOptions[i] and 'xform' not in self.handleOptions[i]: self.handleOptions[i]['xform']=self.joints[i] if 'aim' not in self.handleOptions[i] and 'a' not in self.handleOptions[i]: self.handleOptions[i]['aim']=self.aimVector self.handleOptions[i]['parent']=self.group self.handleOptions[-i]['pointTo']=self.joints[i] self.handleOptions[i]['aimAt']=self.joints[i] self.handles.append(Handle(**self.handleOptions[i])) self.controlObjects[i]=(self.handles[-1].transforms[-1]) if not mc.objExists(self.controlObjects[-1]): if 'name' not in self.handleOptions[-1] and 'n' not in self.handleOptions[-1]: self.handleOptions[-1]['n']=self.joints[1]+'_aimCtrl' if 'x' not in self.handleOptions[-1] and 'xform' not in self.handleOptions[-1]: self.handleOptions[-1]['x']=self.ctrlJoints[1] if 'aim' not in self.handleOptions[i] and 'a' not in self.handleOptions[i]: self.handleOptions[i]['aim']=self.poleVector self.handleOptions[-1]['parent']=self.group self.handleOptions[-1]['pointTo']=self.joints[1] self.handleOptions[-1]['aimAt']=self.joints[1] self.handles.append(Handle(**self.handleOptions[-1])) self.controlObjects[-1]=(self.handles[-1].transforms[-1]) mc.move\ ( poleOffset*(self.poleVector[0]), poleOffset*(self.poleVector[1]), poleOffset*(self.poleVector[2]), self.controlObjects[-1], r=True,os=True,wd=True ) # add and set control attributes mc.setAttr(self.controlObjects[-1]+'.v',k=False) for attr in ['.sx','.sy','.sz']: mc.setAttr(self.controlObjects[-1]+attr,l=True,k=False,cb=False) mc.setAttr(self.ikHandle+attr,l=True,k=False,cb=False) for attr in ['.rx','.ry','.rz']: mc.setAttr(self.controlObjects[-1]+attr,k=False,cb=False) for attr in ['.tx','.ty','.tz']: mc.setAttr(self.group+attr,l=True,k=False,cb=False) mc.setAttr(self.controlObjects[0]+attr,l=True,k=False,cb=False) mc.setAttr(self.ikHandle+'.v',k=False,cb=False) for attr in ['.tx','.ty','.tz']: mc.setAttr(self.controlObjects[1]+attr,l=True,k=False,cb=False) if not mc.objExists(self.controlObjects[-2]+'.twist'): mc.addAttr(self.controlObjects[-2],at='doubleAngle',ln='twist',k=True) if not mc.objExists(self.controlObjects[-2]+'.sway') and self.sway: mc.addAttr(self.controlObjects[-2],at='doubleAngle',ln='sway',k=1) if not mc.objExists(self.controlObjects[-2]+'.stretch'): mc.addAttr(self.controlObjects[-2],at='double',ln='stretch',k=1,dv=self.stretch,min=0) if not mc.objExists(self.controlObjects[-2]+'.squash'): mc.addAttr(self.controlObjects[-2],at='double',ln='squash',k=1,dv=self.squash,min=0,max=99) if not mc.objExists(self.controlObjects[-2]+'.ikSwitch'): mc.addAttr(self.controlObjects[-2],at='enum',ln='ikSwitch',en='ik:fk',k=True,dv=1)# if self.switch=='fk' else 0 #sway control if self.sway: adl=mc.createNode('addDoubleLinear') mc.connectAttr(self.ctrlJoints[1]+'.r'+self.poleAxis,adl+'.i1') mc.connectAttr(self.controlObjects[-2]+'.sway',adl+'.i2') childList=removeAll\ ( iterable(mc.listRelatives(self.joints[2],c=True,ad=True)), iterable(mc.listRelatives(self.joints[1],c=True,ad=True)) )+[self.joints[2],self.joints[1]] for c in childList: if mc.nodeType(c)=='transform' or mc.nodeType(c)=='joint': pc=mc.parentConstraint(c,q=True) nc=listNodeConnections(self.ctrlJoints[1],pc,s=True,d=True) for conn in nc: if conn[0]==self.ctrlJoints[1]+'.rotate': mc.disconnectAttr(conn[0],conn[1]) for a in removeAll(self.poleAxis,['x','y','z']): mc.connectAttr(conn[0]+a.upper(),conn[1]+a.upper(),f=True) mc.connectAttr(adl+'.o',conn[1]+self.poleAxis.upper(),f=True) # ik/fk switch for i in range(0,3): c=['r','g','b'][i] a=['x','y','z'][i] adl=mc.createNode('addDoubleLinear') mdl1=mc.createNode('multDoubleLinear') mc.setAttr(mdl1+'.i2',.01) mdl2=mc.createNode('multDoubleLinear') mc.setAttr(mdl2+'.i2',.01) revNode=mc.createNode('reverse') mc.setAttr(adl+'.i1',1) mc.connectAttr( mdl1+'.o',adl+'.i2') mc.connectAttr(self.controlObjects[-2]+'.stretch',mdl1+'.i1') mc.connectAttr( mdl2+'.o',revNode+'.ix') mc.connectAttr(self.controlObjects[-2]+'.squash',mdl2+'.i1') mc.connectAttr(adl+'.o',cn+'.mx'+c,f=True) mc.connectAttr(revNode+'.ox',cn+'.mn'+c,f=True) if not mc.objExists(self.controlObjects[-2]+'.zenPreviousIKState'): if self.switch=='fk': mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKState',k=0,dv=1) else: mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKState',k=0,dv=0) if not mc.objExists(self.controlObjects[-2]+'.zenPreviousIKParent'): if self.switch=='fk': mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKParent',k=0,dv=1) else: mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKParent',k=0,dv=0) for i in range(0,2): for c in mc.listRelatives(self.controlObjects[i],s=True): mc.connectAttr(self.controlObjects[-2]+'.ikSwitch',c+'.v') mc.connectAttr(self.controlObjects[-2]+'.twist',self.ikHandle+'.twist') rev=mc.createNode('reverse') mc.connectAttr(self.controlObjects[-2]+'.ikSwitch',rev+'.ix') mc.connectAttr(rev+'.ox',self.ikHandle+'.ikBlend') for c in mc.listRelatives(self.controlObjects[-1],s=True): mc.connectAttr(rev+'.ox',c+'.v') # parent spaces for i in [0,1,2]: if(mc.objExists(self.jointParent)and i in [0,2]): ParentSpace(self.controlObjects[i],self.jointParent) else: ParentSpace(self.controlObjects[i],self.controlObjects[i-1]) ParentSpace(self.controlObjects[-1],self.controlObjects[-2]) if mc.objExists(self.jointParent): ParentSpace(self.controlObjects[-1],self.jointParent).setParent(self.jointParent) ParentSpace(self.controlObjects[-2],self.jointParent).setParent(self.jointParent) else: ParentSpace(self.controlObjects[-1],self.controlObjects[0]) if self.switch=='fk': ParentSpace(self.controlObjects[2],self.controlObjects[1]) for co in self.controlObjects[2:]: freeze(co,t=True) mc.aimConstraint\ ( self.ctrlJoints[1],self.controlObjects[-1], aim=(self.aimVector[0],self.aimVector[1],self.aimVector[2]), wuo=self.ctrlJoints[1], wut='objectrotation', mo=True ) if mc.objExists(self.jointParent): mc.setAttr(self.controlObjects[0]+'.parentTo',l=True,k=False,cb=False) mc.setAttr(self.controlObjects[1]+'.parentTo',l=True,k=False,cb=False) #constraints orientConstraints=['','',''] for i in [2,1,0]: orientConstraints[i]=mc.orientConstraint(self.controlObjects[i],self.ctrlJoints[i],mo=True)[0] mc.setAttr(self.controlObjects[i]+'.v',k=False) for attr in ['.sx','.sy','.sz']: mc.setAttr(self.controlObjects[i]+attr,l=True,k=False,cb=False) if i==1: if not self.sway: mc.setAttr(self.controlObjects[i]+'.r'+self.poleAxis,l=True,k=False,cb=False) mc.setAttr(self.controlObjects[i]+'.r'+self.orientAxis,l=True,k=False,cb=False) self.poleVectorConstraint=mc.poleVectorConstraint(self.controlObjects[-1],self.ikHandle)[0] for oc in orientConstraints[:-1]: octl=mc.orientConstraint(oc,q=True,tl=True) ocwal=mc.orientConstraint(oc,q=True,wal=True) weightAlias=ocwal[octl.index(self.controlObjects[orientConstraints.index(oc)])] mc.connectAttr(self.controlObjects[-2]+'.ikSwitch',oc+'.'+weightAlias) mc.parent(self.ikHandle,self.controlObjects[2],r=False) if self.switch=='ik': mc.setAttr(self.controlObjects[-2]+'.ikSwitch',0) # link for asset detection if 'zenIkFkLimbCtrls' not in mc.listAttr(self.group): mc.addAttr(self.group,ln='zenIkFkLimbCtrls',at='message',m=True) if 'zenIkFkLimbCtrlJoints' not in mc.listAttr(self.group): mc.addAttr(self.group,ln='zenIkFkLimbCtrlJoints',at='message',m=True) for co in self.controlObjects: if 'zenCtrl' not in mc.listAttr(co): mc.addAttr(co,ln='zenCtrl',at='message') mc.connectAttr(co+'.zenCtrl',self.group+'.zenIkFkLimbCtrls['+str(firstOpenPlug(self.group+'.zenIkFkLimbCtrls'))+']') for cj in self.ctrlJoints: if 'zenCtrl' not in mc.listAttr(cj): mc.addAttr(cj,ln='zenCtrl',at='message') mc.connectAttr(cj+'.zenCtrl',self.group+'.zenIkFkLimbCtrlJoints['+str(firstOpenPlug(self.group+'.zenIkFkLimbCtrlJoints'))+']') for bp in self.bindPoses: for co in self.controlObjects: mc.dagPose(co,a=True,n=bp) self[:]=[self.group]+self.controlObjects mc.cycleCheck(e=True) mc.select(self[-2])
def __init__(self,*args,**keywords): #default options self.targets=[] self.origin='local' self.frontOfChain=True self.deleteTargets=False self.base=[] self.baseIndex=0 self.useExisting=True self.controlObjects=[] self.controlAttributes=[] self.before=False self.after=False self.name='blendShape#' self.goals=[] # use to specify exact goal weights for each target in each target list self.range=[[0,10]] # use to specify range of goals for each target self.weights=[0] self.prune=False self.baseIndex=0 self.createControlObject=False self.control=True # any of the following abbreviations can be substituted self.shortNames=\ { 'o':'origin', 'foc':'frontOfChain', 'dt':'deleteTargets', 'b':'base', 'ue':'useExisting', 'co':'controlObjects', 'control':'controlObjects', 'ca':'controlAttributes', 'n':'name', 'g':'goals', 'goal':'goals', 'gm':'goalMax', 'p':'prune', 'r':'range', 't':'targets', 'w':'weights', 'c':'control' } unusedKeys={} for k in keywords: if k in self.shortNames: exec('self.'+self.shortNames[k]+'=keywords[k]') elif k in self.__dict__: exec('self.'+k+'=keywords[k]') else: unusedKeys[k]=keywords[k] self.controlObjects=iterable(self.controlObjects) if not isIterable(self.range[0]): self.range=[self.range] if len(args)==0: args=mc.ls(sl=True) sel=[] for a in args: if isinstance(a,basestring) and mc.objExists(a) and mc.nodeType(a)=='blendShape': self.append(a) self.base=mc.blendShape(a,q=True,g=True) for i in range(0,len(self.base)): self.base[i]=shape(self.base[i]) break else: sel.append(a) if len(self.base)>self.baseIndex and mc.objExists(self.base[self.baseIndex]): self.targets.extend(removeAll([self[0],self.base[self.baseIndex]],sel)) else: self.targets.extend(sel[:-1]) self.base=[shape(args[-1])] if self.useExisting and len(self[:])==0: self.find() if len(self)==0: self.create() self.addTargets(**self.__dict__)
def __call__(self,*args,**keywords): # default options recursive=True applications=[] home=True roots=True path=[] pathRegularExpression=False searchPath=[] plugin=False isDirectory=False # keyword directory isFile=False # keyword file all=False each=False regularExpression=False shortNames=\ { 'a':'all', 'd':'isDirectory', 'directory':'isDirectory', 'dir':'isDirectory', 'p':'path', 'pre':'pathRegularExpression', 'f':'isFile', 'file':'isFile', 'ss':'smartSearch', 'sp':'searchPath', 're':'regularExpression', 'app':'applications', 'rec':'recursive', 'e':'each' } self.openWorkSpaces=[] self.openFiles=[] for k in keywords: if k in self.__dict__: exec('self.'+k+'=keywords[k]') elif k in locals(): exec(k+'=keywords[k]') elif k in self.shortNames: exec('self.'+self.shortNames[k]+'=keywords[k]') elif k in shortNames: exec(shortNames[k]+'=keywords[k]') sel=[] for a in args: sel.extend(iterable(a)) if not isDirectory and not isFile and len(sel)>0: if len(sel[0].split('.'))<2: isDirectory=True isFile=True if isinstance(applications,bool) and applications: applications=['*.*'] path=iterable(path) searchPath=iterable(searchPath) applications=iterable(applications) for p in searchPath: if '*' in p or not os.path.isdir(p): pathRegularExpression=True if len(applications)>0: pathRegularExpression=True if 'each' not in keywords and 'e' not in keywords: each=True filePaths=[] for s in sel: if '*' in s: regularExpression=True selRE=re.compile(s) f=[] searched=[] if len(applications)>0: searchPath=self.getProgramDirs(pre=pathRegularExpression,*applications) pathRegularExpression=False if len(searchPath)>0 and not pathRegularExpression: searchDirCmds=['searchPath'] elif s.split('.')[-1].split('*')[-1] in ['py','pyc','pyo']: searchDirCmds=['path','getReversed(sys.path)','self.getOpenFiles()','self.getOpenWorkSpaces()','self.getAllWorkSpaces()','self.getMelPath()','self.getProgramDirs('+str(applications)+',pre='+str(pathRegularExpression)+')'] elif s.split('.')[-1].split('*')[-1] in ['mel']: searchDirCmds=['path','self.getMelPath()','self.getOpenFiles()','self.getOpenWorkSpaces()','self.getAllWorkSpaces()','getReversed(sys.path)','self.getProgramDirs('+str(applications)+',pre='+str(pathRegularExpression)+')'] else: searchDirCmds=['path','self.getOpenFiles()','self.getOpenWorkSpaces()','self.getAllWorkSpaces()','getReversed(sys.path)','self.getMelPath()','self.getProgramDirs('+str(applications)+',pre='+str(pathRegularExpression)+')'] if home and not applications: searchDirCmds.append('self.getHomeDirs()') if roots and not applications: searchDirCmds.append('self.getRoots()') for sdCmd in searchDirCmds: searchDir=removeAll(searched,eval(sdCmd)) searched.extend(searchDir) while len(searchDir)>0 and (f==[] or all): sd=[] for d in searchDir: found=False matchDir=True if pathRegularExpression: matchDir=False for p in (searchPath+path): if type(re.compile(p).search(d+'/')).__name__!='NoneType': matchDir=True if matchDir: if s in d and os.path.exists(d) and os.access(d,os.F_OK): if d[-len(s):]==s: if\ ( (os.path.isfile(d) and isFile) or (os.path.isdir(d) and isDirectory) ): f.append(d.replace('\\','/')) found=True if not(all or each): break elif\ ( isDirectory and d[d.index(s)-1] in ['/','\\'] and d[d.index(s)+len(s)] in ['/','\\'] ): if os.path.isdir(d[:d.index(s)+len(s)]): f.append(d[:d.index(s)+len(s)].replace('\\','/')) found=True if not(all or each): break elif regularExpression and type(selRE.search(d)).__name__!='NoneType': if d[-len(selRE.search(d).group()):]==selRE.search(d).group(): if\ ( (os.path.isfile(d) and isFile) or (os.path.isdir(d) and isDirectory) ): f.append(d.replace('\\','/')) found=True if not(all or each): break if\ ( (all or not found) and os.path.isdir(d) and not(not(recursive) and (os.path.dirname(d) in searchPath or os.path.dirname(d) in path)) ): if d[-1] in ['/','\\']: d=d[:-1] try:#avoids acess denied errors for fn in iterable(os.listdir(d)): sd.append((d+'/'+fn).replace('\\','/')) except: pass searchDir[:]=sd[:] if f!=[] and not all: break filePaths.extend(iterable(f)) if len(filePaths)==0: self[:]=[] return [] else: self[:]=filePaths if len(filePaths)==1: return filePaths[0] else: return filePaths
def addParents(self, *args, **keywords): enumNames = [] shortNames = {"en": "enumNames"} for k in keywords: if k in locals(): exec(k + "=keywords[k]") if k in shortNames: exec(shortNames[k] + "=keywords[k]") enumNames = iterable(enumNames) parents = [] for a in args: parents.extend(iterable(a)) enumNames = parents baseNameRE = re.compile("(^[^0-9].*[^0-9])") i = len(enumNames) while len(enumNames) < len(parents): enumNames.append(baseNameRE.search(parents[i]).group()) i += 1 for i in range(0, len(parents)): p = parents[i] en = enumNames[i] if mc.objExists(str(mc.parentConstraint(self[0], q=True))) and p in iterable( mc.parentConstraint(mc.parentConstraint(self[0], q=True), q=True, tl=True) ): return self.parentConstraint = pc = mc.parentConstraint(p, self[0], mo=False)[0] self.scaleConstraint = sc = mc.scaleConstraint(p, self[0], mo=False)[0] if not mc.objExists(self.child + ".parentTo"): mc.addAttr(self.child, at="enum", ln="parentTo", en=en, k=True) else: mc.addAttr( self.child + ".parentTo", e=True, enumName=mc.addAttr(self.child + ".parentTo", q=True, enumName=True) + ":" + en, ) enumNum = len(removeAll("", mc.addAttr(self.child + ".parentTo", q=True, enumName=True).split(":"))) - 1 if enumNum == 0: enumNum = len(removeAll("", mc.addAttr(self.child + ".parentTo", q=True, enumName=True).split(";"))) - 1 parentWeightAttr = pc + "." + mc.parentConstraint(pc, q=True, wal=True)[-1] scaleWeightAttr = sc + "." + mc.scaleConstraint(sc, q=True, wal=True)[-1] cond = mc.createNode("condition", n="parentSpaceCond#") mc.connectAttr(self.child + ".parentTo", cond + ".ft") mc.setAttr(cond + ".st", enumNum) mc.setAttr(cond + ".op", 0) mc.setAttr(cond + ".ctr", 1) mc.setAttr(cond + ".cfr", 0) mc.connectAttr(cond + ".ocr", parentWeightAttr) mc.connectAttr(cond + ".ocr", scaleWeightAttr)
def deferExec(*args,**keywords): #defaults melCommand=False repeatable=True showErrors=True shortNames={ 'mel':'melCommand', 're':'repeatable', 'se':'showErrors' } if len(args)==0: return for k in keywords: if k in locals(): exec(k+'=keywords[k]') elif k in shortNames: exec(shortNames[k]+'=keywords[k]') zdc=MelGlobalVar('zenDelayedCommands') dcStr=zdc.get() if isinstance(dcStr,basestring): dc=dcStr.split(';') else: dcStr='' dc=[] dcsjVar=MelGlobalVar('zenDelayedCommandsSJ') dcsj=dcsjVar.get() if type(dcsj).__name__=='NoneType': dcsj='' for a in args: if not repeatable: dc.remove(a) if isinstance(a,basestring): if melCommand: dc.append(a) else: lines=a.split('\n') if len(lines)==1: dc.append('python('+melEncode(a)+')') else: pyCmd='python(\n' for l in lines: pyCmd+=melEncode(l+'\n')+'+\n' pyCmd=pyCmd[:-2]+')' dc.append(pyCmd) sjExists=False if isIterable(dc) and len(dc)>0 and isinstance(dcsj,(int,long,float)) and dcsj!=0 and mel.eval('scriptJob -ex '+str(dcsj)): sjExists=True dc=removeAll([''],dc) zdc.set(';'.join(dc)) if not(sjExists): cmd=( 'scriptJob \n'+ ' -ro true\n'+ ' -e "idle" \n'+ ' (\n'+ ' '+melEncode('string $zenDeferExec_errCmds[]={};\n')+'+\n'+ ' '+melEncode('for($c in (stringArrayRemoveDuplicates(stringToStringArray($zenDelayedCommands,\";\"))))\n')+'+\n'+ ' '+melEncode('{\n')+'+\n'+ ' '+melEncode(' if(catch(`eval($c)`)) $zenDeferExec_errCmds[size($zenDeferExec_errCmds)]=$c;\n')+'+\n'+ ' '+melEncode('}\n')+'+\n'+ ' '+melEncode('for($c in $zenDeferExec_errCmds) warning("errors encountered: \\n"+$c+"\\n");\n')+'+\n'+ ' '+melEncode('$zenDelayedCommands="";\n')+'+\n'+ ' '+melEncode('$zenDelayedCommandsSJ=0;\n')+'\n'+ ' )' ) dcsjVar.set(mel.eval(cmd))
def uniqueNames(*args,**keywords): """ With no keywords, returns a unique version of the given name(s). With re=True or raiseException=True : Ensures unique names are used in the scene and raises an error if there are duplicates present. With rn=True or rename=True : renames any object which have duplicate names. """ rename=False raiseException=False validate=False shortNames=\ { 'rn':'rename', 'v':'validate', 're':'raiseException' } for k in keywords: if k in locals(): exec(k+'=keywords[k]') elif k in shortNames: exec(shortNames[k]+'=keywords[k]') if len(args)==0: args=mc.ls(sl=True) if len(args)==0: args=mc.ls() sel=[] for a in args: sel.extend(iterable(a)) shapes=[] for s in sel: if mc.objExists(s) and shape(s)==s: shapes.append(s) sel=removeAll(shapes,sel)+shapes if validate: rename=False raiseException=False if rename: raiseException=False validate=False if raiseException: rename=False validate=False max=0 if rename or validate or raiseException: max=1 names=[] nonUnique=[] newNames={} baseNameRE=re.compile('(^[^0-9].*[^0-9])') for s in sel: sn=iterable(s.split('|'))[-1] ln=hierarchyOrder(removeDuplicates(mc.ls(sn,l=True)),r=True) if len(ln)>max: try: baseName=baseNameRE.match(sn).group(0) except: baseName=sn i=1 rn=s un=[] while mc.objExists(rn) or len(un)<len(ln): rn=baseName+str(i) if not mc.objExists(rn): un.append(rn) i+=1 names.append(un[0]) for i in range(0,len(ln)): if validate or rename: newNames[ln[i]]=un[i] if rename: mc.rename(ln[i],un[i]) else: nonUnique.append(ln[i]) else: names.append(s) if raiseException: if len(nonUnique)>0: print('##Non-unique names:##\n'+str(nonUnique)) raise Exception('Non-unique names found.') return nonUnique elif validate or rename: return newNames else: if len(sel)==1 and len(names)==1: return names[0] else: return names