def chipFacesTool(self): # cuts faces off of the poly and then seperates the faces to it's own polygon object, also ungroups them selectedFaces = self.getSelection() selectionParent = cmds.listRelatives(selectedFaces[0], p=True) cmds.polyChipOff( selectedFaces, dup=True) seperated = cmds.polySeparate(selectionParent[0]) allSeperated = [i for i in seperated if 'Separate' not in i] if len(allSeperated) > 2: cmds.polyUnite(allSeperated[1:]) new = self.getSelection() else: new = allSeperated[1] old = []; old.append(allSeperated[0]) oldParent = cmds.listRelatives(old[0], p=True) oldParentChildren = cmds.listRelatives(oldParent[0], c=True) oldNodesToDelete = set(old) ^ set(oldParentChildren) print oldNodesToDelete, ' this is old nodes to delete' cmds.ungroup( oldParent ) cmds.delete(new, ch=1) cmds.delete(old, ch=1) cmds.rename(old, oldParent ) cmds.select(new) self.assignRandomMaterial() # assigns random lambert to newly created poly cmds.delete(selectedFaces) cmds.select(old) cmds.xform(centerPivots = True) cmds.select(new) # reselect it after material assign cmds.xform(centerPivots = True) # Center pivot of new article. JR_rename_tool.UI('exit') # to rename the freshly branched poly
def extractFaces(self): """Extract faces""" # Get options sef = mc.checkBox("sef", query=True, value=True) dup = mc.checkBox("dup", query=True, value=True) kft = mc.checkBox("kft", query=True, value=True) off = mc.floatSliderGrp("off", query=True, value=True) ran = mc.floatSliderGrp("ran", query=True, value=True) t = mc.floatFieldGrp("t", query=True, value=True) ro = mc.floatFieldGrp("ro", query=True, value=True) s = mc.floatFieldGrp("s", query=True, value=True) lt = mc.floatFieldGrp("lt", query=True, value=True) lr = mc.floatFieldGrp("lr", query=True, value=True) ls = mc.floatFieldGrp("ls", query=True, value=True) # Perform extraction mc.polyChipOff(duplicate=dup, keepFacesTogether=kft, offset=off, random=ran, translate=t, rotate=ro, scale=s, localTranslate=lt, localRotate=lr, localScale=ls) # Separate if sef: mel.eval("SelectToggleMode; performPolyShellSeparate();")
def chipFacesTool(self): # cuts faces off of the poly and then seperates the faces to it's own polygon object, also ungroups them selectedFaces = self.getSelection() selectionParent = cmds.listRelatives(selectedFaces[0], p=True) cmds.polyChipOff(selectedFaces, dup=True) seperated = cmds.polySeparate(selectionParent[0]) allSeperated = [i for i in seperated if 'Separate' not in i] if len(allSeperated) > 2: cmds.polyUnite(allSeperated[1:]) new = self.getSelection() else: new = allSeperated[1] old = [] old.append(allSeperated[0]) oldParent = cmds.listRelatives(old[0], p=True) oldParentChildren = cmds.listRelatives(oldParent[0], c=True) oldNodesToDelete = set(old) ^ set(oldParentChildren) print oldNodesToDelete, ' this is old nodes to delete' cmds.ungroup(oldParent) cmds.delete(new, ch=1) cmds.delete(old, ch=1) cmds.rename(old, oldParent) cmds.select(new) self.assignRandomMaterial( ) # assigns random lambert to newly created poly cmds.delete(selectedFaces) cmds.select(old) cmds.xform(centerPivots=True) cmds.select(new) # reselect it after material assign cmds.xform(centerPivots=True) # Center pivot of new article. JR_rename_tool.UI('exit') # to rename the freshly branched poly
def CreateBushes(self, posX=0, posZ=0): brushesBase = cmds.polyPrimitive(r=0.4, pt=0)[0] cmds.polyChipOff(dup=False, kft=False) cmds.polyChipOff(dup=False, kft=True, ltz=0.1, ran=1.0) cmds.polyExtrudeFacet(ltz=0.2) cmds.polySmooth() cmds.polySeparate() cmds.xform(cp=True) for leaf in cmds.ls(sl=True): leafScale = round(random.uniform(2, 2.5), 3) cmds.select(leaf) cmds.polySoftEdge(a=0, name=leaf) cmds.scale(leafScale, leafScale, leafScale) leafPosition = cmds.xform(leaf, q=True, rp=True, ws=True) if leafPosition[1] < 0: cmds.delete(leaf) else: cmds.xform(leaf, t=leafPosition, ws=True) self.SetRandomLeafColor(leaf) cmds.setAttr(brushesBase + ".translateX", posX) cmds.setAttr(brushesBase + ".translateZ", posZ) return cmds.rename(brushesBase, 'Bushes#')
def hfSplitBadShaded(self, engines): modifiedShapes = [] for sg in engines: print('checking shading group: '+sg) cmds.hyperShade(objects=sg) components = cmds.ls(sl=1) uniqueShapes = [] for entry in components: uniqueShapes.append(entry.split('.')[0]) # remove whole shapes (not components) from the list. if entry.rfind('.f') == -1: components.remove(entry) if len(components) > 0: components.sort() # remove duplicates from uniqueShapes. uniqueShapes = list(set(uniqueShapes)) modifiedShapes.extend(uniqueShapes) # print('\nunique shapes under shading group: ') # print(uniqueShapes) for shape in uniqueShapes: cmds.select(cl=1) # get the total num of faces for the shape for later use. totalFaces = cmds.polyEvaluate(shape, f=1) for comp in components: testStr = shape+'.f[' if testStr in comp: # the current component is a member of the current mesh we're splitting and it has the shader we want. cmds.select(comp, add=1) selFaces = cmds.ls(sl=1) # print 'selection:' # print selFaces # extract the selected faces if we aren't selecting every face of the current mesh. if len(selFaces) < int(totalFaces) and len(selFaces) > 0: cmds.polyChipOff(selFaces, kft=1, dup=0) cmds.delete(shape,ch=1) # now the mesh is broken into shells. separate it if possible. if cmds.polyEvaluate(shape, s=1) > 1: newObjects = cmds.polySeparate(shape, ch=0) modifiedShapes.extend(newObjects) # print('split new shapes: ') # print(newObjects) cmds.select(newObjects) # print(cmds.ls(sl=1)) cmds.delete(ch=1) cmds.select(cl=1) # now in order to return all the new meshes we made, we should sort through uniqueShapes and remove anything that no longer # exists. anything that's been split, etc. modifiedShapes = list(set(modifiedShapes)) returnShapes = [] for shape in modifiedShapes: if cmds.objExists(shape) == 0: modifiedShapes.remove(shape) else: meshNodes = cmds.listRelatives(shape, s=1) if meshNodes != None: # if we are not testing an xform, meshNodes will be a 'NoneType' object so we should include an exception. returnShapes.extend(meshNodes) return returnShapes
def Chop(*args): curSel = cmds.ls(sl=True) if (len(curSel) > 0): cmds.polyChipOff(ch=1, kft=1, dup=0, off=0) gotoObjectmod() cmds.polySeparate() else: print "nothing selected, please select faces"
def separateIntoPlanarElements(name): # Use the automatic UV tool to do the heavy lifting in breaking up the 3d mesh for us cmds.polyAutoProjection('%s.f[0:%i]' % (name, cmds.polyEvaluate(name, f=True)), o=1, p=12) shells = getUVShells(name) for shell in shells: cmds.polyChipOff(shell) elements = cmds.polySeparate( name )[:-1] cmds.delete(elements[0]) # Delete the duplicate mesh return elements[1:]
def hfSplitBadShaded(engines): modifiedShapes = [] for sg in engines: print('checking shading group: ' + sg) cmds.hyperShade(objects=sg) components = cmds.ls(sl=1) uniqueShapes = [] for entry in components: uniqueShapes.append(entry.split('.')[0]) # remove whole shapes (not components) from the list. if entry.rfind('.f') == -1: components.remove(entry) if len(components) > 0: components.sort() # remove duplicates from uniqueShapes. uniqueShapes = list(set(uniqueShapes)) modifiedShapes.extend(uniqueShapes) # print('\nunique shapes under shading group: ') # print(uniqueShapes) for shape in uniqueShapes: cmds.select(cl=1) # get the total num of faces for the shape for later use. totalFaces = cmds.polyEvaluate(shape, f=1) for comp in components: if comp.rfind(shape) != -1: # the current component is a member of the current mesh we're splitting and it has the shader we want. cmds.select(comp, add=1) selFaces = cmds.ls(sl=1) # extract the selected faces if we aren't selecting every face of the current mesh. if len(selFaces) < int(totalFaces) and len(selFaces) > 0: cmds.polyChipOff(selFaces, kft=1, dup=0) cmds.delete(shape, ch=1) # now the mesh is broken into shells. separate it if possible. if cmds.polyEvaluate(shape, s=1) > 1: newObjects = cmds.polySeparate(shape, ch=0) modifiedShapes.extend(newObjects) # print('split new shapes: ') # print(newObjects) cmds.select(newObjects) # print(cmds.ls(sl=1)) cmds.delete(ch=1) cmds.select(cl=1) # now in order to return all the new meshes we made, we should sort through uniqueShapes and remove anything that no longer # exists. anything that's been split, etc. modifiedShapes = list(set(modifiedShapes)) returnShapes = [] for shape in modifiedShapes: if cmds.objExists(shape) == 0: modifiedShapes.remove(shape) meshNodes = cmds.listRelatives(shape, s=1) if meshNodes != None: # if we are not testing an xform, meshNodes will be a 'NoneType' object so we should include an exception. returnShapes.extend(meshNodes) # we're going to get a list of xforms here. we should build a list of shapes and return that for the cleanup op. # print('modified shapes: ') # print(returnShapes) return returnShapes
def separateByVertexBrightness(name): meshDuplicate = cmds.duplicate(name, rr=True)[0] layers = parseMeshVertexColour(meshDuplicate) faceLayers = convertVtxToFace(layers, meshDuplicate) for faceSelection in faceLayers: if faceSelection: cmds.polyChipOff(faceSelection, ran=True) # if faceSelection: # for island in separateIntoPlanarElements(faceSelection): # cmds.geomToBBox(island) return faceLayers
def createChunksFromGeo(self, currHair, loopDict): import pprint as pp hairChunksGRP = cmds.createNode("transform", name="{0}_hairChunksGeo_GRP".format( currHair.name())) deleted = False newHair = None justIndexDict = {} for edge in sorted(loopDict.keys()): justIndex = [] for v in loopDict[edge]: justIndex.append(v.index()) justIndexDict[edge] = justIndex for edge in sorted(justIndexDict.keys()): if int(edge) + 1 >= len(justIndexDict): continue if deleted: currHair = pym.PyNode(newHair) hairShape = currHair.getShape().name() hairName = currHair.name() firstLoop = [] secondLoop = [] for vtx in justIndexDict[edge]: firstLoop.append(pym.MeshVertex(currHair, vtx)) for vtx in justIndexDict['{:04d}'.format(int(edge) + 1)]: secondLoop.append(pym.MeshVertex(currHair, vtx)) pym.select(firstLoop + secondLoop) cmds.ConvertSelectionToContainedFaces() cmds.polyChipOff(ch=1, kft=1, dup=1, off=0) hairPieces = cmds.polySeparate(hairShape, rs=1, ch=1) for i in hairPieces: cmds.DeleteHistory(i) cmds.parent(hairPieces[1], hairChunksGRP) cmds.rename(hairPieces[1], "{0}_piece_{1}".format(hairName, edge)) deletable, = cmds.listRelatives(hairPieces[0], p=1) cmds.parent(hairPieces[0], w=1) cmds.delete(deletable) newHair = cmds.rename(hairPieces[0], hairName) deleted = True return hairChunksGRP, newHair
def makeWindows(self, name_, windowShaders, booleans): ''' Creates windows for a cylinder or pipe house. self: Object of the class House. name_: A string with the name the polygonal house object will have. windowShader: A list with shaders for the windows. booleans: A boolean variable which determines whether the windows should be combined with the house using boolean difference or not. On exit: Columns of windows are created using makeWindowColumn(...) and these are then duplicated around the house. The windows are assigned shaders using assignWindowShaders(...), and are then combined with the house. The House object's name attribute is updated. ''' windowHeight = random.uniform(0.5,1.9) # Make sure the window height is not too close to 1.6 since the window edge # in that case will be too close to a edge loop on the house and the boolean # operation will fail. if booleans and (windowHeight > 1.59 and windowHeight < 1.61): windowHeight = random.choice([1.59, 1.61]) floorHeight = int(math.ceil(windowHeight)) heightNum = int((self.height - (1 + floorHeight/2.0))/floorHeight) if heightNum == 0: return angleR = 2.0 * math.pi / self.sides angleD = math.degrees(angleR) distance = math.cos(angleR / 2.0) * self.radius sideWidth = 2.0 * self.radius * math.sin(angleR / 2.0) windowWidth = random.uniform((sideWidth -0.2)/ 2.0, sideWidth - 0.2) if windowWidth <= 0.1: return windowColumn = makeWindowColumn(windowWidth, windowHeight, heightNum, floorHeight) cmds.rotate(90 - angleD / 2.0, windowColumn[0], y = True) for j in range(self.sides): # Copy the column faces around the house. cmds.polyChipOff(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]", dup = True, kft = True, translate = (math.sin(math.pi/2.0 - angleR/2.0 + angleR * j) * distance,0,math.cos(math.pi/2.0 - angleR/2.0 + angleR * j) * distance)) cmds.select(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]") cmds.rotate(angleD, y = True) cmds.delete(all = True, ch = True) cmds.refresh() cmds.delete(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]") windowNum = self.sides * heightNum assignWindowShaders(windowColumn, windowNum, windowShaders) cmds.select(windowColumn[0] + ".f[0:" + str(windowNum * 6 - 1) +"]") cmds.polySubdivideFacet() if booleans == True: result = cmds.polyBoolOp(self.name,windowColumn[0], op = 2, n = name_) else: result = cmds.polyUnite(self.name,windowColumn[0], n = name_) self.name = result[0] cmds.delete(all = True, ch = True)
def quickTest(testType='mesh'): targetMesh = cmds.ls(sl=True)[0] if testType == 'mesh': testMesh(0.1, targetMesh) else: sourcePlane = cmds.polyChipOff('%s.f[0]'%targetMesh, duplicate=True) testPlanes(0.1, sourcePlane, targetMesh)
def makeWindowColumn(windowWidth, windowHeight, num, floorHeight): ''' Creates a column with the specified number of windows. windowWidth: The width of the windows. windowHeight: The height of the windows. num = The number of windows in the column. floorHeight: The height of one floor. On exit: A column of windows of the given size has been created. ''' window = cmds.polyCube(w = windowWidth, h = windowHeight, d = 0.1) cmds.xform(window, translation = (0, 0.8 + floorHeight,0)) for i in range(1,num): cmds.polyChipOff(window[0] + ".f[0:5]", dup = True, kft = True, translate = (0,(i * floorHeight),0)) cmds.delete(all = True, ch = True) cmds.refresh() return window
def extract_part(self, mesh, polycount): # grow selection cmds.select(mesh+'.f[1]') while cmds.polyEvaluate(tc=True) < polycount: mel.eval('GrowPolygonSelectionRegion;') # extract cmds.polyChipOff(ch=False, kft=True, dup=False, off=False) parts = cmds.polySeparate(mesh, ch=False) # select the mesh with the higher polycount nodes = {} for part in parts: nodes[mesh+'|'+part] = cmds.polyEvaluate(part, f=True) sortList = nodes.values() sortList.sort() key = [key for key in nodes.keys() if nodes[key] == sortList[-1]] cmds.select(key) # return created parts return nodes.keys()
def subtract(self, other): if self.mayaBB is not None and other.mayaBB is not None: #separate cmd.polyChipOff(self.mayaBB + '.f[0:1]', ch=0, kft=1, dup=0, off=0) tempBBPieces = cmd.polySeparate(self.mayaBB, ch=0) #bool cutter = cmd.duplicate(other.mayaBB)[0] tempBBPieces[0] = mel.eval( 'polyCBoolOp -op 2 -ch 0 -classification 2 %s %s' % (tempBBPieces[0], cutter)) cutter = cmd.duplicate(other.mayaBB)[0] tempBBPieces[1] = mel.eval( 'polyCBoolOp -op 2 -ch 0 -classification 2 %s %s' % (tempBBPieces[1], cutter)) #combine self.mayaBB = cmd.polyUnite(tempBBPieces[0], tempBBPieces[1], ch=0, n=self.mayaBB)[0]
def seperateGeo(*args): geo = cmds.ls(sl=True)[0] shape = cmds.listRelatives(geo, type="mesh")[0] SGs = list(set(cmds.listConnections(shape, type="shadingEngine"))) for SG in SGs: cmds.select(SG) cmds.polyChipOff(ch=True, kft=True, dup=False) cmds.polySeparate(shape, ch=False) partitionGeos = cmds.listRelatives(geo, c=True, type="transform") for pGeo in partitionGeos: pShape = cmds.listRelatives(pGeo, type="mesh")[0] pSG = cmds.listConnections(pShape, type="shadingEngine")[0] cmds.rename(pGeo, pSG.replace("_lambertSG", "_geo"))
def CreateLeaves(self, height, minSize, maxSize): leafBase = cmds.polyPrimitive(r=1, l=1, pt=0)[0] cmds.move(height, y=True) cmds.polyChipOff(dup=False, kft=False) cmds.polyChipOff(dup=False, kft=True, ltz=0.08, ran=1.0) cmds.polyExtrudeFacet(ltz=0.6) cmds.polySmooth() cmds.polySeparate() cmds.xform(cp=True) for leaf in cmds.ls(sl=True): leafScale = round(random.uniform(minSize, maxSize), 3) cmds.select(leaf) cmds.polySoftEdge(a=0, name=leaf) cmds.scale(leafScale, leafScale, leafScale) leafPosition = cmds.xform(leaf, q=True, rp=True, ws=True) leafPosition[1] = height + 0.5 * (height - leafPosition[1]) cmds.xform(leaf, t=leafPosition, ws=True) self.SetRandomLeafColor(leaf) return leafBase
def makeTrafficLight(glow): ''' Creates a traffic light. glow: String that determines what colour should be glowing on the traffic light. Valid values are "R", "G", "Y" and "RY". On exit: A traffic light has been created and the right shaders have been assigned to it. The traffic light polygonal object is returned as a tuple containing the object name and node name. ''' pole = cmds.polyCube(n = "pole", w = 0.1,d = 0.1, h = 2) cmds.xform(pole, translation = (0, 1, 0)) cmds.sets(pole[0], edit=True, forceElement="blackMetalGroup") box = cmds.polyCube(n = "box", w = 0.3, d = 0.3, h = 0.7) cmds.xform(box, translation = (0, 2.35, 0)) cmds.sets(box[0], edit=True, forceElement="blackMetalGroup") lights = cmds.polyCylinder(n = "light", r = 0.1, h = 0.2, sx = 12) cmds.xform(lights, rotation = (90, 0, 0)) cmds.xform(lights, translation = (0, 2.575, 0.15), ws = True) cmds.polyChipOff(lights[0] + ".f[0:13]" , dup = True, kft = True, translate = (0, -0.225,0)) cmds.polyChipOff(lights[0] + ".f[0:13]" , dup = True, kft = True, translate = (0, -0.45,0)) if glow == "R" or glow == "RY": cmds.sets(lights[0] + ".f[0:13]", edit=True, forceElement="redLightGroup") else: cmds.sets(lights[0] + ".f[0:13]", edit=True, forceElement="redGroup") if glow == "Y" or glow == "RY": cmds.sets(lights[0] + ".f[14:27]", edit=True, forceElement="yellowLightGroup") else: cmds.sets(lights[0] + ".f[14:27]", edit=True, forceElement="yellowGroup") if glow == "G": cmds.sets(lights[0] + ".f[28:43]", edit=True, forceElement="greenLightGroup") else: cmds.sets(lights[0] + ".f[28:43]", edit=True, forceElement="greenGroup") trafficLight = cmds.polyBoolOp(box[0], lights[0], op = 2) trafficLight = cmds.polyUnite(trafficLight[0], pole[0], n = "trafficLight") cmds.delete(trafficLight[0], ch = True) return trafficLight
def snowyObj(): snowyFaces = mc.ls(sl=1) objName = snowyFaces[0].split(".")[0] faceNum = mc.polyEvaluate(objName, f=True) mc.duplicate(objName) mc.polyChipOff(snowyFaces[:], dup=True, kft=True, ch=True) mc.delete(objName + ".f[:" + str(faceNum-1) + "]") # create emmiter from surface emitter = mc.emitter( objName, n=objName + "_emitter" , typ = "surface", r=5000, sro=0, nuv=0, cye='none', cyi=1, spd=0, srn=0, nsp=1, tsp=0, mxd=0, mnd=0, dx=1, dy=0, dz=0, sp=0) particle = mc.nParticle( n = objName + "_nParticles" ) mc.connectDynamic( particle, em = emitter) NucleusList = mc.ls(type='nucleus') mc.setAttr(NucleusList[0] + ".gravity", 0) #parameter setting global snowParticleShape snowParticleShape = objName + "_nParticlesShape" mc.setAttr(objName + "_nParticlesShape" + '.dynamicsWeight', 0) mc.setAttr(objName + "_nParticlesShape" + '.conserve', 0) mc.setAttr(objName + "_nParticlesShape" + '.radius', 0.1) mc.setAttr(objName + "_nParticlesShape" + '.radiusScaleRandomize', 0.5) mc.setAttr(objName + "_nParticlesShape" + '.particleRenderType', 3) mc.setAttr(objName + "_nParticlesShape" + '.blobbyRadiusScale', 1.8) mc.setAttr(objName + "_nParticlesShape" + '.meshTriangleSize', 0.2) # set to quad shape mc.setAttr(objName + "_nParticlesShape" + '.meshMethod', 3) #smoothing snow polygon mc.setAttr(objName + "_nParticlesShape" + '.meshSmoothingIterations', 8) mc.select(objName + "_nParticles", r=True) snowPolygon = mm.eval("particleToPoly")
def skinInsideFaces(insideFaceList): """ Copy skinCluster weights to inside faces from the outside faces of the same mesh. insideFaceList @param insideFaceList: List of inside faces to copy skinWeights to. @type insideFaceList: list """ # Get Component List By Object objFaceList = glTools.utils.selection.componentListByObject(insideFaceList) # For Each for objFaces in objFaceList: # Get Source Mesh mesh = cmds.ls(objFaces[0], o=True)[0] # Get Face ID List faceIds = glTools.utils.component.getSingleIndexComponentList(objFaces) faceIds = faceIds[faceIds.keys()[0]] # Duplicate Original Mesh mesh_dup = cmds.duplicate(mesh)[0] mesh_dup_children = cmds.ls(cmds.listRelatives(mesh_dup, c=True), transforms=True) if mesh_dup_children: cmds.delete(mesh_dup_children) # Extract Faces from Duplicate faces = [mesh_dup + '.f[' + str(i) + ']' for i in faceIds] extract = cmds.polyChipOff(faces, dup=False, ch=False) separate = cmds.polySeparate(mesh_dup, ch=False) # Transfer Weights to Extracted Mesh copyToMany(mesh, [separate[0]]) copyToMany(separate[0], [separate[1]]) # Transfer Weights from Extracted Mesh srcSkin = glTools.utils.skinCluster.findRelatedSkinCluster(separate[1]) skinData = glTools.data.skinClusterData.SkinClusterData(srcSkin) skinData.remapGeometry(mesh) skinData.rebuildWorldSpaceData(mesh) # Apply Transferred Weights vtxList = cmds.polyListComponentConversion(objFaces, fromFace=True, toVertex=True, internal=False) skinData.loadWeights(componentList=vtxList) # Clean Up cmds.delete(mesh_dup)
def main(): facecluster=[] dupobject=[] #return null if no target object specified if maya.textScrollList(targetObjBox,q=True,si=True)==None: return selectface=processFaceSelection() #if not select face, return null if selectface==None: return if maya.radioButtonGrp(snapModeButton,q=True,sl=True)==2: duplicateMode=True grp_dupObj=maya.group(n='grp_dup_transform',em=True) else: duplicateMode=False targetObj=maya.textScrollList(targetObjBox,q=True,si=True)[0] objectname=selectface[0].split('.')[0] #print objectname for com in selectface: #print com if duplicateMode==True: dup_targetObj=maya.duplicate(targetObj,n='dup_'+targetObj) maya.parent(dup_targetObj,grp_dupObj) dup_object=maya.duplicate(objectname,n='dup_'+objectname) dupobject.append(dup_object[0]) #print dupobject raw_data=maya.polyInfo(com,fv=True)[0] #print raw_data #data processing raw_verindex=raw_data.split(':')[1] #print raw_verindex verindex=[] ver_all=raw_verindex.split(' ') #print ver_all for ver in ver_all: if ver != ''and ver != '\n': verindex.append(ver) #print verindex for ver in verindex: #print objectname cluster_temp=maya.cluster(objectname+'.vtx[{0}]'.format(ver),en=True,rel=True) if duplicateMode==True: maya.pointConstraint(cluster_temp,dup_targetObj,o=(0,0,0)) else: maya.pointConstraint(cluster_temp,targetObj,o=(0,0,0)) facecluster.append(cluster_temp) #print facecluster maya.polyChipOff(dup_object[0]+'.'+com.split('.')[1],kft=True,dup=True,off=0,ch=True) grp_obj=maya.polySeparate(dup_object,o=True,n='seperate_'+dup_object[0]) if duplicateMode==True: maya.normalConstraint(grp_obj[1],dup_targetObj,aim=(0,1,0),u=(1,0,0),wut='vector') else: maya.normalConstraint(grp_obj[1],targetObj,aim=(0,1,0),u=(1,0,0),wut='vector') #print T_channel_keyable #print R_channel_keyable if T_channel_keyable: maya.setKeyframe(targetObj,at='translataeX') maya.setKeyframe(targetObj,at='translateY') maya.setKeyframe(targetObj,at='translateZ') maya.delete(targetObj+'_pointConstraint*') if R_channel_keyable: maya.setKeyframe(targetObj,at='rotateX') maya.setKeyframe(targetObj,at='rotateY') maya.setKeyframe(targetObj,at='rotateZ') maya.delete(targetObj+'_normalConstraint*') #print facecluster for cluster in facecluster: #not sure here which to delete?? maya.delete(cluster) for dupObj in dupobject: maya.delete(dupObj)
def cleanupNonManifoldGeometry(self, normals = True): ## Get all the mesh that has mentalraySubdivApprox connected and has non-manifold problem # subdiv_mesh = [cmds.listRelatives(mesh, parent = True, fullPath = True)[0] for mesh in cmds.ls(type = 'mesh') if cmds.listConnections(mesh, type = 'mentalraySubdivApprox') if cmds.polyInfo(mesh, nme = True) or cmds.polyInfo(nmv = True)] subdiv_mesh = [cmds.listRelatives(mesh, parent = True, fullPath = True)[0] for mesh in cmds.ls(type = 'mesh') if cmds.polyInfo(mesh, nme = True) or cmds.polyInfo(nmv = True)] subdiv_mesh = list( set( subdiv_mesh ) ) if subdiv_mesh: for each in subdiv_mesh: ## Make sure we do indeed have nonmanifold geometry ## nonManifold = cmds.polyInfo(each, nmv = True, nme = True) if nonManifold: proceed = cmds.confirmDialog(title = 'Non-Manifold Geometry!', message = 'Geo Name:\n%s' % each, button = ['Cleanup!', 'Skip...'], defaultButton = 'Skip...', cancelButton = 'Skip...', dismissString = 'Skip...') if proceed == 'Cleanup!': ## Conform the geo and see if that gets rid of all the nonmanifold bits ## if normals: cmds.polyNormal('%s.f[*]' % each, normalMode = 2, constructionHistory = True) edges = cmds.polyInfo(each, nme = True) if cmds.polyInfo(each, nme = True) else [] vertices = [] if edges else cmds.polyInfo(each, nmv = True) lastEdges = [] lastVertices = [] while ( not self.arraysMatch(lastEdges, edges) or not self.arraysMatch(lastVertices, vertices) ) and ( edges or vertices ): ## Remember what was nonmanifold last time ## lastEdges = edges lastVertices = vertices ## Split any nonmanifold edges ## if edges: cmds.polySplitEdge(edges, constructionHistory = True) vertices = cmds.polyInfo(each, nmv = True) edges = [] ## Split any remaining nonmanifold vertices ## if vertices: cmds.polySplitVertex(vertices, constructionHistory = True) vertices = [] ## Now check to see if the object is still nonmanifold ## nonManifold = cmds.polyInfo(each, nmv = True, nme = True) if nonManifold: ## Chip off the faces ## nonManifoldFaces = cmds.polyListComponentConversion(nonManifold, toFace = True) cmds.polyChipOff(nonManifoldFaces, kft = 0, dup = 0, constructionHistory = True) ## And then check for nonmanifold bits again ## edges = cmds.polyInfo(each, nme = True) if not edges: vertices = cmds.polyInfo(each, nmv = True) ## Check to see if we failed to cleanup if edges or vertices: cmds.warning('Failed to cleanup non-manifold geometry of %s...' % each)
cmds.select(cmds.polyListComponentConversion(['%s.vtx[%i]'%(meshDuplicate,vtx) for vtx in layers[-1]], fv=True, tf=True, vfa=True)) #randomly distribute meshes using ratios of density:amount for layer in layers: #density[i] = int(ratios[i] * objCount) if layer: print layer # Break off the vertex colour islands into separate objects faceSelection = cmds.polyListComponentConversion(['%s.vtx[%i]'%(meshDuplicate,vtx) for vtx in layer], fv=True, tf=True, internal=True) """ Edge case """ # If only a less than 4 vertices are selected, the internal flag will mean faceSelection selects nothing # Could check if these vertices are involved with any other layer (internal causes problems if it's turned off) if faceSelection: cmds.select(faceSelection) cmds.polyChipOff(faceSelection, dup=True) faceIslands = ObjectScatter.separateIntoPlanarElements(meshDuplicate)[1:] thisSet = cmds.sets(n='Ratio_%i'%i) for face in faceIslands: #cmds.geomToBBox(face, ko=True,shaderColor=[1,0.5,0.043],n="%s_bbox_%i_#"%(surface,i)) cmds.sets(cmds.geomToBBox(face, ko=True,shaderColor=[1,0.5,0.043],n="%s_bbox_%i_#"%(face,i)), add=thisSet) # The last item is the name of the polySeparate node, this is not needed so we discard it #separatedFaces = cmds.polySeparate( meshDuplicate )[:-1] #duplicatedObj, elements = separatedFaces[0], separatedFaces[1:] #cmds.delete(duplicatedObj) cmds.delete(meshDuplicate)
def makeWindows(self, name_, windowShaders, booleans): ''' Creates windows for a box house. self: Object of the class BoxHouse. name_: A string with the name the house will have. windowShader: A list with shaders for the windows. booleans: A boolean variable which determines whether the windows should be combined with the house using boolean difference or not. On exit: Columns of windows are created using makeWindowColumn(...) and these are then duplicated around the house. The windows are assigned shaders using assignWindowShaders(...), and are then combined with the house. The House object's name attribute is updated. ''' windowHeight = random.uniform(0.5,1.9) # Make sure the window height is not too close to 1.6 since the window edge # in that case will be too close to a edge loop on the house and the boolean # operation will fail. if booleans and (windowHeight > 1.59 and windowHeight < 1.61): windowHeight = random.choice([1.59, 1.61]) windowWidth = random.uniform(1, 3) floorHeight = int(math.ceil(windowHeight)) heightNum = max(0,int((self.height - (1 + floorHeight/2.0))/floorHeight)) if heightNum == 0: return widthNum = max(0,int((self.width - 0.3) / (windowWidth))) if (widthNum != 0): # Makes it possible for houses to have less windows or no windows on a side. widthNum = widthNum - random.randint(0, min(2, widthNum)) # Space between window columns along the width of the house. widthSpace = (self.width - (widthNum * windowWidth)) /(widthNum + 1) depthNum = max(0,int((self.depth - 0.3)/ windowWidth)) if (depthNum != 0): # Makes it possible for houses to have less windows or no windows on a side. depthNum = depthNum - random.randint(0, min(2, depthNum)) if (depthNum == 0) and (widthNum == 0): return # Space between window columns along the width of the house. depthSpace = (self.depth - (depthNum * windowWidth)) / (depthNum + 1) windowColumn = makeWindowColumn(windowWidth,windowHeight, heightNum, floorHeight) for j in range(widthNum): # Duplicates all the faces of the first window column and translates the duplicates along the width. cmds.polyChipOff(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]", dup = True, kft = True, translate = (-self.width/2.0 + windowWidth/2.0 + widthSpace + (windowWidth + widthSpace) * j, 0, self.depth/2.0)) cmds.polyChipOff(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]", dup = True, kft = True, translate = (-self.width/2.0 + windowWidth/2.0 + widthSpace + (windowWidth + widthSpace) * j, 0, -self.depth/2.0)) cmds.delete(all = True, ch = True) cmds.refresh() cmds.select(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]") cmds.rotate(90, y = True) for j in range(depthNum): # Duplicates all the faces of the first window column and translates the duplicates along the depth. cmds.polyChipOff(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]", dup = True, kft = True, translate = (self.width/2.0, 0, -self.depth/2.0 + windowWidth/2.0 + depthSpace + (windowWidth + depthSpace) * j), ws = True) cmds.polyChipOff(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]", dup = True, kft = True, translate = (-self.width/2.0, 0, -self.depth/2.0 + windowWidth/2.0 + depthSpace + (windowWidth + depthSpace) * j), ws = True) cmds.delete(all = True, ch = True) cmds.refresh() cmds.select(windowColumn[0] + ".f[0:" + str((heightNum * 6) - 1) + "]") cmds.delete() windowNum = widthNum * heightNum * 2 + depthNum * heightNum * 2 # Total number of windows. assignWindowShaders(windowColumn, windowNum, windowShaders) cmds.select(windowColumn[0] + ".f[0:" + str(windowNum * 6 - 1) +"]") cmds.polySubdivideFacet() if booleans: result = cmds.polyBoolOp(self.name,windowColumn[0], op = 2, n = name_) else: result = cmds.polyUnite(self.name,windowColumn[0], n = name_) self.name = result[0] cmds.delete(self.name, ch = True)
def cleanupNonManifoldGeometry(self, normals=True): ## Get all the mesh that has mentalraySubdivApprox connected and has non-manifold problem # subdiv_mesh = [cmds.listRelatives(mesh, parent = True, fullPath = True)[0] for mesh in cmds.ls(type = 'mesh') if cmds.listConnections(mesh, type = 'mentalraySubdivApprox') if cmds.polyInfo(mesh, nme = True) or cmds.polyInfo(nmv = True)] subdiv_mesh = [ cmds.listRelatives(mesh, parent=True, fullPath=True)[0] for mesh in cmds.ls(type='mesh') if cmds.polyInfo(mesh, nme=True) or cmds.polyInfo(nmv=True) ] subdiv_mesh = list(set(subdiv_mesh)) if subdiv_mesh: for each in subdiv_mesh: ## Make sure we do indeed have nonmanifold geometry ## nonManifold = cmds.polyInfo(each, nmv=True, nme=True) if nonManifold: proceed = cmds.confirmDialog( title='Non-Manifold Geometry!', message='Geo Name:\n%s' % each, button=['Cleanup!', 'Skip...'], defaultButton='Skip...', cancelButton='Skip...', dismissString='Skip...') if proceed == 'Cleanup!': ## Conform the geo and see if that gets rid of all the nonmanifold bits ## if normals: cmds.polyNormal('%s.f[*]' % each, normalMode=2, constructionHistory=True) edges = cmds.polyInfo(each, nme=True) if cmds.polyInfo( each, nme=True) else [] vertices = [] if edges else cmds.polyInfo(each, nmv=True) lastEdges = [] lastVertices = [] while (not self.arraysMatch(lastEdges, edges) or not self.arraysMatch(lastVertices, vertices) ) and (edges or vertices): ## Remember what was nonmanifold last time ## lastEdges = edges lastVertices = vertices ## Split any nonmanifold edges ## if edges: cmds.polySplitEdge(edges, constructionHistory=True) vertices = cmds.polyInfo(each, nmv=True) edges = [] ## Split any remaining nonmanifold vertices ## if vertices: cmds.polySplitVertex(vertices, constructionHistory=True) vertices = [] ## Now check to see if the object is still nonmanifold ## nonManifold = cmds.polyInfo(each, nmv=True, nme=True) if nonManifold: ## Chip off the faces ## nonManifoldFaces = cmds.polyListComponentConversion( nonManifold, toFace=True) cmds.polyChipOff(nonManifoldFaces, kft=0, dup=0, constructionHistory=True) ## And then check for nonmanifold bits again ## edges = cmds.polyInfo(each, nme=True) if not edges: vertices = cmds.polyInfo(each, nmv=True) ## Check to see if we failed to cleanup if edges or vertices: cmds.warning( 'Failed to cleanup non-manifold geometry of %s...' % each)
start_time = time.clock() geometry = pm.ls(tr=True) geometries_poly = cmds.polyListComponentConversion(geometry, tf=True) materials = pm.ls(mat=True) ### for object in geometries_poly: for mat in materials: cmds.hyperShade(objects=str(mat)) selected = pm.ls(sl=True) geometries_poly = cmds.polyListComponentConversion(selected, tf=True) try: cmds.polyChipOff(geometries_poly, kft=False, dup=False) print("ChipOff") except: pass obj_name = [] for obj in geometry: obj_name.append(obj) for i in obj_name: try: cmds.polySeparate(str(i)) print("Separate: " + str(i)) except: pass
def setClone(self, *arg): ''' Creating the smear and its associated control ''' self.chainText = cmds.textField(self.chainName, query=True, text=True) # select the arm geo you want to act as the smear, then run this if cmds.objExists(self.chainText + "_smearGeo"): raise KeyError('Please change the name in the text field') else: print "Making geo clones." oldMan = cmds.textField("oldGeo", query=True, text=True) theSea = cmds.textField("theSea", query=True, text=True) Origin = cmds.ls(selection=True) cmds.select(Origin) cmds.polyChipOff(constructionHistory=1, keepFacesTogether=True, duplicate=True, off=0) if cmds.objExists('originalGeo'): cmds.select('originalGeo') cmds.rename('originalGeo_Grp') else: cmds.select(oldMan) cmds.polySeparate() SuperSmear = cmds.ls(selection=True) cmds.select(SuperSmear[0]) print SuperSmear[0] g1 = cmds.rename("originalGeo") cmds.select(SuperSmear[1]) print SuperSmear[1] g2 = cmds.rename(self.chainText + "_smearGeo") del SuperSmear[:] SuperSmear = [g1, g2] cmds.setAttr('originalGeoShape.doubleSided', 0) cmds.setAttr(self.chainText + '_smearGeoShape.doubleSided', 0) # meant to group the new arm geo twice Grp = cmds.group(empty=True, name=self.chainText + "_Clone_Arm_Grp") cmds.parent(Grp, oldMan) Offset = cmds.group(empty=True, name=self.chainText + "_Clone_Arm_Offset") cmds.parent(Offset, Grp) cmds.parent(SuperSmear[1], Offset) cmds.select(clear=True) # Organize the new Transformation Null cmds.select('transform1') theProphet = cmds.rename(self.chainText + '_transform') if cmds.objExists('Smear_DO_NOT_TOUCH'): print "No need for another 'DNT', as one already exists" else: cmds.group(empty=True, name='Smear_DO_NOT_TOUCH') cmds.parent('Smear_DO_NOT_TOUCH', oldMan) Agro = ('Smear_DO_NOT_TOUCH') cmds.parent(theProphet, Agro) cmds.select(clear=True) # Create the adjustment Locator if cmds.objExists(self.chainText + "_smearLoc"): print "Locator exists, proceeding" else: cmds.spaceLocator(name=self.chainText + "_smearLoc") Loc = (self.chainText + "_smearLoc") cmds.parent(Loc, Grp) cmds.parentConstraint(oldMan, Loc, name=self.chainText + "_warpPC") cmds.parentConstraint(theSea, Grp, name=self.chainText + "_warpGrpPC") cmds.select(clear=True) # Connects Locator's translate and rotate attributes to clone arm attributes cmds.connectAttr(self.chainText + '_smearLoc.translate', self.chainText + '_smearGeo.translate') cmds.connectAttr(self.chainText + '_smearLoc.rotate', self.chainText + '_smearGeo.rotate') # Create control for the new arm cmds.curve(degree=1, point=[(0, 0, 3), (2, 0, 2), (3, 0, 0), (2, 0, -2), (0, 0, -3), (-2, 0, -2), (-3, 0, 0), (-2, 0, 2), (0, 0, 3), (0, -2, 2), (0, -3, 0), (0, -2, -2), (0, 0, -3), (0, 2, -2), (0, 3, 0), (0, 2, 2), (0, 0, 3), (0, 0, 0), (-3, 0, 0), (3, 0, 0), (0, 0, 0), (0, -3, 0), (0, 3, 0), (0, 0, 0), (0, 0, -3), (0, 0, 0), (3, 0, 0), (2, 2, 0), (0, 3, 0), (-2, 2, 0), (-3, 0, 0), (-2, -2, 0), (0, -3, 0), (2, -2, 0), (3, 0, 0)], knot=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]) warpControl = cmds.rename(self.chainText + '_Warp_Ctrl') WarpControlGroup = cmds.group(warpControl, name=self.chainText + '_Warp_Ctrl_Grp') cmds.parent(WarpControlGroup, theSea, relative=True) cmds.parent(WarpControlGroup, world=True) cmds.select(clear=True) if cmds.objExists('Warp_Controls_Group'): print "The host thrives" elif cmds.objExists('Warp_Ctrls_Group'): print "The host thrives" else: cmds.group(empty=True, name='Warp_Ctrls_Group') cmds.parent(WarpControlGroup, 'Warp_Ctrls_Group') cmds.parentConstraint(warpControl, Offset) cmds.scaleConstraint(warpControl, Offset) cmds.setAttr(Offset + '.t', lock=True) cmds.setAttr(Offset + '.r', lock=True) cmds.setAttr(Offset + '.s', lock=True) cmds.setAttr(Offset + '.v', lock=True) cmds.setAttr(Grp + '.t', lock=True) cmds.setAttr(Grp + '.r', lock=True) cmds.setAttr(Grp + '.s', lock=True) cmds.setAttr(Grp + '.v', lock=True) cmds.setAttr(Loc + '.t', lock=True) cmds.setAttr(Loc + '.r', lock=True) cmds.setAttr(Loc + '.s', lock=True) cmds.setAttr(Loc + '.v', 0, lock=True) cmds.setAttr(Agro + '.t', lock=True) cmds.setAttr(Agro + '.r', lock=True) cmds.setAttr(Agro + '.s', lock=True) cmds.setAttr(Agro + '.v', lock=True) cmds.setAttr(theProphet + '.t', lock=True) cmds.setAttr(theProphet + '.r', lock=True) cmds.setAttr(theProphet + '.s', lock=True) cmds.setAttr(theProphet + '.v', lock=True) cmds.select(clear=True) # Connect the smear control to the rig cmds.parentConstraint(theSea, WarpControlGroup, maintainOffset=True) cmds.setAttr(self.chainText + '_Warp_Ctrl.v', lock=True, keyable=False, channelBox=False) cmds.setAttr(self.chainText + '_Warp_Ctrl_Grp.t', lock=True) cmds.setAttr(self.chainText + '_Warp_Ctrl_Grp.r', lock=True) cmds.setAttr(self.chainText + '_Warp_Ctrl_Grp.s', lock=True) cmds.setAttr(self.chainText + '_Warp_Ctrl_Grp.v', lock=True) cmds.setAttr(self.chainText + '_Warp_CtrlShape.overrideDisplayType', 1) print "Please select the group you wish to place the smear pivot control to"
def createInfluenceObject(*args, **keywords): # Create a skin patch to locally deformed the skin as influence object # The patch can be deformed by blendShape or nCloth # usage: select faces on a skinned object # TBD: mirror (boolean), combine (boolean), layer # TBD: need to preserve one skin cluster having no influence object (joint binded only, rigid shape w/o collision) # for the creation of attract to matching mesh constraint if 'influenceType' not in keywords: raise Exception, "missing argument influenceType" influenceType = keywords['influenceType'] s = cmds.ls(sl=True, l=True) if not s: raise Exception, "no selection" faces = cmds.polyListComponentConversion(s, tf=True, internal=True) obj = cmds.listRelatives(cmds.ls(sl=True, o=True, l=True), p=True, f=True) sc = jc.helper.findTypeInHistory(obj, 'skinCluster') dup = cmds.duplicate(obj) def f(x): return dup[0] + re.search('\..*', x).group(0) faces = map(f, faces) cmds.polyChipOff(faces, ch=True, kft=True, dup=True, off=0) dup = cmds.listRelatives(list(set(cmds.ls(faces, o=True, l=True))), p=True, f=True) objs = cmds.polySeparate(dup, ch=False, rs=True) def f(x): return len(cmds.ls(cmds.polyListComponentConversion(x, tf=True), fl=True, l=True)) face_counts = map(f, objs) cmds.delete(objs[face_counts.index(max(face_counts))]) objs.pop(face_counts.index(max(face_counts))) jts = jc.helper.findTypeInHistory(sc, 'joint') for o in objs: if influenceType == "blendShape": dup = cmds.duplicate(o, rr=True) (x1,y1,z1, x2,y2,z2) = cmds.exactWorldBoundingBox(obj) cmds.move((x2-x1), 0, 0, dup, r=True) # bind objs to sc, then copy skin weights from obj to objs sc2 = cmds.skinCluster(jts, o)[0] cmds.copySkinWeights(ss=sc, ds=sc2, nm=True, sa="closestPoint", ia="closestJoint") if influenceType == "blendShape": bs = cmds.blendShape(dup, o, foc=True) cmds.setAttr(bs[0]+"."+dup[0], 1) elif influenceType == "nCloth": cmds.select(o, r=True) mel.eval("createNCloth 0;") ncloth = cmds.ls(sl=True) if ncloth: ncloth = ncloth[0] cmds.setAttr(ncloth+".inputMeshAttract", 2) cmds.select(o, r=True) jc.clothes.__updateNClothAttribute(cmds.ls(cmds.polyListComponentConversion(o, tv=True), fl=True), "inputMeshAttract", 0.03) cmds.select(cmds.polyListComponentConversion(o, te=True), r=True) cmds.polySelectConstraint(m=2, w=1) cmds.select(cmds.polyListComponentConversion(tv=True), r=True) cmds.polySelectConstraint(m=0, w=0) jc.clothes.__updateNClothAttribute(cmds.ls(sl=True, fl=True), "inputMeshAttract", 1) cmds.setAttr(sc+".useComponents", 1) def f((x,y)): return x-y for o in objs: cmds.skinCluster(sc, e=True, ug=True, dr=99, ps=0, ai=o) pts = [] (x1,y1,z1, x2,y2,z2) = cmds.exactWorldBoundingBox(o) for v in cmds.ls(cmds.polyListComponentConversion(obj, tv=True), fl=True, l=True): outside = True (x,y,z) = cmds.pointPosition(v) if x>x1 and x<x2 and y>y1 and y<y2 and z>z1 and z<z2: for u in cmds.ls(cmds.polyListComponentConversion(o, tv=True), fl=True, l=True): zp = zip([x,y,z], cmds.pointPosition(u)) (dx,dy,dz) = map(f, zp) if abs(dx) < 0.0001 and abs(dy) < 0.0001 and abs(dz) < 0.0001: outside = False break if outside: pts.append(v) if pts: cmds.skinPercent(sc, pts, tv=[o, 0]) return
def polyChipOff(*args, **kwargs): res = cmds.polyChipOff(*args, **kwargs) if not kwargs.get('query', kwargs.get('q', False)): res = _factories.maybeConvert(res, _general.PyNode) return res
def split_shells(sel=None, uvset=None, hist=None): """Splitting edges by uv shell borders # Partially based on rebb's code: https://polycount.com/discussion/52722/maya-mel-script-help-needed-uv-border-edges/p1 # TODO: - optimipztion: get_uv_shells() is revoking each time edges are modified(splitting) # Using: - get_uv_shells() # Usage: select objects: >> split_shells(hist=True) # Args: - sel, str, if None current selections will be used - uvset, str, if None current uvSet will be used for each selection - hist, bool, construction history preservation, default is True # Returns: >> 0 # on success """ # solve selection lssl = cm.ls(sel, l=1) if not sel: lssl = cm.ls(sl=1, l=1) if not lssl: return # uv component name attr = "map" # resolve kwargs for all selection hist = True if hist is None else hist for sel_l in lssl: # resolve kwargs for each selection if not uvset: # if not given use current uvset = cm.getAttr(sel_l + ".cuvs") else: # if given, check if exists alluvs = cm.polyUVSet(sel_l, q=1, auv=1) if sel not in alluvs: msg = " ! Not found in: '{}':'{}'" print msg.format(uvset, sel_l), continue shells = get_uv_shells(sel_l, uvSet=uvset) # shell = shells[0] print ">", sel_l for i in range(len(shells)): comps = [] for j in shells[i]: comp = "{}.{}[{}]".format(sel_l, attr, j) comps.append(comp) #cm.select(comps) # chippoff shells except first(0) if i: # convert to containing face and flatten list # (faster than `ls -fl ..`) shell2face = cm.filterExpand( cm.polyListComponentConversion(comps, tf=1, internal=1), sm=34) #cm.select(shell2face) chipoff = cm.polyChipOff(shell2face, dup=0, ch=hist) comps = cm.polyListComponentConversion(shell2face, tuv=1) # select only borders of one shell cm.select(comps) # do not comment this line # (!) selection based operation # On selection mask type to "uv borders" bord_uvs = cm.polySelectConstraint( t=0x0010, uv=0, bo=1, m=2, returnSelection=1) # Off "uv borders" mask cm.polySelectConstraint(bo=0) #cm.select(bord_uvs) # convert to edge and flatten list edgs = cm.filterExpand( cm.polyListComponentConversion(bord_uvs, te=1, internal=1), sm=32) #cm.select(edgs) # filter edges by uv uv2edg = [] for ed in edgs: # cm.select(ed) uvs = cm.filterExpand( cm.polyListComponentConversion(ed, tuv=1), sm=35) if len(uvs) > 2: uv2edg.append(ed) #cm.select(uv2edg) if uv2edg: cm.polySplitEdge(uv2edg, ch=hist) # update shells # update uv shells' uv points shells = get_uv_shells(sel_l, uvSet=uvset) return 0
def snowFactory(self): #Duplicate Face faceSelection = mc.ls(sl=True) object = mc.ls(sl=True, o=True) mc.polyChipOff(faceSelection, ch=True, kft=True, dup=True, off=0) mc.polySeparate(object) mc.parent(w=True) mc.select(object, deselect=True) mm.eval("CenterPivot") objA = mc.ls(sl=True, head=1) objB = mc.ls(sl=True, tail=1) mc.select(objA, deselect=True) global objC objC = mc.ls(sl=True) totalDuplicatedMesh = len(objC) #Delete History for j in range(0, totalDuplicatedMesh, 1): TransformNode = mc.ls(objC[j], dependencyNodes=True) mc.select(TransformNode[0]) mm.eval('DeleteHistory') mc.delete(TransformNode[0], ch=True) orgTrans = mc.ls(objA, dependencyNodes=True) mc.select(orgTrans[0]) mm.eval('DeleteHistory') mc.delete(orgTrans[0], ch=True) #Nparticle Setup snowParticle = mc.nParticle() for i in range(0, totalDuplicatedMesh, 1): mc.select(objC[i]) snowEmitter = mc.emitter(n=(objC[i] + 'snowEmitter'), type='surface', r=5000, sro=0, nuv=0, cye='none', cyi=1, spd=0, srn=0, nsp=1, tsp=0, mxd=0, mnd=0, dx=1, dy=0, dz=0, sp=0) mc.connectDynamic(snowParticle, em=snowEmitter[1]) mc.setAttr(str(snowParticle[0]) + '.ignoreSolverGravity', 1) mc.setAttr(str(snowParticle[0]) + '.dynamicsWeight', 0) mc.setAttr(str(snowParticle[0]) + '.conserve', 0) mc.setAttr(str(snowParticle[0]) + '.radius', 0.1) mc.setAttr(str(snowParticle[0]) + '.radiusScaleRandomize', 0.5) mc.setAttr(str(snowParticle[0]) + '.particleRenderType', 3) #Play Forward #Generate Nparticle Mesh mc.select(snowParticle[0], r=True) outMesh = mm.eval('particleToPoly') global snowParticleShape snowParticleShape = mc.listRelatives(snowParticle[0], s=True) mc.setAttr(str(snowParticleShape[0]) + '.blobbyRadiusScale', 1.8) mc.setAttr(str(snowParticleShape[0]) + '.meshTriangleSize', 0.2) mc.setAttr(str(snowParticleShape[0]) + '.meshMethod', 3) mc.setAttr(str(snowParticleShape[0]) + '.meshSmoothingIterations', 10)