예제 #1
0
def makeShards(number, size, sizeVar, rgb1, rgb2, transparency, glow):
    '''
    Creates a number of ice shard particles
    
    number       : Number of particles to create
    size         : Radius of the particles
    sizeVar      : Variation in the radius
    rgb1         : One end of the colour range in the form (r,g,b)
    rgb2         : The other end of the colour range in the form (r,g,b)
    transparency : Alpha value for the shader
    glow         : Glow value for the shader
    
    The progress window is updated and the shading group list is created. 
    A while loop is initiated to create octahedrons, add them to the list 
    and assign shaders. The list of objects is returned.
    '''
    cmds.progressWindow(e=1, progress=0, status='Making Shards...')
    SGList = createColourList(rgb1, rgb2, transparency, glow, 5)
    list = []
    count = 0
    while count < number:
        radius = size + random.uniform(-(size * sizeVar * 0.01),
                                       (size * sizeVar * 0.01))
        list[len(list):] = [cmds.polyPlatonicSolid(r=radius, st=2)[0]]
        cmds.polySoftEdge(list[-1], a=0)
        cmds.sets(list[-1], e=1, forceElement=SGList[random.randint(0, 4)])
        cmds.progressWindow(e=1, step=100 / number)
        count += 1
    return list
    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#')
예제 #3
0
def ldmt_turboSmooth():
    mods = cmds.getModifiers()
    mel.eval('resetPolySelectConstraint;')
    sel = cmds.ls(sl=1,o=1)
    sel = sel[0]
    cmds.select(sel+'.e[*]',r=1)
    cmds.polySelectConstraint(m=3,t=0x8000,sm=1)
    cmds.sets(n="ldmt_turboSmoothQS")
    currentSel = cmds.ls(sl=1)
    if currentSel != []:
        try:
            cmds.polyCrease(value=1)
        except:
            pass
    cmds.select(sel,r=1)
    cmds.polySmooth(sel,mth=0,sdt=2,ovb=2,ofb=3,ofc=1,ost=1,ocr=1,dv=1,bnr=1,c=0,kb=0,ksb=1,khe=1,kt=0,kmb=0,suv=1,peh=1,sl=1,dpe=1,ps=0.1,ro=1,ch=1)
    cmds.select("ldmt_turboSmoothQS",r=1)
    currentSel = cmds.ls(sl=1)
    if currentSel != []:
        try:
            cmds.polySoftEdge(a=0,ch=1)
            cmds.polyCrease(value=0)
        except:
            pass
        if mods == 4:
            try:
                cmds.polyCrease(value=1)
            except:
                pass
    cmds.polySelectConstraint(m=0,dis=1)
    cmds.select(sel,r=1)
    cmds.delete("ldmt_turboSmoothQS")
예제 #4
0
def makeShards(number,size,sizeVar,rgb1,rgb2,transparency,glow):
    '''
    Creates a number of ice shard particles
    
    number       : Number of particles to create
    size         : Radius of the particles
    sizeVar      : Variation in the radius
    rgb1         : One end of the colour range in the form (r,g,b)
    rgb2         : The other end of the colour range in the form (r,g,b)
    transparency : Alpha value for the shader
    glow         : Glow value for the shader
    
    The progress window is updated and the shading group list is created. 
    A while loop is initiated to create octahedrons, add them to the list 
    and assign shaders. The list of objects is returned.
    '''
    cmds.progressWindow(e=1,progress=0,status='Making Shards...')
    SGList = createColourList(rgb1,rgb2,transparency,glow,5)
    list=[]
    count=0
    while count<number:
        radius = size+random.uniform(-(size*sizeVar*0.01),(size*sizeVar*0.01))
        list[len(list):] = [cmds.polyPlatonicSolid(r=radius,st=2)[0]]
        cmds.polySoftEdge(list[-1],a=0)
        cmds.sets(list[-1], e=1, forceElement=SGList[random.randint(0,4)])
        cmds.progressWindow(e=1,step=100/number)
        count += 1
    return list
예제 #5
0
def run():	
	#get selected edgeloop
	edgeLoop = cmds.ls(selection=True)
	#get verticles in the edge loop
	vertLoop = cmds.polyListComponentConversion(edgeLoop, fromEdge=True, toVertex=True)
	#sort individual verticles into a list
	vertLoop = cmds.ls(vertLoop, flatten=True)

	#open undo chunk so entire operation is a single action
	cmds.undoInfo(openChunk = True)

	#soften the mesh normals
	mesh = cmds.listRelatives(parent=1)
	cmds.polySoftEdge(mesh, angle=180)

	#run on each vertex on the edgeloop
	for vert in vertLoop:
		#unlock the normal of the vertex
		cmds.polyNormalPerVertex(vert, unFreezeNormal=True)
		#get the normals of the vertex on the loop
		vertNormals = list(cmds.polyNormalPerVertex(vert, query=True, xyz=True))
		#get only the first three vectors
		vertNormals = vertNormals[:3]

		# select the neighboring verticles using the declared function below
		vertNeighbors(vert, vertLoop)

		#set their normal angle to match the vertex on the loop
		cmds.polyNormalPerVertex(xyz=vertNormals)

	#reselect the edge loops
	cmds.select(edgeLoop)

	#close undo chunk, operation is done
	cmds.undoInfo(closeChunk = True)
예제 #6
0
파일: ui.py 프로젝트: jubeyjose/maya-prefs
    def initGeometry(self):
        selection = m.ls(sl=True)

        meshes = m.ls(selection=True,
                      long=True,
                      dagObjects=True,
                      allPaths=True,
                      type='mesh',
                      noIntermediate=True)
        if meshes:
            for mesh in meshes:
                transform = com.getParent(mesh)
                if transform:
                    self.backupers.append(backuper.Backuper(mesh, transform))
                    m.polyNormalPerVertex(mesh, ufn=True)
                    m.polySoftEdge(transform, a=180, ch=False)

                    geomProcessor = geom_processor.GeomProcessor(mesh)
                    geomProcessor.params = Parameters
                    self.processors.append(geomProcessor)
        else:
            pm.confirmDialog(
                title='Error',
                message='Invalid selection. Select at least one mesh.',
                button=['OK'],
                defaultButton='OK',
                icon='critical')
            return

        m.select(selection, r=True)
예제 #7
0
def crystalise(base):
    '''
    Adds hexagonal crystals to a branch
    
    base : The branch to be crystallised
    
    A crystal is created by scaling the top and bottom rings of vertices of a 
    cylinder. The crystal is aligned to the base branch and scaled to match. 
    The crystal is duplicated, randomly distributed along the branch and scaled 
    relative to their positioning. The crystals are combined with the base branch 
    mesh and this object is returned.
    '''
    crystal=[cmds.polyCylinder(r=1,sx=6,sy=2)[0]]
    cmds.polySoftEdge(crystal[0], a=0)
    cmds.scale(0.6,0.3,0.6,crystal[0]+'.f[12:13]',r=1)
    [(tx,ty,tz)] = cmds.getAttr(base+'.translate')
    [(rx,ry,rz)] = cmds.getAttr(base+'.rotate')
    cmds.move(tx,ty,tz,crystal[0])
    cmds.rotate(rx,ry,rz,crystal[0])
    [x1,y1,z1,x2,y2,z2] = cmds.xform(base+'.vtx[0:1]',q=1,t=1,ws=1)
    baseScale = cmds.getAttr(base+'.scaleX')
    cmds.scale(0.5,0.2,0.5,crystal[0])
    length = ((x2-x1)**2+(z2-z1)**2)**0.5
    for i in range(0,6):
        crystal[len(crystal):]=[cmds.duplicate(crystal[0])[0]]
    for x in crystal:
        dist = (random.random())
        cmds.move(length*dist,0,0,x,os=1,r=1,wd=1)
        size = (1.5-dist)*(length/3)
        cmds.scale(size,size,size,x,r=1)
        cmds.rotate(0,30,0,x,r=1)
    crystal += [base]
    return combineParts(crystal,base)
예제 #8
0
def dessBranche(formule, puissance, getPosDeb, taille, epaisseur, embout,
                nbSousBranches, proportion, rotationBranche):

    g_branche = cmds.group(empty=True, name="branche")
    pIniRotate = tuple(getPosDeb)

    for i in range(1, nbSousBranches + 1):
        getX = int(taille * proportion)
        getPosDeb, getPosFin = dessCourbe(formule, puissance, getPosDeb,
                                          taille, epaisseur, getX)
        taille -= getX
        c = cmds.rename("branche_" + formule + "_" + str(i))
        cmds.parent(c, g_branche)

        if (embout == 1):
            s = cmds.polySphere(sx=6, sy=6, radius=2, n="embout")
            cmds.polySoftEdge(a=180)
        elif (embout == 2):
            s = cmds.polyCube(w=2, h=2, d=2, n="embout")
            cmds.rotate(45, 0, 45)
        else:
            s = cmds.polyCone(ax=[0, -1, 0], r=2, sa=12, n="embout")
            cmds.polySoftEdge(a=60)

        cmds.move(getPosFin[0], getPosFin[1], getPosFin[2], s)
        cmds.parent(s, g_branche)

    cmds.rotate(0, rotationBranche, 0, g_branche, pivot=pIniRotate)
    return g_branche
예제 #9
0
파일: helpers.py 프로젝트: shdwdln/pbTools
def uvShellHardEdges():
    '''
    Sets uv border edges on a mesh has hard, and everythign else as soft.
    '''
    objList = cmds.ls(sl=True, o=True)
    finalBorder = []

    for subObj in objList:
        cmds.select(subObj, r=True)
        cmds.polyNormalPerVertex(ufn=True)
        cmds.polySoftEdge(subObj, a=180, ch=1)
        cmds.select(subObj + '.map[*]', r=True)

        polySelectBorderShell(borderOnly=True)

        uvBorder = cmds.polyListComponentConversion(te=True, internal=True)
        uvBorder = cmds.ls(uvBorder, fl=True)

        for curEdge in uvBorder:
            edgeUVs = cmds.polyListComponentConversion(curEdge, tuv=True)
            edgeUVs = cmds.ls(edgeUVs, fl=True)

            if len(edgeUVs) > 2:
                finalBorder.append(curEdge)

        cmds.polySoftEdge(finalBorder, a=0, ch=1)

    cmds.select(objList)
	def HardedgeNormals(self):
		henselVerArray = cmds.ls( selection=True, fl=True )
		if not henselVerArray:
			pass
			print "nothing selected"
			return
		if self.selectlive:
#			print"test: sel islive in HardedgeNormals"
			self.selectlive = False
#			print "self.selectlive", self.selectlive
			cmds.polyNormalPerVertex(ufn=True)
			cmds.select(cmds.polyListComponentConversion( henselVerArray, te=True ))
			cmds.polySoftEdge( a=self.NormalAngle.value() )
#			cmds.polyNormalPerVertex(cmds.polyListComponentConversion( selVerArray, tv=True ),ufn=True)
			cmds.select(henselVerArray)
			self.VecOriginlist = nrmedittool.BuildVecOrigin()
			self.SliderIntensity.setValue(0)
			self.selectlive = True
			return
		else:
#			print"test: sel is not live in HardedgeNormals"
			cmds.polyNormalPerVertex(ufn=True)
			cmds.select(cmds.polyListComponentConversion( henselVerArray, te=True ))
			cmds.polySoftEdge( a=self.NormalAngle.value() )
			cmds.select(henselVerArray)
			self.VecOriginlist = nrmedittool.BuildVecOrigin()
			return
예제 #11
0
def gameOpt():

    # dialogue box
    softenEdgeDialogue = cmds.confirmDialog(t='Soften Edges',
                                            b=['Yes', 'No'],
                                            defaultButton='Yes',
                                            cancelButton='No',
                                            dismissString='No')

    # this softens the mesh's edges, should the user click 'Yes'
    if softenEdgeDialogue == 'Yes':
        for i in objs:
            cmds.select(i)
            cmds.polySoftEdge(a=180)

    # this runs optimization commands for game engine
    for i in objs:
        cmds.select(i)
        cmds.snapMode(gr=True)
        cmds.move(rpr=True)
        cmds.snapMode(gr=False)
        cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)
        cmds.DeleteHistory()
    # deselect
    cmds.select(clear=True)
예제 #12
0
파일: ui.py 프로젝트: Italic-/maya-prefs
    def initGeometry(self):
        selection = m.ls(sl=True)

        meshes = m.ls(
            selection=True,
            long=True,
            dagObjects=True,
            allPaths=True,
            type='mesh',
            noIntermediate=True
        )
        if meshes:
            for mesh in meshes:
                transform = com.getParent(mesh)
                if transform:
                    self.backupers.append(backuper.Backuper(mesh, transform))
                    m.polyNormalPerVertex(mesh, ufn=True)
                    m.polySoftEdge(transform, a=180, ch=False)

                    geomProcessor = geom_processor.GeomProcessor(mesh)
                    geomProcessor.params = Parameters
                    self.processors.append(geomProcessor)
        else:
            pm.confirmDialog(
                title='Error',
                message='Invalid selection. Select at least one mesh.',
                button=['OK'],
                defaultButton='OK',
                icon='critical'
            )
            return

        m.select(selection, r=True)
예제 #13
0
def shell_border_edges_to_hard():
    """
    Sets uv border edges on a mesh has hard, and everythign else as soft.
    """
    objList = cmds.ls(sl=True, o=True)
    finalBorder = []

    for subObj in objList:
        cmds.select(subObj, r=True)
        cmds.polyNormalPerVertex(ufn=True)
        cmds.polySoftEdge(subObj, a=180, ch=1)
        cmds.select(subObj + '.map[*]', r=True)

        polySelectBorderShell(borderOnly=True)

        uvBorder = cmds.polyListComponentConversion(te=True, internal=True)
        uvBorder = cmds.ls(uvBorder, fl=True)

        for curEdge in uvBorder:
            edgeUVs = cmds.polyListComponentConversion(curEdge, tuv=True)
            edgeUVs = cmds.ls(edgeUVs, fl=True)

            if len(edgeUVs) > 2:
                finalBorder.append(curEdge)

        cmds.polySoftEdge(finalBorder, a=0, ch=1)

    cmds.select(objList)
예제 #14
0
def crystalise(base):
    '''
    Adds hexagonal crystals to a branch
    
    base : The branch to be crystallised
    
    A crystal is created by scaling the top and bottom rings of vertices of a 
    cylinder. The crystal is aligned to the base branch and scaled to match. 
    The crystal is duplicated, randomly distributed along the branch and scaled 
    relative to their positioning. The crystals are combined with the base branch 
    mesh and this object is returned.
    '''
    crystal = [cmds.polyCylinder(r=1, sx=6, sy=2)[0]]
    cmds.polySoftEdge(crystal[0], a=0)
    cmds.scale(0.6, 0.3, 0.6, crystal[0] + '.f[12:13]', r=1)
    [(tx, ty, tz)] = cmds.getAttr(base + '.translate')
    [(rx, ry, rz)] = cmds.getAttr(base + '.rotate')
    cmds.move(tx, ty, tz, crystal[0])
    cmds.rotate(rx, ry, rz, crystal[0])
    [x1, y1, z1, x2, y2, z2] = cmds.xform(base + '.vtx[0:1]', q=1, t=1, ws=1)
    baseScale = cmds.getAttr(base + '.scaleX')
    cmds.scale(0.5, 0.2, 0.5, crystal[0])
    length = ((x2 - x1)**2 + (z2 - z1)**2)**0.5
    for i in range(0, 6):
        crystal[len(crystal):] = [cmds.duplicate(crystal[0])[0]]
    for x in crystal:
        dist = (random.random())
        cmds.move(length * dist, 0, 0, x, os=1, r=1, wd=1)
        size = (1.5 - dist) * (length / 3)
        cmds.scale(size, size, size, x, r=1)
        cmds.rotate(0, 30, 0, x, r=1)
    crystal += [base]
    return combineParts(crystal, base)
예제 #15
0
def import_obj(file_path):
    dirname, filename = os.path.split(file_path)
    filename, ext = os.path.splitext(filename)

    load_obj_plugin()

    # usually when import and obj mesh the imported object name will be polySurface1
    # check if there is already a polysSurface object in the scene root
    if cmds.objExists('|polySurface1'):
        import_name = '|{}_polySurface1'.format(filename)
    else:
        import_name = '|polySurface1'

    # delete the mtl file before importing, we don't really want to create a new material
    mtl_file = os.path.join(dirname, filename + '.mtl')
    if os.path.exists(mtl_file):
        os.remove(mtl_file)

    cmds.file(file_path, i=True, typ='OBJ', options='mo=0')

    # check if there is already an object with the filename in the scene
    # if so update this mesh vertex position otherwise only rename the imported mesh
    if cmds.objExists(filename):
        sel = om.MSelectionList()
        sel.add(import_name)
        sel.add(filename)

        mmesh_source = om.MFnMesh(sel.getDagPath(0))
        mmesh_target = om.MFnMesh(sel.getDagPath(1))

        if mmesh_source.numVertices != mmesh_target.numVertices:
            raise Exception(
                "Error, imported mesh doesn't have the same vertex count. {} -> {}"
                .format(mmesh_source.numVertices, mmesh_target.numVertices))

        points = mmesh_source.getPoints()
        mmesh_target.setPoints(points)

        cmds.delete(import_name)
    else:
        # clean object set
        shapes = cmds.listRelatives(import_name, shapes=True, fullPath=True)
        if shapes:
            for shape in shapes:
                objGroup = cmds.listConnections(shape,
                                                type='objectSet',
                                                exactType=True,
                                                destination=False)
                if objGroup:
                    cmds.delete(objGroup)

        # polySoftEdge -a 180 -ch 1 polySurface1
        cmds.polySoftEdge(import_name, a=180, ch=1)
        cmds.delete(import_name, constructionHistory=True)

        cmds.rename(import_name, filename)

    # remove file
    os.remove(file_path)
예제 #16
0
def softenEdge(*args):
   mmSelectedItems = cmds.ls(sl = 1)

   for mmItem in mmSelectedItems:
      cmds.select(mmItem)
      cmds.polySoftEdge(a=180);

   cmds.select(cl = 1)
예제 #17
0
def softEdgeSelection():
    """
    unlock normals and soft edge
    """
    sel = cmds.ls(sl=True)
    for node in sel:
        cmds.polyNormalPerVertex(node, ufn=True)
        cmds.polySoftEdge(node, angle=normalAngle)
예제 #18
0
 def kmSoftEdge0(self):
     selectionList = mc.ls(selection=True, type='transform')
     if selectionList:
         for obj in selectionList:
             mc.polySoftEdge(obj, angle=0)
         sel = mc.select(selectionList)
     else:
         print ">> No selection"
예제 #19
0
파일: ka_shapes.py 프로젝트: 3dkris/ka_maya
def createShape_mesh(numVertices,
                     numFaces,
                     faceCounts,
                     faceConnects,
                     points,
                     hardEdges,
                     name=None,
                     parent=None):
    """
    Creates a mesh from the given parameters. These inputs are usually generated from the print_createShape_mesh function.
    """

    if not parent:
        parentMObject = OpenMaya.MObject()
    else:
        if not ka_pymel.isPyTransform(parent):
            parent = pymel.PyNode(parent)

        parentMObject = parent.__apimobject__()

    if not name and parent:
        name = parent.nodeName() + 'Shape'

    faceCounts_MintArray = OpenMaya.MIntArray()
    for i in faceCounts:
        faceCounts_MintArray.append(i)

    faceConnects_MIntArray = OpenMaya.MIntArray()
    for i in faceConnects:
        faceConnects_MIntArray.append(i)

    points_MFloatPointArray = OpenMaya.MFloatPointArray()
    for point in points:
        points_MFloatPointArray.append(OpenMaya.MFloatPoint(*point))

    meshFS = OpenMaya.MFnMesh()
    newMesh = meshFS.create(numVertices, numFaces, points_MFloatPointArray,
                            faceCounts_MintArray, faceConnects_MIntArray,
                            parentMObject)
    #for edge in hardEdges:

    #meshFS.setEdgeSmoothing(edge, False)
    meshFS.updateSurface()

    if name:
        mesh = cmds.rename(meshFS.name(), name)
    else:
        mesh = meshFS.name()

    hardEdgesStrings = []
    for edge in hardEdges:
        hardEdgesStrings.append('%s.e[%s]' % (mesh, str(edge)))

    cmds.sets(mesh, e=True, fe='initialShadingGroup')
    cmds.polySoftEdge(*hardEdgesStrings, ch=0, a=0)

    return pymel.PyNode(mesh)
예제 #20
0
    def createMayaHelixNodes(self, x, y, colorname, strandType, mID):
        """
        Create all the Maya nodes, set the initial attributes and connections.
        There are 3 Maya nodes associated with each Strand: Transform Node,
        Shape Node (spHalfCylinderHelixNode), and a Mesh Node (a generic Maya
        Node that is used for rendering) The Mesh Node is the child of the
        Transform Node, and spHalfCylinderHelixNode node inputs the shape data
        into the Mesh Node, using cmds.connectAttr command
         ________________
        | Transform Node |
         ----------------
                |
         ________________  .inMesh          .outputMesh _____________________
        |   Mesh Node    |<---------------------------| HalfCylinderHelixNode |
         ----------------                              -----------------------
        """
        m = Mom()
        cylinderName = "%s%s" % (m.helixNodeName, mID)
        transformName = "%s%s" % (m.helixTransformName, mID)
        meshName = "%s%s" % (m.helixMeshName, mID)
        # shaderName = "%s%s" % (m.helixShaderName, mID)
        cmds.createNode("transform", name=transformName, skipSelect=True)
        cmds.setAttr("%s.rotateX" % transformName, 90)
        cmds.setAttr("%s.translateX" % transformName, x)
        cmds.setAttr("%s.translateY" % transformName, y)
        cmds.createNode("mesh",
                        name=meshName,
                        parent=transformName,
                        skipSelect=True)
        cmds.createNode("spHalfCylinderHelixNode",
                        name=cylinderName,
                        skipSelect=True)
        cmds.connectAttr("%s.outputMesh" % cylinderName,
                         "%s.inMesh" % meshName)
        # XXX - [SB] This should go away and we will ask the model for
        # the right numbers...
        vhi = self._virtualHelixItem
        part = vhi.partItem().part()
        cSType = part.crossSectionType()
        cmds.setAttr("%s.rotation" % cylinderName, part.twistPerBase())
        cmds.setAttr("%s.parity" % cylinderName, vhi.isEvenParity())
        if cSType == LatticeType.HONEYCOMB:
            cmds.setAttr("%s.rotationOffset" % cylinderName, 250)
            cmds.setAttr("%s.decoratorRotOffset" % cylinderName, 90)
        elif cSType == LatticeType.SQUARE:
            cmds.setAttr("%s.rotationOffset" % cylinderName, 125)
            cmds.setAttr("%s.decoratorRotOffset" % cylinderName, 200)
        else:
            raise NotImplementedError
        cmds.setAttr("%s.strandType" % cylinderName, strandType)
        self.updateColor(mID, colorname)

        cmds.select(transformName)
        cmds.polySoftEdge(a=89.99)
        cmds.setAttr("%s.displayEdges" % meshName, 2)
        cmds.select(clear=True)
        return (cylinderName, transformName, meshName)
예제 #21
0
파일: modeling.py 프로젝트: shrimo/dmptools
def unlockAndHarden():
    """
    comverts selected components to vertices, unlocks and harden
    """
    if cmds.ls(sl=True):
        newSel = cmds.polyListComponentConversion(ff=True, fe=True, fuv=True, fvf=True, tv=True)
        cmds.select(newSel)
        cmds.polyNormalPerVertex(ufn=True)
        cmds.polySoftEdge(angle=0, ch=False)
 def smooth_copy(mesh, progressBar, progressStep):  # 331
     orig_name = self.static_base_meshes[0]  # modified by Hiura
     self.original_mesh = snapshot(mesh, 0)  # modified by Hiura
     self.original_mesh = cm.rename(self.original_mesh,
                                    orig_name + "_MorphExport")
     cm.polySoftEdge(self.original_mesh, a=180, ch=0)
     cm.polyTriangulate(self.original_mesh, ch=0)  # added by Hiura
     self.vert_count = get_vert_count(self.original_mesh)
     store_original_vert_positions(progressBar, progressStep)
예제 #23
0
	def importObj(self, file, groupName):
		'''Import and prep an obj file. This is used to import the terrain
		   object as well as the agent geometry objects.'''
		importedNodes = mc.file(file, returnNewNodes=True, type="OBJ", options='mo=0',
								groupName=groupName, groupReference=True, i=True)
		meshes = mc.ls(importedNodes, long=True, type="mesh")
		for mesh in meshes:
			mc.polySoftEdge(mesh, a=180, ch=False)
		[newGroup] = mc.ls(importedNodes, long=True, assemblies=True)
		return newGroup
예제 #24
0
파일: editor.py 프로젝트: McManning/shaders
def softenModel():
    """Applies polySoftEdge softening to all edges in the model"""
    # select all edges of the parent, soften, and return to old selection
    selected = cmds.ls(selection=True)

    cmds.select(getParent(selected[0]), replace=True)
    cmds.select(cmds.polyListComponentConversion(te=True))
    cmds.polySoftEdge(a=180)

    cmds.select(selected, replace=True)
def mirrorGeometry(node, across=0, merge=True, softEdge=True, threshold=0.001):
    shapes = cmds.listRelatives(node, s=True, pa=True)
    if not shapes:
        return False
    if cmds.objectType(shapes[0]) != 'mesh':
        return False
    shape = shapes[0]
    pivot = cmds.xform(node, q=True, ws=True, piv=True)

    if across == 0:
        direction = 4
        index = 2
    elif across == 1:
        direction = 0
        index = 0
    else:
        direction = 2
        index = 1

    kwargs = {}
    if merge:
        kwargs['mm'] = True
        kwargs['mt'] = threshold
    else:
        kwargs['mm'] = False

    cmds.polyMirrorFace(shape, ws=True, d=direction, p=pivot[0:3], **kwargs)

    if softEdge:
        vertices = cmds.polyListComponentConversion(shape,
                                                    fv=1,
                                                    ff=1,
                                                    fe=1,
                                                    fuv=1,
                                                    fvf=1,
                                                    tv=1)
        vertices = cmds.ls(vertices, fl=True)

    centerVertices = []
    for vertex in vertices:
        pos = cmds.pointPosition(vertex, w=True)
        if abs(pivot[index] - pos[index]) <= threshold:
            centerVertices.append(vertex)

    centerEdges = []
    if centerVertices:
        centerEdges = cmds.polyListComponentConversion(centerVertices,
                                                       fv=1,
                                                       ff=1,
                                                       fuv=1,
                                                       fvf=1,
                                                       te=1,
                                                       internal=1)
    if centerEdges:
        cmds.polySoftEdge(centerEdges, a=180)
예제 #26
0
파일: temp_py.py 프로젝트: auqeyjf/pubTool
def j_doFreezeVtx():
    '''
    do freeze vertex position on channelBox
    '''
    obj = mc.ls(sl = 1)
    mc.select(clear =1)
    for i in obj:
        mc.polySoftEdge( i, a =180 , ch = 0 )
        mc.delete( obj , ch =1 )
        mc.select(obj , r =1)
    print "Complete !!"    
예제 #27
0
def j_doFreezeVtx():
    '''
    do freeze vertex position on channelBox
    '''
    obj = mc.ls(sl=1)
    mc.select(clear=1)
    for i in obj:
        mc.polySoftEdge(i, a=180, ch=0)
        mc.delete(obj, ch=1)
        mc.select(obj, r=1)
    print "Complete !!"
예제 #28
0
파일: jimboRibbon.py 프로젝트: radvfx/py
def initializeRibbon(initWidth):
	mc.polyPlane(sx = 240, sy = 2.0, n = "ribbonTemp", w = initWidth, h = 0.165)
	mc.rename("polyPlane1", "ribbonTempHistory")
	mc.polySoftEdge( a = 180)
	mc.lattice( n = 'ribbon', cp = True, dv = (2, 4, 2), objectDentered = True, ldv = (2, 3, 2), outsideLattice = True )
        mc.hide()
	mc.select('ribbonTempHistory.vtx[1]', r=True )
	mc.ChamferVertex()
	mc.rename( "polyChamfer1", "tempChamfer" )
	mc.seAttr( 'tempChamfer.width', 1)
	mc.delete( 'ribbonTemp.vtx[72]' )
	return
예제 #29
0
파일: jimboBalloon.py 프로젝트: radvfx/py
def initializeBalloon(initRadius):
	mc.polySphere(sx = 12, sy = 8, n = "balloonTemp", r = initRadius)
	mc.rename( "polySphere1", "balloonTempHistory")
	mc.polySoftEdge( a = 180 )
	mc.lattice( n = 'balloon', cp = True, dv = (2, 4, 2), objectCentered = True,  ldv = (2, 3, 2), outsideLattice = True )
	mc.hide()
	mc.select('balloonTemp.vtx[84]', r=True)
	mc.ChamferVertex()
	mc.rename( "polyChamfer1", "tempChamfer" )
	mc.setAttr( 'tempChamfer.width', .1 )
	mc.delete( 'balloonTemp.f[72]' )
	return
예제 #30
0
def toAlembic(parameters, arguments):
	"""
	Converts an Obj file to Alembic file.
	
	:param parameters: Command line parameters.
	:type parameters: object
	:param arguments: Command line arguments.
	:type arguments: object
	:return: Definition success.
	:rtype: bool
	"""

	inputFile = parameters.inputFile
	if inputFile is None:
		sys.stderr.write("!> {0} | No input file provided!\n".format(inspect.getmodulename(__file__)))
		return

	if not os.path.exists(inputFile):
		sys.stderr.write("!> {0} | '{1}' file doesn't exists'!\n".format(inspect.getmodulename(__file__), inputFile))
		return

	outputFile = os.path.abspath(parameters.outputFile if parameters.outputFile else re.sub(r"\.\w+$", ".abc", inputFile))

	exportAll = parameters.exportAll

	frameRange = parameters.frameRange
	try:
		frameIn, frameOut = frameRange.split("-")
	except ValueError:
		sys.stderr.write("!> {0} | The frame range format could not be determined!\n".format(inspect.getmodulename(__file__)))
		return
	
	not cmds.pluginInfo("AbcExport", q=True, loaded=True) and cmds.loadPlugin("AbcExport")	

	cmds.file(inputFile, o=True)

	# Processing ".obj" file normals.
	if re.search(r"\.obj$", inputFile, flags=re.IGNORECASE):
		for mesh in cmds.ls(type="mesh", long=True):
			cmds.polyNormalPerVertex(mesh, ufn=True)
			cmds.polySoftEdge(mesh, a=180, ch=False)

	if exportAll:
		jobCommand = "-frameRange {0} {1} -uvWrite -file {2}".format(frameIn, frameOut, outputFile)
	else:
		rootNodes = list(set([getRoot(mesh) for mesh in cmds.ls(type="mesh", long=True)]))
		rootFlags = " ".join(["-root {0}".format(rootNode) for rootNode in rootNodes])
		jobCommand = "-frameRange {0} {1} -uvWrite {2} -file {3}".format(frameIn, frameOut, rootFlags, outputFile)
	
	sys.stderr.write("{0} | Exporting to 'Alembic' with following job command: '{1}'\n".format(inspect.getmodulename(__file__), jobCommand))
	cmds.AbcExport(j=jobCommand)
	return True
예제 #31
0
def createBaseMesh():
    ob = cmd.ls(sl=True)[0]
    if (cmd.nodeType(ob) == 'transform') and (cmd.attributeQuery(
            'name', node=ob, exists=True)):

        #initialize
        merge = True
        name = cmd.getAttr('%s.name' % ob)
        frames = cmd.getAttr('%s.count' % ob)
        ctlObj = cmd.getAttr('%s.myCtl' % ob)
        thresh = 0.015
        extrudeAmt = 0.2
        edgeAmt = 0.05
        newGp = cmd.group(em=True, w=True, n='%s_GEO_GP' % name)
        cmd.addAttr(newGp, ln='name', dt='string')
        cmd.setAttr("%s.name" % newGp, name, type='string')

        #create the new objects
        for i in range(1, frames + 1):
            cmd.setAttr('%s.frame' % ctlObj, i)
            newName = '%s_%02d_GEO' % (name, i)
            newOb = cmd.duplicate(ob, n=newName)[0]
            cmd.setAttr('%s.v' % newOb, 0)
            #insert a handler here to detect double faces or bad geo
            if merge:
                cmd.polyMergeVertex(newOb, ch=1, d=thresh)
            selectBorderEdges(newOb)
            cmd.polyExtrudeEdge(ch=1, d=2, lty=edgeAmt)
            cmd.polyExtrudeFacet(newOb, ch=1, kft=True, ltz=extrudeAmt, d=2)
            cmd.select(newOb)
            mel.eval(
                'polyCleanupArgList 4 { "0","1","1","0","1","0","0","0","0","1e-005","0","1e-005","0","1e-005","0","-1","0","0"}'
            )
            cmd.polySoftEdge(newOb, ch=1, a=180)
            cmd.parent(newOb, newGp)
            cmd.setKeyframe('%s.v' % newOb, t=[i - 1, i + 1], v=0)
            cmd.setKeyframe('%s.v' % newOb, t=i, v=1)
            for xyz in ['x', 'y', 'z']:
                cmd.setAttr('%s.t%s' % (newOb, xyz), 0)
            cmd.delete(newOb, ch=True)
            shit = cmd.ls('*%s*' % newName, io=True, type='mesh')
            if shit:
                cmd.delete(shit)

            #check for non-manifold and fix
            if (cmds.polyInfo(newOb, nme=True, nmv=True, nue=True, nuv=True)):
                print('%s had nonmanifold Geo, attempting fix...' % newOb)
                mel.eval(
                    'polyCleanupArgList 4 { "0","1","0","0","0","0","0","0","0","1e-005","0","1e-005","0","1e-005","0","1","0","0" }'
                )
    else:
        cmd.error('You must select only one mesh object')
예제 #32
0
def create_platonic_sphere_a():
    mel.eval(
        'polyPlatonic -primitive 4 -subdivisionMode 0 -subdivisions 1 -radius 1 -sphericalInflation 1;'
    )
    sphere = cmds.ls(selection=True)
    cmds.polySoftEdge(sphere, a=180)
    cmds.select(sphere)
    message = 'Create > Polygon Primitives > <span style=\"color:#FF0000;text-decoration:underline;\">Platonic Solid</span>'
    cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9)
    cmds.inViewMessage(amg='(Settings: Icosahedron, Quads, 1, 1, 1)',
                       pos='botLeft',
                       fade=True,
                       alpha=.9)
예제 #33
0
def add_spikes(obj):
    """This function adds spikes to a polygon object."""

    try:
        polyCount = cmds.polyEvaluate(obj, face=True)
    except:
        raise
    for i in range(0,polyCount):
        face="%s.f[%s]" % (obj,i)
        cmds.polyExtrudeFacet(face, ltz=1, ch=0)
        cmds.polyExtrudeFacet(face, ltz=1, ch=0, ls=[0.1,0.1,0.1])
    cmds.polySoftEdge(obj, a=180, ch=0)
    cmds.select(obj)
예제 #34
0
파일: modeling.py 프로젝트: shrimo/dmptools
def softEdgeSelection(unlockAndHarden=180, history=True):
    """
    unlock normals and soft edge 
    """
    normalAngle = SETTINGS.get('default_normal_angle')
    if normalAngle == None:
        normalAngle = unlockAndHarden
        SETTINGS.add('default_normal_angle', normalAngle)
    if cmds.ls(sl=True):
        newSel = cmds.polyListComponentConversion(fv=True, ff=True, fuv=True, fvf=True, te=True, vfa=True)
        if newSel:
            cmds.select(newSel)
        #cmds.polyNormalPerVertex(ufn=True)
        cmds.polySoftEdge(angle=normalAngle, ch=history)
예제 #35
0
 def prepare_geo(self, original, smooth, smoothValue, projectUV, scaleUV):
     if smooth:
         print '> smooth normals...'
         cmds.polySoftEdge(a=smoothValue, ch=False) 
     if projectUV:
         print '> project uvs...'
         cmds.polyProjection(original+'.f[*]',
                                 ch=False,
                                 type='Planar',
                                 ibd=True,
                                 isu=scaleUV,
                                 isv=scaleUV,
                                 md='y')
     cmds.select(original, r=True)
예제 #36
0
def j_doFreezeVtx(): #10
    u'''
    清除点的位移信息
    '''
    obj = mc.ls(type = "mesh")
    if len(obj) == 0:
            j_text1 = u'There Is No Mesh To Operate !';
            return j_text1 ;    
    mc.select(clear =1)
    for i in obj:
        mc.polySoftEdge( i, a =180 , ch = 0 )
        mc.delete( obj , ch =1 )
        mc.select(obj , r =1)
    print "Complete !!"     
예제 #37
0
def j_doFreezeVtx():  #10
    u'''
    清除点的位移信息
    '''
    obj = mc.ls(type="mesh")
    if len(obj) == 0:
        j_text1 = u'There Is No Mesh To Operate !'
        return j_text1
    mc.select(clear=1)
    for i in obj:
        mc.polySoftEdge(i, a=180, ch=0)
        mc.delete(obj, ch=1)
        mc.select(obj, r=1)
    print "Complete !!"
예제 #38
0
    def importObj(self, file, groupName):
        '''Import and prep an obj file. This is used to import the terrain
		   object as well as the agent geometry objects.'''
        importedNodes = mc.file(file,
                                returnNewNodes=True,
                                type="OBJ",
                                options='mo=0',
                                groupName=groupName,
                                groupReference=True,
                                i=True)
        meshes = mc.ls(importedNodes, long=True, type="mesh")
        for mesh in meshes:
            mc.polySoftEdge(mesh, a=180, ch=False)
        [newGroup] = mc.ls(importedNodes, long=True, assemblies=True)
        return newGroup
예제 #39
0
def apply_hard_soft_edges():
    '''grabs target meshes to match hard soft edges'''
    targets = get_target_meshes(baseObject=cmds.ls(sl=True))

    hardEdges, edgeCount = getInfo(sel=cmds.ls(sl=True))

    for obj in targets:
        '''set all edges to 180'''
        cmds.polySoftEdge(str(obj) + '.e[0:' + str(edgeCount) + ']',
                          angle=180,
                          ch=1)
        print obj
        for edge in hardEdges:
            cmds.polySoftEdge(str(obj) + '.e[0:' + str(edge) + ']',
                              angle=0,
                              ch=1)
예제 #40
0
def setOrigNormalSoft( target ):
    
    ioMeshs = sgModelDag.getIntermediateObjects( target )
    
    for ioMesh in ioMeshs:
        mesh = cmds.createNode( 'mesh' )
        meshObj = sgModelDag.getTransform( mesh )
        cmds.connectAttr( ioMesh+'.outMesh', mesh+'.inMesh' )
        cmds.refresh()
        cmds.disconnectAttr( ioMesh+'.outMesh', mesh+'.inMesh' )
        cmds.polyNormalPerVertex( mesh, ufn=1 )
        cmds.polySoftEdge( mesh, a=180, ch=1 )
        cmds.connectAttr( mesh+'.outMesh', ioMesh+'.inMesh' )
        cmds.refresh()
        cmds.disconnectAttr( mesh+'.outMesh', ioMesh+'.inMesh' )
        cmds.delete( meshObj )
예제 #41
0
def setOrigNormalSoft(target):

    ioMeshs = sgModelDag.getIntermediateObjects(target)

    for ioMesh in ioMeshs:
        mesh = cmds.createNode('mesh')
        meshObj = sgModelDag.getTransform(mesh)
        cmds.connectAttr(ioMesh + '.outMesh', mesh + '.inMesh')
        cmds.refresh()
        cmds.disconnectAttr(ioMesh + '.outMesh', mesh + '.inMesh')
        cmds.polyNormalPerVertex(mesh, ufn=1)
        cmds.polySoftEdge(mesh, a=180, ch=1)
        cmds.connectAttr(mesh + '.outMesh', ioMesh + '.inMesh')
        cmds.refresh()
        cmds.disconnectAttr(mesh + '.outMesh', ioMesh + '.inMesh')
        cmds.delete(meshObj)
예제 #42
0
파일: uv_tools.py 프로젝트: bafly/myScripts
def smooth_shells(lssl=None, hist=None):
    """Usage(optional, select objects):
    >> smooth_shell(hist=False)
    Args:
     - hist, bool, (default True) construction history
    """
    lssl = cm.ls(lssl)
    if not lssl:
        lssl = [x for x 
                  in cm.ls(sl=1)
                  if cm.listRelatives(x, s=1, type="mesh")]
    hist = True if hist is None else hist
    for sel in lssl:
        cm.polySoftEdge(sel, a=180, ch=hist)
        borders = shell_border(sel + ".map[*]")
        # cm.select(borders)
        cm.polySoftEdge(borders, a=0, ch=hist)
예제 #43
0
def addPolyRemeshNodeType(svgTransform, svgExtruder, svgTool, svgMesh, svgAdjuster):
    cmds.select(svgTransform)
    polyRemeshNode = cmds.polyRemesh(nodeState=1, interpolationType=0, tessellateBorders=0, refineThreshold=1.0)[0]

    cmds.addAttr( polyRemeshNode, hidden=True, longName='typeMessage', attributeType='message' )
    cmds.connectAttr( svgTool+'.remeshMessage', polyRemeshNode+'.typeMessage' )

    cmds.connectAttr( svgExtruder+'.capComponents', polyRemeshNode+'.inputComponents' )

    #set normals
    cmds.polySoftEdge(svgMesh, angle=30, ch=1)

    #add the UV proj node
    addUVNodeToSVG(svgTransform, svgExtruder)

    #connect the deformer
    connectSVGShellDeformer(svgMesh, svgTransform, svgExtruder, svgTool, svgAdjuster)

    showThesvgTool(svgTool, svgTransform)
예제 #44
0
 def Action_SelectAngle(self):
     maya_cmds.undoInfo(openChunk=True)
     try:
         maya_cmds.polySoftEdge(caching=True,
                                angle=self.window.Float_SelectAngle.value())
         maya_cmds.polySelectConstraint(mode=2, type=0x8000, smoothness=1)
         mel_eval('resetPolySelectConstraint')
         maya_cmds.polySelectConstraint(mode=2, type=0x8000, propagate=4)
         mel_eval('resetPolySelectConstraint')
         setA = maya_cmds.sets()
         setB = maya_cmds.sets(
             maya_cmds.polyListComponentConversion(maya_cmds.ls(
                 selection=True, objectsOnly=True),
                                                   toEdge=True))
         maya_cmds.select(maya_cmds.sets(setA, subtract=setB))
         maya_cmds.delete(setA, setB)
     except Exception as e:
         print >> stderr, str(e)
     maya_cmds.undoInfo(closeChunk=True)
예제 #45
0
파일: editor.py 프로젝트: McManning/shaders
def resetMesh():
    """Softens, deletes creases, and sets vertex colors to a sane default"""
    selected = cmds.ls(selection=True)

    cmds.select(getParent(selected[0]), replace=True)
    setColorset()

    # Soften all edges
    cmds.select(cmds.polyListComponentConversion(te=True))
    cmds.polySoftEdge(a=180)

    # Reset vertex colors of every vertex to a base color + no crease data
    cmds.select(cmds.polyListComponentConversion(tv=True))

    (r, g, b) = DEFAULT_COLOR
    cmds.polyColorPerVertex(r=r, g=g, b=b, a=0)

    # Restore selection
    cmds.select(selected, replace=True)
예제 #46
0
파일: jimboBalloon.py 프로젝트: radvfx/py
def tieOff():
	global balloonRadius, balloonQuantity
	knotVals = mc.pointPosition('balloonTemp.vtx[96]', w=True)
	knotThickness = balloonRadius * .05
	endHeight = balloonRadius * .15
	knotRadius = knotVals[0]
	knotPos = ( knotVals[1] - (.5 * knotThickness))

	mc.polyCylinder( n="knotTemp", r=knotRadius, h=knotThickness, sx=12, sy=3, sz=0, rcp=0, cuv=3)
	mc.delete( 'knotTemp.f[36:37]')
	mc.setAttr( 'knotTemp.translateY', knotPos )
	mc.scale(1.25, 1.75, 1.25, 'knotTemp.vtx[12:35]', r=True )
	mc.lattice( n='knot', cp=True,  dv =(2, 2, 2), objectCentered=True, ldv=(2,2,2))
	mc.move( (.75 * knotThickness), 'knotLattice.pt[1][0][0:1]', r=True, y=True)
	mc.move( (.25 * knotThickness), 'knotLattice.pt[0][0][0:1]', r=True, y=True)

	mc.duplicate('knotTemp')
	mc.rotate(180, 'knotTemp1', z=True)

	mc.polyCone( n="endTemp", r=knotRadius*2, h=endHeight, sx=12, sy=6, sz=3, rcp=0, cuv=3)
	mc.delete( 'endTemp.f[60:83]', 'endTemp.f[96:107]')
	mc.setAttr( 'endTemp.translateY', knotPos - knotThickness/2 )	
	mc.scale( 1.15, 1, 1.15, 'endTemp.vtx[36:59]') 
	mc.move((.5 * endHeight), 'endTemp.vtx[0:11]', 'endTemp.vtx[72]', y=True, r=True)
	mc.polyUnite( 'balloonTemp', 'knotTemp', 'knotTemp1', 'endTemp', ch=True )
	mc.polySoftEdge( a = 180 )
	mc.polyMergeVertex( d=.001)

	mc.polyEditUV('polySurface1.map[0:126]', pu=0.5, pv=1, su=1, sv=0.575)
	mc.polyEditUV('polySurface1.map[127:230]', pu=0.5, pv=0.35, su=2, sv=.25)
	mc.polyEditUV('polySurface1.map[267:318]', u=0, v=-0.1, pu=0.5, pv=0, su=1, sv=.5)
	mc.polyEditUV('polySurface1.map[231:266]', 'polySurface1.map[319]', u=0, v=-.175, pu=0.5, pv=0.25, su=0.25, sv=0.25)
	mc.polyMergeUV('polySurface1.map[103:126]', d=0.5, ch=True )
	mc.polyEditUV('polySurface1.map[104]',  r=False, u=0)
	mc.polyEditUV('polySurface1.map[103]', r=False, u=1)
	mc.polySmooth('polySurface1',  mth=0, dv=1, c=1, kb=0, ksb=1, khe=0, kt=1, kmb=0, suv=0, peh=0, sl=1, dpe=1, ps=0.1 , ro=1, ch=True)

	mc.DeleteHistory()
	mc.delete( 'knotTemp1')
	mc.rename('polySurface1', 'balloon1')
	mc.select(cl=True)
	return
예제 #47
0
def J_getGeoSmoothNormalToUv():
    sel = om.MGlobal.getActiveSelectionList()
    newDag = cmds.duplicate(sel.getComponent(0))
    cmds.polySoftEdge(newDag, a=180, ch=1)
    cmds.select(newDag)
    mesh = om.MFnMesh(sel.getComponent(0)[0])

    mesh.createUVSet("map5")
    mesh.clearUVs("map5")
    sel = om.MGlobal.getActiveSelectionList()

    mesh1 = om.MFnMesh(sel.getComponent(0)[0])

    faceCount = mesh.numPolygons
    uvid = 0
    for i in range(0, faceCount, 1):
        vertexCount = 0
        for verticesId in mesh.getPolygonVertices(i):
            vertexNormal = mesh.getFaceVertexNormal(i, verticesId)
            vertexBiNormal = mesh.getFaceVertexBinormal(i, verticesId)
            vertexTangent = mesh.getFaceVertexTangent(i, verticesId)
            vertexBiTangent = mesh.getFaceVertexNormal(i, verticesId).__xor__(
                mesh.getFaceVertexTangent(i, verticesId))

            matrix1 = om.MFloatMatrix(
                ((vertexTangent.x, vertexTangent.y, vertexTangent.z,
                  0), (vertexBiTangent.x, vertexBiTangent.y, vertexBiTangent.z,
                       0), (vertexNormal.x, vertexNormal.y, vertexNormal.z, 0),
                 (0, 0, 0, 0)))
            smoothNormal = vertexNormal = mesh1.getFaceVertexNormal(
                i, verticesId)
            matrix2 = om.MFloatMatrix(
                ((smoothNormal.x, 0, 0, 0), (smoothNormal.y, 0, 0, 0),
                 (smoothNormal.z, 0, 0, 0), (0, 0, 0, 0)))
            print matrix1.__mul__(matrix2)
            mesh.setUV(uvid,
                       matrix1.__mul__(matrix2).getElement(0, 0),
                       matrix1.__mul__(matrix2).getElement(1, 0), "map5")

            mesh.assignUV(i, vertexCount, uvid, "map5")
            uvid += 1
            vertexCount += 1
예제 #48
0
def prepare():
    get_ui_values()
    selection = cmds.ls(sl=True)
    cmds.polyPlane(name = "REFPLANE", axis = [0,0,1], width = 1, height = float(resolution_y)/resolution_x, subdivisionsX=1, subdivisionsY=1)
    cmds.move(0.5,float(resolution_y)/resolution_x/2,0)
    ###CREATE ATTRIBUTES
    for obj in selection:
        shape = cmds.listRelatives(obj, shapes=True)
        if (cmds.objectType(shape, isType='pointLight') or cmds.objectType(shape, isType='spotLight')) and cmds.getAttr(obj + '.visibility'):
            cmds.select(shape[0])            
            if not 'hqzLightStart' in cmds.listAttr():
                cmds.addAttr(attributeType = 'float', niceName='HQZ Light Start', longName='hqzLightStart', shortName='hqzls', defaultValue=0, keyable=True)
            if not 'hqzLightEnd' in cmds.listAttr():
                cmds.addAttr(attributeType = 'float', niceName='HQZ Light End', longName='hqzLightEnd', shortName='hqzle', defaultValue=0, keyable=True)
            if not 'hqzSpectralLight' in cmds.listAttr():
                cmds.addAttr(attributeType = 'bool', niceName='HQZ Spectral Light', longName='hqzSpectralLight', shortName='hqzsl', defaultValue=True, keyable=True)
            if not 'hqzSpectralStart' in cmds.listAttr():
                cmds.addAttr(attributeType = 'float', niceName='HQZ Spectral Start', longName='hqzSpectralStart', shortName='hqzss', defaultValue=400, minValue=400, maxValue=700, keyable=True)
            if not 'hqzSpectralEnd' in cmds.listAttr():
                cmds.addAttr(attributeType = 'float', niceName='HQZ Spectral End', longName='hqzSpectralEnd', shortName='hqzse', defaultValue=700, minValue=400, maxValue=700, keyable=True)

        if cmds.objectType(shape, isType='spotLight') and cmds.getAttr(obj + '.visibility'):
            try:
                cmds.setAttr(obj+'.rotateX', 0)
                cmds.setAttr(obj+'.rotateY', -90)
                cmds.setAttr(obj+'.rotateY', lock = True)
                cmds.setAttr(obj+'.rotateX', lock = True)
            except:
                pass
            
        if cmds.objectType(shape, isType='mesh') and (cmds.getAttr(obj + '.v')):
            cmds.select(shape[0])
            if not 'hqzMaterial' in cmds.listAttr():
                cmds.addAttr(attributeType = 'byte', niceName='HQZ Material', longName='hqzMaterial', shortName='hqzmat', defaultValue = 0, keyable = True)
            cmds.polySoftEdge(obj, a = 180, ch = 0)
    
    try:
        cmds.select(selection, replace=True)
    except:
        pass
def makeSeamless(meshName):
	"""Makes a supplied mesh "seamless" in Unity by deleting its UV coordinates, smoothing normals, triangulating, and clearing material assignments"""
	# clear uvs so there are no seams or tangents
	uvs = cmds.polyUVSet(meshName, q=True, auv=True)
	for uv in uvs:
		try: cmds.polyUVSet(meshName, e=True, uvSet=uv, delete=True)
		except: pass
	uvSet = cmds.polyUVSet(meshName, q=True, auv=True)[0]
	sel = om.MSelectionList()
	sel.add(meshName)
	dagPath = om.MDagPath()
	sel.getDagPath(0, dagPath)
	fn = om.MFnMesh(dagPath)
	fn.clearUVs(uvSet)
	# smooth normals so there are no normal separations
	cmds.polySoftEdge(meshName, a=180, ch=True)
	# triangulate geometry
	cmds.polyTriangulate(meshName)
	# apply a single material so there are no submesh separations
	cmds.sets(meshName, e=True, forceElement='initialShadingGroup')
	# delete all history
	cmds.delete(meshName, ch=True)
	cmds.select(clear=True)
def batch_render():
    del_pointcloud()
    #autoload Mental-Ray, from http://forums.cgsociety.org/archive/index.php/t-1001360.html
    #cmds.loadPlugin('Mayatomr', quiet=True)
    #cmds.setAttr('defaultRenderGlobals.ren', 'mentalRay', type='string')
    cmds.undoInfo(state=False)

    #imageFormat 32 means PNG, from here: http://www.oputo.com/html/blog/2010/06/12/defaultrenderglobals-imageformat/
    cmds.setAttr('defaultRenderGlobals.imageFormat', 32)
        
    #hide our TEMPLATE
    cmds.hide( "template_skin" )
    cmds.hide( "template_bone" )

    input_bones_list = cmds.getFileList(folder=path_of_files, filespec='bone*.obj')
    frames_rendered = 0
    for curr_bone in input_bones_list:
        #take off the .obj, then get the last four digits of the name of the file
        #split_name = curr_bone.split('.')
        #file_name = split_name[0]
        #curr_digits = file_name[-4:]
        #print curr_digits
        curr_digits, bone_name, frm_name = get_bone_digit(curr_bone)
        
        # Assign shader to objects
        if draw_mesh:
            cmds.file(path_of_files + bone_name, i=True)
            cmds.file(path_of_files + frm_name, i=True)
            cmds.sets("Mesh", edit=True, forceElement="boneShader")
            frm_mesh_name = "frm" + curr_digits + "_Mesh"
            cmds.sets(frm_mesh_name, edit=True, forceElement="skinShader")
            cmds.select('Mesh')
            cmds.polySoftEdge(a=soften_angle)
            cmds.select(frm_mesh_name)
            cmds.polySoftEdge(a=soften_angle)
        
        #load the point cloud
        if draw_points:
            point_cloud_file = path_of_files + "frm" + curr_digits + ".xyz"
            load_xyz( point_cloud_file )
        
        path_to_file = cmds.render()
        
        if path_to_file[-3:] != "png":
            print "Render is NOT outputting pngs! Quitting..."
            break

        #rename the rendered file
        output_name = "frame" + curr_digits + ".png"
        split_path = path_to_file.split('/')
        split_path[-1] = output_name
        new_path = "/".join(split_path)
        #os.rename(path_to_file, new_path)
        move(path_to_file, new_path)
        print 'RENDERED TO: ', new_path
        
        #delete the meshes
        if draw_mesh:
            cmds.select('Mesh')
            cmds.delete()
            frm_mesh_name = "frm" + curr_digits + "_Mesh"
            cmds.select(frm_mesh_name)
            cmds.delete()
        
        #delete the point cloud
        if draw_points:
            del_pointcloud()
        
        frames_rendered = frames_rendered + 1
        
        if frames_rendered > max_num_frames:
            break
        
    #show our templates
    cmds.showHidden( "template_skin" )
    cmds.showHidden( "template_bone" )
    load_xyz( path_of_files + "frm0000.xyz" )
import maya.cmds as cmds

sels = cmds.listRelatives( cmds.ls( sl=1 ), c=1, ad=1, type='transform' )
if not sels:
    sels = cmds.ls( sl=1 )

targetOrigs= []
for sel in sels:
    shapes = cmds.listRelatives( sel, s=1, f=1 )
    if not shapes: continue
    for shape in shapes:
        if cmds.nodeType( shape ) != 'mesh': continue
        if cmds.listConnections( shape + '.inMesh', s=1, d=0 ): continue
        targetOrigs.append( shape )

for targetOrig in targetOrigs:
    cmds.polyNormalPerVertex( targetOrig, ufn=True )
    cmds.polySoftEdge( targetOrig, a=180, ch=0 )
예제 #52
0
def normHard(*args):
	cmds.polySoftEdge(a=0)
예제 #53
0
def normSoft(*args):
	cmds.polySoftEdge(a=180)
예제 #54
0
 def setObjectToDisplay(self):
     '''
     Sets the object that will be displayed in the viewport
     '''
     #first delete display object if exist
     if self._mVoroDisplay:
         cmds.delete(self._mVoroDisplay)
         self._mVoroDisplay = None                        
     
     # Retrieve breaked object faces
     mVoroOutputMeshFn = OpenMaya.MFnMesh(self._mVoroOutputMeshDAG)
     aAllFaces = cmds.getAttr(self._mVoroOutputMeshDAG.fullPathName() + '.fxFaceIdx')
     fCount = len(aAllFaces)
     
     # Get only internal faces
     aInFaces = [f for f in xrange(fCount) if aAllFaces[f] < 0]
     
     util = OpenMaya.MScriptUtil()
     util.createFromList(aInFaces, len(aInFaces))
     aInFacesIdsPtr = util.asIntPtr()
     aInFacesIds = OpenMaya.MIntArray(aInFacesIdsPtr, len(aInFaces))    
     
     mfnComponents = OpenMaya.MFnSingleIndexedComponent()
     components = mfnComponents.create(OpenMaya.MFn.kMeshPolygonComponent)    
     mfnComponents.addElements(aInFacesIds)
     
     # Iterate over faces and convert to edges
     mFaceEdges = OpenMaya.MIntArray()   
     mOuterEdges = set(xrange(mVoroOutputMeshFn.numEdges()))    
     mInnerEdges = set()
     
     mFaceIter = OpenMaya.MItMeshPolygon(self._mVoroOutputMeshDAG, components)    
     while not mFaceIter.isDone():
         
         mFaceIter.getEdges(mFaceEdges)
         mInnerEdges.update(mFaceEdges)
         mFaceIter.next()
     
     # Select outer edges and apply polySoftEdge
     mOuterEdges.difference_update(mInnerEdges)
     aOuterEdges = list(mOuterEdges)   
     util.createFromList(aOuterEdges, len(aOuterEdges))
     aOuterEdgesIdsPtr = util.asIntPtr()
     aOuterEdgesIds = OpenMaya.MIntArray(aOuterEdgesIdsPtr, len(aOuterEdges))
     
     mfnComponents = OpenMaya.MFnSingleIndexedComponent()
     components = mfnComponents.create(OpenMaya.MFn.kMeshEdgeComponent)    
     mfnComponents.addElements(aOuterEdgesIds)
     
     self._mVoroDisplay = cmds.duplicate(self._mVoroObject, name = 'IS_Display', rc = True, rr = True)        
     mPolyShape = cmds.listRelatives(self._mVoroDisplay[0], fullPath = True)[1]        
     cmds.setAttr(self._mVoroDisplay[0] + '.visibility', True)
     
     mSelection = OpenMaya.MSelectionList()
     mDagPath = OpenMaya.MDagPath()        
     mSelection.add(self._mVoroDisplay[0])
     mSelection.getDagPath(0, mDagPath)
     
     mOuterEdgesSel = OpenMaya.MSelectionList()
     mOuterEdgesSel.add(mDagPath, components)
     OpenMaya.MGlobal.setActiveSelectionList(mOuterEdgesSel)
     
     cmds.polySoftEdge(a = self._mSoften, ws = True, ch = False)
     cmds.setAttr(mPolyShape + '.displayEdges', self._mDisplayType)
     cmds.setAttr(mPolyShape + '.overrideEnabled', True)
     cmds.setAttr(mPolyShape + '.overrideColor', 1)
     
     if (cmds.attributeQuery('hiddenInOutliner', node = self._mVoroDisplay[0], exists = True)):
         cmds.setAttr(self._mVoroDisplay[0] + '.hiddenInOutliner', True)
         
     cmds.select(clear = True)       
예제 #55
0
def positionReorder(**kwargs):
	meshes = kwargs.get('meshes',[])

	################################################################
	#
	# do some error checking
	#
	################################################################

	if len(meshes) < 2:
		cmds.error('please select 2 meshes')
		
	fromMesh = meshes[0]
	toMesh = meshes[1]

	if cmds.nodeType(fromMesh) != 'mesh':
		shapes = cmds.listRelatives( fromMesh, shapes=True)

		if shapes is not None and len(shapes) > 0 and cmds.nodeType(shapes[0]) == 'mesh':
			fromMesh = shapes[0]
		else:
			cmds.error('source mesh was not found')

	if cmds.nodeType(toMesh) != 'mesh':
		shapes = cmds.listRelatives( toMesh, shapes=True)

		if shapes is not None and len(shapes) > 0 and cmds.nodeType(shapes[0]) == 'mesh':
			toMesh = shapes[0]
		else:
			cmds.error('destination mesh was not found')

	if len( cmds.listHistory( toMesh ) ) > 1:
		cmds.error('destination mesh ( '+toMesh+' ) has history, please delete history')

	################################################################
	#
	# use api to get the mesh data from
	# the source and destination meshes
	#
	################################################################
	
	selectionList = om.MSelectionList()
	selectionList.add( fromMesh )
	selectionList.add( toMesh )
	
	fromDagPath = selectionList.getDagPath(0)
	toDagPath = selectionList.getDagPath(1)
	fromMeshFn = om.MFnMesh( fromDagPath )
	toMeshFn = om.MFnMesh( toDagPath )
	fromPoints = fromMeshFn.getPoints()
	toPoints = toMeshFn.getPoints()
	fromDagNodeFn = om.MFnDagNode(fromDagPath)
	toDagNodeFn = om.MFnDagNode(toDagPath)
	fromBoundingBox = fromDagNodeFn.boundingBox
	toBoundingBox = toDagNodeFn.boundingBox

	################################################################
	#
	# More error checking!
	# make sure source mesh doesn't have
	# more points than the destination mesh
	#
	################################################################

	if len(fromPoints) > len(toPoints):
		cmds.error('source mesh ( '+fromMesh+' ) has more points than destination mesh ( '+toMesh+' ). Source mesh must have the same number of points or less points than the destination mesh')

	################################################################
	#
	# build lookup tables for points and faces
	#
	################################################################

	fromVertices = fromMeshFn.getVertices()
	toVertices = toMeshFn.getVertices()

	fromVertPolyTable = [None]*len(fromPoints)
	fromPolyVertTable = []
	index = 0

	for faceID,numberOfVerts in enumerate(fromVertices[0]):
		fromPolyVertTable.append([])

		for x in range(numberOfVerts):
			vertID = fromVertices[1][index]
			fromPolyVertTable[faceID].append(vertID)

			if fromVertPolyTable[vertID] is None:
				fromVertPolyTable[vertID] = [faceID]
			else:
				fromVertPolyTable[vertID].append(faceID)

			index = index+1

	toVertPolyTable = [None]*len(toPoints)
	toPolyVertTable = []
	index = 0

	for faceID,numberOfVerts in enumerate(toVertices[0]):
		toPolyVertTable.append([])

		for x in range(numberOfVerts):
			vertID = toVertices[1][index]
			toPolyVertTable[faceID].append(vertID)
			
			if toVertPolyTable[vertID] is None:
				toVertPolyTable[vertID] = [faceID]
			else:
				toVertPolyTable[vertID].append(faceID)

			index = index+1

	################################################################
	#
	# create a list of destination points that
	# are in the bounding box of the source
	# mesh and have a matching point
	#
	################################################################

	toSearchPoints = {}
	toMatchingPoints = {}
	for index,point in enumerate(toPoints):
		if fromBoundingBox.contains(point):
			matchingPoint = findMatchingPoint(point=point, meshFn=fromMeshFn, meshPoints=fromPoints)

			if matchingPoint != None:
				#print(index,matchingPoint)
				toSearchPoints[index] = None
				toMatchingPoints[index] = matchingPoint

	################################################################
	#
	# create a list of destination faceIds
	# associated with bounding box points
	#
	################################################################

	toMatchingPolys = {}
	toBorderingPolys = {}

	for toIndex in toSearchPoints:
		toPolyIds = toVertPolyTable[toIndex]

		for toPolyId in toPolyIds:
			toVerts = toPolyVertTable[toPolyId]

			for toVert in toVerts:
				found = toSearchPoints.get(toVert,False)
				#toUsePoints[toVert] = False

				if found == False:
					toBorderingPolys[toPolyId] = True
				else:
					toMatchingPolys[toPolyId] = True

	# just a double check to make sure the matching
	# polys list doesn't contain any connecting polys items
	for toPolyId in toBorderingPolys:
		toMatchingPolys.pop(toPolyId,False)

	################################################################
	#
	# Find any matching points, from the connecting polys,
	# between the source and destination meshes
	#
	################################################################

	toPointsConvert = {}

	for toPolyId in toBorderingPolys:
		toPolyVerts = toMeshFn.getPolygonVertices( toPolyId )
		
		for toPolyVert in toPolyVerts:
			matchingPoint = toMatchingPoints.get(toPolyVert,None)

			if matchingPoint != None:
				toPointsConvert[toPolyVert] = matchingPoint


	################################################################
	#
	# create points conversion table for the destination mesh
	#
	################################################################
	
	newIndex = len(fromPoints)
	for toIndex,toPoint in enumerate(toPoints):
		matchingPointFound = toMatchingPoints.get(toIndex,None)

		if matchingPointFound == None:
			toPointsConvert[toIndex] = newIndex
			newIndex = newIndex+1

	################################################################
	#
	# new points, poly and polyconnects lists
	#
	################################################################

	newPoints = om.MPointArray()
	newPoints.setLength( len(toPoints) )
	newPolys = []
	newPolyConnects = []

	################################################################
	#
	# get info from the source mesh (the from mesh)
	#
	################################################################

	for index,fromPoint in enumerate(fromPoints):
		newPoints[index] = fromPoint

	for fromPolyVerts in fromPolyVertTable:
		newPolys.append(len(fromPolyVerts))

		for fromPolyVert in fromPolyVerts:
			newPolyConnects.append(fromPolyVert)

	################################################################
	#
	# get data from the destination mesh (the to mesh)
	#
	################################################################
	
	for toPointId,toPointConvertId in toPointsConvert.iteritems():
		newPoints[toPointConvertId] = toPoints[toPointId]

	for toPolyId,toPolyVerts in enumerate(toPolyVertTable):
		isMatchingPoly = toMatchingPolys.get(toPolyId,None)

		if isMatchingPoly == None:
			newPolys.append(len(toPolyVerts))

			for toPolyVert in toPolyVerts:
				newPolyConnects.append(toPointsConvert[toPolyVert])

	################################################################
	#
	# create a new mesh with the vertex IDs reordered
	#
	################################################################

	reorderedMesh = om.MFnMesh()
	reorderedMesh.create( newPoints, newPolys, newPolyConnects )
	meshShape = reorderedMesh.partialPathName()
	meshTransform = cmds.listRelatives(meshShape,parent=True)[0]
	cmds.select(meshTransform)
	cmds.hyperShade(assign='initialShadingGroup')
	cmds.polySoftEdge(meshTransform, angle=0, ch=False)

	toMeshTransform = cmds.listRelatives(toMesh,parent=True)[0]
	newMeshName = cmds.rename(meshTransform,toMeshTransform+'_reordered')
	cmds.select(newMeshName)

	print('Finished Reordering Vertex IDs')
예제 #56
0
def traverseReorder(**kwargs):
	faces = kwargs.get('faces',[])
	vertex1s = kwargs.get('vertex1s',[])
	vertex2s = kwargs.get('vertex2s',[])
	targetList = kwargs.get('targetList',[])

	fromMesh = cmds.listRelatives(faces[0],parent=True)[0]
	toMesh = cmds.listRelatives(faces[1],parent=True)[0]

	fromFaceId = extractIndex(faces[0])
	fromVertex1Id = extractIndex(vertex1s[0])
	fromVertex2Id = extractIndex(vertex2s[0])

	toFaceId = extractIndex(faces[1])
	toVertex1Id = extractIndex(vertex1s[1])
	toVertex2Id = extractIndex(vertex2s[1])

	################################################################
	#
	# use api to get the mesh data from
	# the source and destination meshes
	#
	################################################################
	
	selectionList = om.MSelectionList()
	selectionList.add( fromMesh )
	selectionList.add( toMesh )
	
	fromDagPath = selectionList.getDagPath(0)
	toDagPath = selectionList.getDagPath(1)
	fromMeshFn = om.MFnMesh( fromDagPath )
	toMeshFn = om.MFnMesh( toDagPath )
	fromPoints = fromMeshFn.getPoints()
	toPoints = toMeshFn.getPoints()
	fromDagNodeFn = om.MFnDagNode(fromDagPath)
	toDagNodeFn = om.MFnDagNode(toDagPath)

	################################################################
	#
	# start creation of poly and point convert tables
	#
	################################################################

	toPointConvert = [None]*len(toPoints)
	toPointConvert[toVertex1Id] = fromVertex1Id
	toPointConvert[toVertex2Id] = fromVertex2Id

	################################################################
	#
	# build lookup tables for points and faces
	#
	################################################################

	fromVertices = fromMeshFn.getVertices()
	toVertices = toMeshFn.getVertices()

	fromVertPolyTable = [None]*len(fromPoints)
	fromPolyVertTable = []
	index = 0

	for faceID,numberOfVerts in enumerate(fromVertices[0]):
		fromPolyVertTable.append([])

		for x in range(numberOfVerts):
			vertID = fromVertices[1][index]
			fromPolyVertTable[faceID].append(vertID)

			if fromVertPolyTable[vertID] is None:
				fromVertPolyTable[vertID] = [faceID]
			else:
				fromVertPolyTable[vertID].append(faceID)

			index = index+1

	toVertPolyTable = [None]*len(toPoints)
	toPolyVertTable = []
	index = 0

	for faceID,numberOfVerts in enumerate(toVertices[0]):
		toPolyVertTable.append([])

		for x in range(numberOfVerts):
			vertID = toVertices[1][index]
			toPolyVertTable[faceID].append(vertID)
			
			if toVertPolyTable[vertID] is None:
				toVertPolyTable[vertID] = [faceID]
			else:
				toVertPolyTable[vertID].append(faceID)

			index = index+1

	fromPolyId = fromFaceId
	toPolyId = toFaceId
	fromStartVertexId = fromVertex1Id
	fromEndVertexId = fromVertex2Id
	toStartVertexId = toVertex1Id
	toEndVertexId = toVertex2Id

	fromPolyData = traversePoly( fromPolyId, fromStartVertexId, fromEndVertexId, fromPolyVertTable[fromPolyId] )
	toPolyData = traversePoly( toPolyId, toStartVertexId, toEndVertexId, toPolyVertTable[toPolyId] )

	fromCheckPolys = [fromPolyData]
	toCheckPolys = [toPolyData]

	fromPolysFound = [False]*len(fromVertices[0])
	toPolysFound = [False]*len(toVertices[0])

	for count in range( len(fromPolyVertTable) ):
		newFromCheckPolys = []
		newToCheckPolys = []
		newFromCheckPolyIDs = []
		newToCheckPolyIDs = []

		for checkIndex,checkItem in enumerate(fromCheckPolys):
			fromPolyId = fromCheckPolys[checkIndex]['id']
			toPolyId = toCheckPolys[checkIndex]['id']
			fromPolyEdges = fromCheckPolys[checkIndex]['edges']
			toPolyEdges = toCheckPolys[checkIndex]['edges']

			fromPolysFound[fromPolyId] = True
			toPolysFound[toPolyId] = True
			
			for edgeIndex,edgeItem in enumerate(fromPolyEdges):
				fromStartVertexId = fromPolyEdges[edgeIndex][0]
				fromEndVertexId = fromPolyEdges[edgeIndex][1]
				toStartVertexId = toPolyEdges[edgeIndex][0]
				toEndVertexId = toPolyEdges[edgeIndex][1]

				fromConnectingPolyId = getConnectingPoly( fromPolyId, set(fromVertPolyTable[fromStartVertexId]), set(fromVertPolyTable[fromEndVertexId]) )
				toConnectingPolyId = getConnectingPoly( toPolyId, set(toVertPolyTable[toStartVertexId]), set(toVertPolyTable[toEndVertexId]) )

				if fromConnectingPolyId != None and toConnectingPolyId != None:
					fromPolyData = traversePoly( fromConnectingPolyId, fromStartVertexId, fromEndVertexId, fromPolyVertTable[fromConnectingPolyId] )
					toPolyData = traversePoly( toConnectingPolyId, toStartVertexId, toEndVertexId, toPolyVertTable[toConnectingPolyId] )

					fromPolyPoints = fromPolyData['polyPoints']
					toPolyPoints = toPolyData['polyPoints']

					for fromPolyPointIndex,fromPolyPoint in enumerate(fromPolyPoints):
						fromPolyPointId = fromPolyPoints[fromPolyPointIndex]
						toPolyPointId = toPolyPoints[fromPolyPointIndex]
						toPointConvert[toPolyPointId] = fromPolyPointId

					if not fromPolysFound[fromPolyData['id']] and fromPolyData['id'] not in newFromCheckPolyIDs:
						newFromCheckPolyIDs.append( fromPolyData['id'] )
						newFromCheckPolys.append( fromPolyData )
						newToCheckPolys.append( toPolyData )

		fromCheckPolys = list(newFromCheckPolys)
		toCheckPolys = list(newToCheckPolys)

	newToPointConvert = [None]*len(toPoints)

	newPolys = []
	newPolyConnects = []

	newIndex = len(fromPoints)
	for toId,fromId in enumerate(toPointConvert):
		if fromId == None:
			newToPointConvert[toId] = newIndex
			newIndex = newIndex+1
		else:
			newToPointConvert[toId] = fromId

	index = 0
	for faceID,numberOfVerts in enumerate(toVertices[0]):
		newPolys.append(numberOfVerts)

		for x in range(numberOfVerts):
			vertID = toVertices[1][index]
			newPolyConnects.append( newToPointConvert[vertID] )

			index = index+1

	################################################################
	#
	# create a new mesh with the vertex IDs reordered
	#
	################################################################

	if len(targetList) > 0:
		for target in targetList:

			################################################################
			#
			# use api to get the target mesh points list
			#
			################################################################

			targetMesh = cmds.listRelatives( target, shapes=True )[0]
			
			targetSelectionList = om.MSelectionList()
			targetSelectionList.add( targetMesh )
			
			targetDagPath = targetSelectionList.getDagPath(0)
			targetMeshFn = om.MFnMesh( targetDagPath )
			targetPoints = targetMeshFn.getPoints()

			newTargetPoints = om.MPointArray()
			newTargetPoints.setLength( len(targetPoints) )

			for toId,fromId in enumerate(newToPointConvert):
				newTargetPoints[fromId] = targetPoints[toId]

			reorderedMesh = om.MFnMesh()
			reorderedMesh.create( newTargetPoints, newPolys, newPolyConnects )
			meshShape = reorderedMesh.partialPathName()
			meshTransform = cmds.listRelatives(meshShape,parent=True)[0]
			cmds.select(meshTransform)
			cmds.hyperShade(assign='initialShadingGroup')
			cmds.polySoftEdge(meshTransform, angle=0, ch=False)

			#toMeshTransform = cmds.listRelatives(toMesh,parent=True)[0]
			newMeshTransform = cmds.rename(meshTransform,target+'_reordered')

			# copy and paste transform attributes
			t = cmds.getAttr(target+'.translate')[0]
			r = cmds.getAttr(target+'.rotate')[0]
			s = cmds.getAttr(target+'.scale')[0]

			cmds.setAttr( newMeshTransform+'.translate', t[0], t[1], t[2] )
			cmds.setAttr( newMeshTransform+'.rotate', r[0], r[1], r[2] )
			cmds.setAttr( newMeshTransform+'.scale', s[0], s[1], s[2] )

			cmds.select(newMeshTransform)

	else:
		newPoints = om.MPointArray()
		newPoints.setLength( len(toPoints) )

		for toId,fromId in enumerate(newToPointConvert):
			newPoints[fromId] = toPoints[toId]

		reorderedMesh = om.MFnMesh()
		reorderedMesh.create( newPoints, newPolys, newPolyConnects )
		meshShape = reorderedMesh.partialPathName()
		meshTransform = cmds.listRelatives(meshShape,parent=True)[0]
		cmds.select(meshTransform)
		cmds.hyperShade(assign='initialShadingGroup')
		cmds.polySoftEdge(meshTransform, angle=0, ch=False)

		toMeshTransform = cmds.listRelatives(toMesh,parent=True)[0]
		newMeshTransform = cmds.rename(meshTransform,toMeshTransform+'_reordered')

		# copy and paste transform attributes
		t = cmds.getAttr(toMeshTransform+'.translate')[0]
		r = cmds.getAttr(toMeshTransform+'.rotate')[0]
		s = cmds.getAttr(toMeshTransform+'.scale')[0]

		cmds.setAttr( newMeshTransform+'.translate', t[0], t[1], t[2] )
		cmds.setAttr( newMeshTransform+'.rotate', r[0], r[1], r[2] )
		cmds.setAttr( newMeshTransform+'.scale', s[0], s[1], s[2] )

		cmds.select(newMeshTransform)

	print('Finished Reordering Vertex IDs')
def hardenNormals(*args):
    cmds.polySoftEdge(a=0, ch=True)
    print 'Harden Normals Edges'
def softenNormals(*args):
    cmds.polySoftEdge(a=180, ch=True)
    print 'Soften Normals Edges'