Esempio n. 1
0
def snapShapeToNeutral(source, target):
    '''
	Take a mesh, and find the closest location on the target head, and snap to that
	Then set up a blendShape so the artist can "paint" in the snapping behavior
	'''
    # Make a duplicate of the source and snap it to the target
    snapShape = cmds.duplicate(source, name='snp')
    cmds.transferAttributes(
        target,
        snapShape,
        transferPositions=1,
        sampleSpace=1,  # 0=World, 1=Local, 3=UV
        searchMethod=0,  # 0=Along Normal, 1=Closest Location
    )

    # Then delete history
    cmds.delete(snapShape, constructionHistory=True)
    cmds.hide(snapShape)

    # Blend the source to the snappedShape
    bs = cmds.blendShape(snapShape, source)[0]
    cmds.blendShape(bs, edit=True, weight=((0, 1)))

    # But set the weights back to 0.0 for painting
    numVerts = cmds.polyEvaluate(source, vertex=1)
    setter = '{0}.inputTarget[0].inputTargetGroup[0].targetWeights[0:{1}]'.format(
        bs, numVerts - 1)
    weights = [0.0] * numVerts
    cmds.setAttr(setter, *weights, size=numVerts)
Esempio n. 2
0
def convert_edge_lock():
    sel = cmds.ls(sl=True, l=True)
    meshes = common.search_polygon_mesh(sel, serchChildeNode=False)
    if not meshes:
        return
    for mesh in meshes:
        d_mesh = cmds.duplicate(mesh, rr=True)[0]
        modeling.setSoftEdge(mesh, angle=120)
        cmds.transferAttributes(
            d_mesh,
            mesh,
            flipUVs=0,
            transferPositions=0,
            transferUVs=0,
            sourceUvSpace="map1",
            searchMethod=3,
            transferNormals=1,
            transferColors=0,
            targetUvSpace="map1",
            colorBorders=1,
            sampleSpace=5,
        )
        freeze.main(mesh)
        cmds.polyNormalPerVertex(mesh, ufn=True)
        cmds.delete(d_mesh)
    cmds.select(meshes)
Esempio n. 3
0
def clean_uv_transfer():
    """
    It's a script to copy the uv from one mesh to a another skinned mesh
    Select the mesh you want to copy from, then skinned mesh and run the script.
    """

    selList = cmds.ls(sl=True, ap=True, long=True)
    #ERROR CHECK
    if len(selList) != 2:
        cmds.warning('Please select your source AND target object only')
    else:
        #GETTING TRANSFORM OF TGT AND SHAPE OF DEST NODE
        source, target = selList[0], selList[1]
        tgtList = cmds.listRelatives(target, s=True)
        tgtInd = [i for i, elem in enumerate(tgtList) if 'Orig' in elem]
        tgtOrig = target + '|' + tgtList[tgtInd[0]]
        #GETTING ACCESS TO ORIG NODE AND EXECUTION
        cmds.setAttr('{}.intermediateObject'.format(tgtOrig), 0)
        cmds.select(cl=True)
        cmds.select(source)
        cmds.select(tgtOrig, add=True)
        cmds.transferAttributes(pos=0,
                                nml=0,
                                uvs=2,
                                col=2,
                                spa=4,
                                suv='map1',
                                tuv='map1',
                                sm=3,
                                fuv=0,
                                clb=1)
        cmds.delete(tgtOrig, ch=True)
        cmds.setAttr(tgtOrig + '.intermediateObject', 1)
Esempio n. 4
0
def copy_user_attr(selparentshapes, seltargetshapes, copyUV=True):
    listattrvalue = {}
    listdatatype = {}
    userattr = cmds.listAttr(selparentshapes, ud=True)
    if copyUV and cmds.nodeType(seltargetshapes) == 'mesh' and cmds.nodeType(selparentshapes) == 'mesh':
            cmds.transferAttributes(selparentshapes, seltargetshapes, transferUVs=1, transferColors=2, searchMethod=3, sampleSpace=5, flipUVs=False)
    if userattr:
        for attr in userattr:
            nodetype = cmds.nodeType(selparentshapes)
            checkrendershape = cmds.getAttr(selparentshapes + '.intermediateObject')
            if checkrendershape != 1 or nodetype != 'mesh':
                key = attr
                value = cmds.getAttr("%s.%s" % (selparentshapes, key))
                data = cmds.getAttr("%s.%s" % (selparentshapes, key), typ=True)
                listattrvalue[key] = value
                listdatatype[key] = data
    checkrendershape = cmds.getAttr(seltargetshapes + '.intermediateObject')
    if checkrendershape != 1:
        for key in listattrvalue:
            if not cmds.attributeQuery(key, node=seltargetshapes, ex=True):
                if listdatatype[key] == 'string':
                    cmds.addAttr(seltargetshapes, longName=key, dataType=listdatatype[key])
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                else:
                    cmds.addAttr(seltargetshapes, longName=key)
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
            else:
                cmds.warning('Attribute ' + key + ' already on ' + seltargetshapes)
                if cmds.getAttr("%s.%s" % (seltargetshapes, key), se=True):
                    if listdatatype[key] == 'string':
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                    else:
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
Esempio n. 5
0
def mirroringUVs(mirroringSpace, *args):
    print mirroringSpace
    if mirroringSpace == 1:
        xValue = -1.0
        yValue = 1.0
        zValue = 1.0
    elif mirroringSpace == 2:
        xValue = 1.0
        yValue = -1.0
        zValue = 1.0
    elif mirroringSpace == 3:
        xValue = 1.0
        yValue = 1.0
        zValue = -1.0
    cmds.transferAttributes(
        transferPositions=0,
        transferNormals=0,
        transferUVs=1,  # single uvset
        transferColors=0,
        sampleSpace=0,  # world space
        searchMethod=3,
        searchScaleX=xValue,
        searchScaleY=yValue,
        searchScaleZ=zValue,
        flipUVs=1)
Esempio n. 6
0
def ProcessMeshesPair(pBaseFile, pSubdFile, pOutputDir):
    cmds.file(newFile=True, force=True)
    baseMesh = cmds.file(pBaseFile, i=True, returnNewNodes=True)[0]
    baseMesh = cmds.rename(baseMesh, 'BaseMesh')

    subdMesh = cmds.file(pSubdFile, i=True, returnNewNodes=True)[0]
    subdMesh = cmds.rename(subdMesh, 'SubdMesh')
    cmds.xform(subdMesh, absolute=True, translation=[0, 0, 100])

    with DebugTimer('Processing base resolution'):
        cmds.transferAttributes(subdMesh,
                                baseMesh,
                                transferPositions=1,
                                transferNormals=0,
                                sampleSpace=3)
        cmds.delete(baseMesh, constructionHistory=True)

        #Transfer eyesockets vertices manually to fix 'spikes' error
        eyeSocketFaces = libHazardSelectionUtils.GetFacesInUVRange(
            'BaseMesh', pFrom=[0.3, 0.9], pTo=[0.7, 1])
        tempShape = cmds.duplicate(
            subdMesh, name='Temp' + 'SubdMesh'
        )[0]  #temp shape with high poly eye sockets only to speed up calculations
        cmds.xform(tempShape, absolute=True, translation=[0, 0, 150])
        subdEyeSocketFaces = libHazardSelectionUtils.GetFacesInUVRange(
            tempShape, pFrom=[0.3, 0.8], pTo=[0.7, 1], pInvertResult=True)
        cmds.delete(subdEyeSocketFaces)
        cmds.delete(tempShape, constructionHistory=True)
        TransferAttributesManuallyUVSpace(tempShape, eyeSocketFaces)
        cmds.delete(tempShape)

        cmds.delete(baseMesh, constructionHistory=True)

    #Export baseMesh Here
    fileUtils.ExportObj(baseMesh, pOutputDir, env.PROCESSED_BASE_MESH_NAME)
Esempio n. 7
0
def makeCopies(default_blendshape, target_mesh):
    
    target_mesh_copy = cmds.duplicate(target_mesh, n='{}_COPY'.format(target_mesh), 
                                      returnRootsOnly=True)
                                          
    cmds.transferAttributes(default_blendshape, target_mesh,
                            transferPositions=1,
                            transferNormals=0,
                            transferUVs=2,
                            transferColors=2,
                            sampleSpace=3,
                            sourceUvSpace=utils.getCurrentUV(default_blendshape),
                            targetUvSpace=utils.getCurrentUV(target_mesh),
                            searchMethod=3,
                            flipUVs=0,
                            colorBorders=1)
                            
    target_mesh_final = cmds.duplicate(target_mesh, n='{}_FINAL'.format(target_mesh), 
                                      returnRootsOnly=True)
                                      
    create_blendshape = cmds.blendShape(target_mesh, target_mesh_copy, target_mesh_final, 
                    automatic=True, name='{}_BS'.format(default_blendshape))

    cmds.blendShape('{}.{}'.format(create_blendshape[0], 
                    target_mesh), edit=True, 
                    w=[(0, 1.0), (1, 1.0)])
                    
    cmds.delete(target_mesh_copy)
    
    # returns the mesh that will serve as a dummy to create new duplicates from
    return target_mesh_final
Esempio n. 8
0
def transfertRemeshed(*args):
    
    
    remeshList = cmds.listRelatives('remesh_GRP', c=True, ad=True,  typ='mesh')
    
    if len(remeshList)==0:
        cmds.warning('No remesh GRP')
    else:
        for mesh in remeshList :
            meshTR = cmds.listRelatives('*'+mesh, p=True)[0]
            flatObj = cmds.ls(meshTR, l=True)
            
            origFlat = ''
            remeshFlat = ''
            
            for f in flatObj:
                if 'remesh' in f:
                    remeshFlat = f
                else:
                    origFlat = f
            
            cmds.transferAttributes(origFlat, remeshFlat, transferUVs=2, spa=0, suv='map1', tuv= 'map1', sm=3)
            cmds.delete(remeshFlat, ch=True)
            
            costumePiece = meshTR.replace('_flat', '')
            
            cmds.transferAttributes( costumePiece, remeshFlat, pos=1, spa=3, sus= 'map1', tus= 'map1', sm=3 )
            cmds.delete(remeshFlat, ch=True)
Esempio n. 9
0
def transferUVs():
    cH = cmds.checkBox('cH', q=True, v=True)

    sel = cmds.ls(sl=True)
    for i in range(len(sel)):

        # Handling multiple objects
        if (len(sel) > 2):
            cmds.select(sel[0], r=True)
            cmds.select(sel[i], add=True)
            cmds.transferAttributes(transferUVs=2, sampleSpace=5)

        elif (len(sel) == 2):
            cmds.transferAttributes(transferUVs=2, sampleSpace=5)

        else:
            cmds.error(
                'Please select the source object first, and at least one target object.'
            )

    # Deleting History if chosen
    if (cH == 1):
        cmds.select(sel[1:len(sel)])
        cmds.DeleteHistory()

    cmds.select(sel, r=True)
Esempio n. 10
0
def transfertUVtoHierarchy():

    objList = cmds.listRelatives(cmds.ls(sl=True, l=True),
                                 typ='transform',
                                 c=True,
                                 ad=True,
                                 f=True)

    for o in objList:
        shortName = cmds.ls(o, sn=True)[0]

        objParent = cmds.listRelatives(o, p=True, f=True)[0]
        objectChildren = cmds.listRelatives(o, c=True, typ='transform')

        cmds.parent(o, w=True)
        if objectChildren:
            cmds.parent(objectChildren, w=True)

        cmds.transferAttributes('temp:' + shortName,
                                shortName,
                                transferUVs=2,
                                spa=4)
        cmds.delete(shortName, ch=True)
        cmds.delete('temp:' + shortName)

        if objectChildren:
            cmds.parent(objectChildren, shortName)
        cmds.parent(shortName, objParent)

        print "UVs transfer successfully on " + str(
            objList.index(o) + 1) + '/' + str(len(objList)) + ' objects.'
Esempio n. 11
0
def TryLoadExternalUVs():
    with mayaUtils.DebugTimer('TryLoadExternalUVs'):
        mainMesh = mayaUtils.FindMeshByWildcard('Genesis8Female*',
                                                checkForMatWithName='Torso')

        if mainMesh is None:
            print 'Error! Can`t find body(Torso) mesh'
            return

        cmds.delete(mainMesh, constructionHistory=True)

        uvMeshFile = os.path.join(env.GetIntermediateFullPath(),
                                  env.BASE_FEMALE_MESH_WITH_UV1_NAME + '.obj')
        uvMeshFileExist = os.path.exists(uvMeshFile)

        print 'UV mesh file: {} Exist: {}'.format(uvMeshFile, uvMeshFileExist)
        if not uvMeshFileExist:
            print 'ABORTED: no uv mesh file found'
            return

        uvMesh = cmds.file(uvMeshFile, i=True, returnNewNodes=True)[0]
        uvMesh = cmds.rename(uvMesh, 'UV_Source')
        cmds.xform(uvMesh, absolute=True, translation=[0, 0, 100])

        cmds.polyUVSet(mainMesh, create=True, uvSet='Tesselation_UV')
        cmds.transferAttributes(uvMesh,
                                mainMesh,
                                transferPositions=0,
                                transferNormals=0,
                                transferUVs=1,
                                sourceUvSet='map1',
                                targetUvSet='Tesselation_UV',
                                sampleSpace=5)
        cmds.delete(mainMesh, constructionHistory=True)
        cmds.delete(uvMesh)
Esempio n. 12
0
 def clean_parts(self, parts, mesh):
     # group parts
     cmds.select(clear=True)
     [[cmds.select(node, add=True) for node in part] for part in parts.values()]
     cmds.group(n='terrain_grp')
     cmds.parent(w=True)
     partsList = cmds.listRelatives(cmds.ls(sl=True), f=True)
     # delete empty groups and transfer normals
     i = 1
     for part in partsList:
         if cmds.listRelatives(part):
             newname = 'terrain_part'+str(i)
             print '> transfering normals on', newname
             cmds.transferAttributes(mesh, part,
                                     transferPositions=0,
                                     transferNormals=1,
                                     transferUVs=0,
                                     transferColors=2,
                                     sampleSpace=0,
                                     sourceUvSpace="map1",
                                     targetUvSpace="map1",
                                     searchMethod=3,
                                     flipUVs=0,
                                     colorBorders=1)
             cmds.delete(part, ch=True)
             cmds.rename(part, newname)
             i += 1
         else:
             cmds.delete(part)
Esempio n. 13
0
def transferUvHierarchy( fromTopGroup, toTopGroup):
    fromChildren = cmds.listRelatives( fromTopGroup, ad=True, type='mesh', fullPath=True)[1:]
    toChildren = cmds.listRelatives( toTopGroup, ad=True, type='mesh', fullPath=True)[1:]
    
    print fromChildren
    tmp = copy.copy(fromChildren)
    for fChild in tmp:
        split = fChild.split("|")[1:]
        #print split
        split[0] = toTopGroup
        tChild = "|" + "|".join( split)
        print fChild, tChild
        if tChild in toChildren:
            
            fromChildren.remove( fChild)
            toChildren.remove( tChild)
            cmds.select( fChild, r=True)
            tShapes = getShapes(tChild)
            print 'transfered \n%s \n | \n%s' % (fChild, tChild)
            tChildShapeOrig = tShapes[0]+'Orig'
            
            if (cmds.objectType(fChild) == 'transform' and cmds.objectType(tChild) == 'transform' and cmds.objectType(tChildShapeOrig) == 'mesh'):
                cmds.select( tChildShapeOrig, add=True)
                cmds.transferAttributes( transferPositions=0, transferNormals=0, transferUVs=2, transferColors=0, sampleSpace=4, sourceUvSpace="map1", targetUvSpace="map1", searchMethod=3, flipUVs=0, colorBorders=1)
    print toChildren
    print fromChildren
def J_CFXWorkFlow_copyDeformAnimation(sourceMesh='',
                                      deatnationMesh='',
                                      _sampleSpace=4,
                                      startTime=0,
                                      endTime=0):
    if sourceMesh == '':
        if len(cmds.ls(sl=True)) < 2:
            return
        sourceMeshs = J_getAllMeshUnderSelections(cmds.ls(sl=True)[0])
    else:
        sourceMeshs = J_getAllMeshUnderSelections(sourceMesh)

    if deatnationMesh == '':
        if len(cmds.ls(sl=True)) < 2:
            return
        destinationMeshs = J_getAllMeshUnderSelections(cmds.ls(sl=True)[1])
    else:
        destinationMeshs = J_getAllMeshUnderSelections(deatnationMesh)
    #print sourceMeshs
    #print destinationMeshs
    for sourceMeshItem in sourceMeshs:
        for destinationMeshItem in destinationMeshs:
            if J_compareMesh(sourceMeshItem, destinationMeshItem, 5):
                cmds.transferAttributes(sourceMeshItem,
                                        destinationMeshItem,
                                        transferPositions=1,
                                        transferNormals=0,
                                        transferUVs=0,
                                        transferColors=0,
                                        sampleSpace=_sampleSpace,
                                        sourceUvSpace="map1",
                                        targetUvSpace="map1",
                                        searchMethod=3,
                                        flipUVs=0,
                                        colorBorders=1)
Esempio n. 15
0
 def makePairs(self):
     sel = cmds.ls(os=1)
     garments = cmds.listRelatives(sel[0])  # len(garments)
     patterns = cmds.listRelatives(sel[1])  # len(patterns)
     retopos = cmds.listRelatives(sel[2])  # len(retopos)
     retopos_BB_width = {}
     retopos_BB_length = {}
     retopos_BB_center = {}
     patterns_BB_width = {}
     patterns_BB_length = {}
     patterns_BB_center = {}
     # In case that uv doesn't exists.
     cmds.select(retopos, r=1)
     mel.eval("performPolyAutoProj 0;")
     cmds.select(sel, r=1)
     # In case wrong bb
     for i in retopos:
         cmds.polyMergeVertex(i, d=0.001)
     # Matching
     for i in retopos:
         BB = cmds.polyEvaluate(i, b=1)
         retopos_BB_width[i] = BB[0][1] - BB[0][0]
         retopos_BB_length[i] = BB[1][1] - BB[1][0]
         retopos_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                 (BB[1][1] + BB[1][0]) / 2]
     for i in patterns:
         BB = cmds.polyEvaluate(i, b=1)
         patterns_BB_width[i] = BB[0][1] - BB[0][0]
         patterns_BB_length[i] = BB[1][1] - BB[1][0]
         patterns_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                  (BB[1][1] + BB[1][0]) / 2]
     pair_pattern_retopo = {}  # len(pair_pattern_retopo)
     for i in patterns:
         for j in retopos:
             if      abs(patterns_BB_width[i] - retopos_BB_width[j])         < 1 \
                 and abs(patterns_BB_length[i] - retopos_BB_length[j])       < 1 \
                 and abs(patterns_BB_center[i][0] - retopos_BB_center[j][0]) < 1 \
                 and abs(patterns_BB_center[i][1] - retopos_BB_center[j][1]) < 1:
                 pair_pattern_retopo[i] = j
     for i in pair_pattern_retopo:
         cmds.transferAttributes(i, pair_pattern_retopo[i], transferUVs=1)
     for i in pair_pattern_retopo:
         cmds.select(pair_pattern_retopo[i], i, r=1)
         cmds.CreateWrap()
     for i in pair_pattern_retopo:
         pairGarment = i[:-8]
         pattern = i
         blendObjs = [pairGarment, pattern]  # 0: target 1: origin
         blendName = cmds.blendShape(blendObjs,
                                     o='world',
                                     n='clothTransfer#')
         cmds.hide(sel[1])
         cmds.displaySurface(sel[0], x=1)
     cmds.hide(sel[1])
     cmds.displaySurface(sel[0], x=1)
     layerName = cmds.createDisplayLayer(n="garment#", e=1)
     cmds.editDisplayLayerMembers(layerName, sel[0])
     cmds.setAttr(layerName + '.displayType', 2)
Esempio n. 16
0
 def copy_user_attr(self, selparentshapes, seltargetshapes, copyUV=True):
     listattrvalue = {}
     listdatatype = {}
     userattr = cmds.listAttr(selparentshapes, ud=True)
     if copyUV and cmds.nodeType(
             seltargetshapes) == 'mesh' and cmds.nodeType(
                 selparentshapes) == 'mesh':
         print "Copy UV from" + selparentshapes + " to " + seltargetshapes
         cmds.transferAttributes(selparentshapes,
                                 seltargetshapes,
                                 transferUVs=1,
                                 transferColors=0,
                                 searchMethod=3,
                                 sampleSpace=5,
                                 flipUVs=0,
                                 transferPositions=0,
                                 transferNormals=0,
                                 colorBorders=0)
     if userattr:
         for attr in userattr:
             nodetype = cmds.nodeType(selparentshapes)
             checkrendershape = cmds.getAttr(selparentshapes +
                                             '.intermediateObject')
             if checkrendershape != 1 or nodetype != 'mesh':
                 key = attr
                 value = cmds.getAttr("%s.%s" % (selparentshapes, key))
                 data = cmds.getAttr("%s.%s" % (selparentshapes, key),
                                     typ=True)
                 listattrvalue[key] = value
                 listdatatype[key] = data
     checkrendershape = cmds.getAttr(seltargetshapes +
                                     '.intermediateObject')
     if checkrendershape != 1:
         for key in listattrvalue:
             if not cmds.attributeQuery(key, node=seltargetshapes, ex=True):
                 if listdatatype[key] == 'string':
                     cmds.addAttr(seltargetshapes,
                                  longName=key,
                                  dataType=listdatatype[key])
                     cmds.setAttr("%s.%s" % (seltargetshapes, key),
                                  listattrvalue[key],
                                  type=listdatatype[key])
                 else:
                     cmds.addAttr(seltargetshapes, longName=key)
                     cmds.setAttr("%s.%s" % (seltargetshapes, key),
                                  listattrvalue[key])
             else:
                 cmds.warning('Attribute ' + key + ' already on ' +
                              seltargetshapes)
                 if cmds.getAttr("%s.%s" % (seltargetshapes, key), se=True):
                     if listdatatype[key] == 'string':
                         cmds.setAttr("%s.%s" % (seltargetshapes, key),
                                      listattrvalue[key],
                                      type=listdatatype[key])
                     else:
                         cmds.setAttr("%s.%s" % (seltargetshapes, key),
                                      listattrvalue[key])
Esempio n. 17
0
 def transfer_uv(self, parent=None, target=None):
     '''
     transfer UV from parent to target
     '''
     if cmds.nodeType(parent) == cmds.nodeType(target) == 'mesh':
         cmds.transferAttributes(parent, target,
                                 transferUVs=1, transferColors=0, searchMethod=3,
                                 sampleSpace=5, flipUVs=0, transferPositions=0,
                                 transferNormals=0, colorBorders=0)
Esempio n. 18
0
def UVsTransfert(*args):

    sourceObject = str(
        cmds.textField('sourceObject_textField', q=True, text=True))

    targetObjects = cmds.ls(sl=True, l=True)

    if len(sourceObject) == 0:
        cmds.warning('Nothing is defined as a source.')

    elif len(targetObjects) == 0:
        cmds.warning('Nothing is selected.')

    elif sourceObject in targetObjects:

        cmds.warning('The source object cant be in the target objects list.')

    else:

        if len(
                cmds.listRelatives(targetObjects,
                                   path=True,
                                   fullPath=True,
                                   type='mesh')) == 0:
            cmds.warning('Select only Polygonal objects as target.')

        else:

            transfertMode = int()
            UVsets = int()

            if cmds.radioCollection('transfertMode_radioCollection',
                                    q=True,
                                    sl=True) == 'componentMode_radioButton':
                transfertMode = 4
            else:
                transfertMode = 5

            if cmds.radioCollection('transfertUV_radioCollection',
                                    q=True,
                                    sl=True) == 'currentUVset_radioButton':
                UVsets = 1
            else:
                UVsets = 2

            for t in targetObjects:

                cmds.transferAttributes(sourceObject,
                                        t,
                                        transferUVs=UVsets,
                                        sampleSpace=transfertMode,
                                        searchMethod=3)
                cmds.delete(t, ch=True)

            print('UVs transfered on ' + str(len(targetObjects)) +
                  ' object(s) succesfully.')
Esempio n. 19
0
 def TransferUV(self):
     dobj = cmds.ls(sl=1)
     if cmds.polyEvaluate(dobj[0], v=1) != cmds.polyEvaluate(dobj[1], v=1):
         dupobj = cmds.duplicate(dobj[1], rr=1)
         cmds.transferAttributes(dobj[0], dupobj, pos=0, nml=0, uvs=2, col=2, spa=0, sus="map1", tus="map1", sm=3, fuv=0, clb=1)
         cmds.delete(dupobj, ch=1)
         cmds.polyTransfer(dobj[1], uv=1, ao=dupobj[0])
         cmds.delete(dupobj)
     else:
         cmds.polyTransfer(dobj[1], uv=1, ao=dobj[0])
def J_CFXWorkFlow_autoMatchAbc(_sampleSpace=4, separateMesh=False):
    selectAbcFile = cmds.fileDialog2(fileMode=1, caption="Import clothInfo")[0]
    if not selectAbcFile.endswith('.abc'):
        print(selectAbcFile)
        print 'abc error'
        return
    destinationMeshs = J_getAllMeshUnderSelections(cmds.ls(sl=True)[0])
    if len(destinationMeshs) < 1:
        print 'select some mesh'
        return
    prFxName = os.path.basename(selectAbcFile).replace('.abc', '')
    abcNode = ''
    suffix = 0
    trNodeName = prFxName + '_abcCache' + '_' + str(suffix)
    while cmds.objExists(trNodeName):
        suffix += 1
        trNodeName = prFxName + '_abcCache' + '_' + str(suffix)

    groupNode = cmds.createNode('transform', name=trNodeName)
    cmds.setAttr((groupNode + '.visibility'), 0)
    if selectAbcFile is not None:
        abcNode = mel.eval('AbcImport -mode import -reparent ' + groupNode +
                           ' \"' + selectAbcFile + '\";')
        startTime = int(cmds.getAttr(abcNode + '.startFrame'))
        cmds.currentTime(startTime)
    allAbcMeshs = cmds.listConnections(abcNode, type='mesh')
    allAbcAnimationMesh = []
    cmds.currentTime(int(cmds.getAttr(abcNode + '.startFrame')))
    for meshItem in allAbcMeshs:
        if cmds.polyEvaluate(meshItem, shell=True) > 1 and separateMesh:
            separateMeshs = cmds.polySeparate(meshItem)

            for separateMeshItem in separateMeshs:
                if cmds.objectType(separateMeshItem, isType='polySeparate'):
                    continue
                allAbcAnimationMesh.append(separateMeshItem)
        else:
            allAbcAnimationMesh.append(meshItem)

    for meshItem in allAbcAnimationMesh:
        for destinationMeshItem in destinationMeshs:
            if J_compareMesh(meshItem, destinationMeshItem, 5):
                if _sampleSpace < 5:
                    cmds.transferAttributes(meshItem,
                                            destinationMeshItem,
                                            transferPositions=1,
                                            transferNormals=0,
                                            transferUVs=0,
                                            transferColors=0,
                                            sampleSpace=_sampleSpace,
                                            sourceUvSpace="map1",
                                            targetUvSpace="map1",
                                            searchMethod=3,
                                            flipUVs=0,
                                            colorBorders=1)
Esempio n. 21
0
def transfertUvsInTopologySpace(targets, source):
	"""
	This definition transferts UVs from source to targets object in topology space.

	:param targets: Sources objects. ( List )
	:param source: Target object. ( String )
	"""

	for target in targets:
		cmds.transferAttributes(source, target, transferUVs=2, sampleSpace=5)
		cmds.delete(source, ch=True)
Esempio n. 22
0
def transfertVerticesPositionsInUvsSpace(targets, source):
	"""
	This definition transferts vertices positions from source to targets object in UVs space.

	:param targets: Sources objects. ( List )
	:param source: Target object. ( String )
	"""

	for target in targets:
		cmds.transferAttributes(source, target, transferPositions=1, sampleSpace=3)
		cmds.delete(source, ch=True)
Esempio n. 23
0
def transferUVs(space, *args):
    if space == 2:
        value = 4
    elif space == 1:
        value = 0
    # space: 0=world, 1=model, 3=UV, 4=component
    # uvset: 0=No uvSet, 1=Single uvSet, 2=all uvSet
    sel = cmds.ls(sl=True)
    source = sel[0]
    target = sel[1:]
    for s in target:
        cmds.transferAttributes(source, s, transferUVs=1, sampleSpace=value)
Esempio n. 24
0
def transfertVerticesPositionsInWorldSpace(targets, source, searchMethod=0):
	"""
	This definition transferts vertices positions from source to targets object in world space.

	:param targets: Sources objects. ( List )
	:param source: Target object. ( String )
	:param searchMethod: Current search method. ( Integer )
	"""

	for target in targets:
		cmds.transferAttributes(source, target, transferPositions=1, sampleSpace=0, searchMethod=3)
		cmds.delete(source, ch=True)
def J_CFXWorkFlow_nClothIn():
    clothInfoFile = cmds.fileDialog2(fileMode=1, caption="Import clothInfo")[0]
    abcFile=clothInfoFile.replace('.Jcc','.abc')
    prFxName=os.path.basename(clothInfoFile).replace('.Jcc','')
    print prFxName
    runScript='file -import -type "mayaAscii" -gr -gn '+prFxName+"_cloth"+'  -ignoreVersion -ra true  -rpr \"'+prFxName+'\" -options "v=0;" \"'+clothInfoFile.replace('.Jcc','_Geo.ma\"')
    abcNode=''
    #导入abc
    fileId=open(clothInfoFile,'r')
    clothInfo=json.load(fileId)
    fileId.close()
    if cmds.objExists(prFxName+'_J_clothCache'):
        cmds.delete(prFxName+'_J_clothCache')
    if cmds.objExists(prFxName+'_cloth'):
        cmds.delete(prFxName+'_cloth')
    groupNode=cmds.createNode('transform',name=(prFxName+'_J_clothCache'))
    cmds.setAttr(groupNode+'.visibility',False)
    if  abcFile  is not None:
        abcNode=mel.eval('AbcImport -mode import -reparent '+groupNode+' \"'+abcFile +'\";')
    allAbcMeshs=cmds.listConnections(abcNode,type='mesh')
    cmds.select(allAbcMeshs)
    #检查是否有没找到mesh的缓存
    cacheHasNotFoundTarget=[]

    for mesh in allAbcMeshs:
        state=True
        for item in clothInfo[prFxName]['geoInfo']:
            if cmds.objExists(item['abcGeo']):
                print '-------'
                print mesh
                print '+++++'
                print item['abcGeo']
                if mesh==item['dupGeo']:
                    state=False
                    cmds.transferAttributes(mesh,item['abcGeo'],transferPositions=1,transferNormals=0 
                    ,transferUVs=0 ,transferColors=0 ,sampleSpace=4 ,sourceUvSpace="map1" ,targetUvSpace="map1"
                    ,searchMethod=3,flipUVs=0,colorBorders=1 )
        if state:
            cacheHasNotFoundTarget.append(mesh)
    if len(cacheHasNotFoundTarget)>0:
        #从ma导入模型
        try:
            mel.eval(runScript)
        except:
            cmds.confirmDialog(title=u'错误',message=u'可能未加载指定渲染器,加载后重试',button='哦')
        allClothMesh=cmds.listRelatives(prFxName+'_cloth',children=True,fullPath=True)
        for mesh in allAbcMeshs:
            for clothMesh in allClothMesh:
                if clothMesh.split(prFxName)[-1].find(mesh.split(':')[-1].split('|')[-1])>-1:
                    cmds.transferAttributes(mesh,clothMesh,transferPositions=1,transferNormals=0 
                    ,transferUVs=0 ,transferColors=0 ,sampleSpace=4 ,sourceUvSpace="map1" ,targetUvSpace="map1"
                    ,searchMethod=3,flipUVs=0,colorBorders=1 )
Esempio n. 26
0
def transfertUvsInTopologySpace(targets, source):
    """
	Transferts UVs from source to targets object in topology space.

	:param targets: Sources objects.
	:type targets: list
	:param source: Target object.
	:type source: str
	"""

    for target in targets:
        cmds.transferAttributes(source, target, transferUVs=2, sampleSpace=5)
        cmds.delete(source, ch=True)
Esempio n. 27
0
    def on_btn_replace_clicked(self, clicked=None):
        if clicked == None:
            return

        polyGeometry = mc.ls(type="mesh")
        if not polyGeometry:
            print "# Error # No polyGon geometrys...",
            return
        polyGeometry = mc.listRelatives(polyGeometry, p=True)
        polyGeometry = dict.fromkeys(polyGeometry).keys()

        selectIndexes = self.listView.selectedIndexes()
        if not selectIndexes:
            print "# Error # - You must select a model file...",
            return
        index = selectIndexes[0].row()
        modelPath = self.asset_data[index]

        if not uiTool.warning(message="Model's UV will be replaced, and it can not to undo !!!\nContinue ? ?"):
            return

        # - refrence
        f = mc.file(modelPath, r=True, namespace="UV")

        self.progressBar.setMaximum(len(polyGeometry))
        for i, geo in enumerate(polyGeometry):
            self.progressBar.setValue(i)
            self.btn_replace.setText("%d%%" % mathTool.setRange(0, len(polyGeometry), 0, 100, i))

            realName = re.search("\w+$", geo).group()
            UVgeo = "UV:%s" % realName
            if not mc.objExists(UVgeo):
                print "# Warning # There are no model in new file for %s..." % geo
                continue
            # -
            mc.transferAttributes(
                UVgeo, geo, pos=0, nml=0, uvs=2, col=0, spa=5, sus="map1", tus="map1", sm=0, fuv=0, clb=1
            )
            # -
            print "# Result # Copyed UV %s -> %s" % (UVgeo, geo)

            # - delete history
            RemoveUVWasteNode.delUVTransferAttributesNode(geo)

        self.progressBar.setMaximum(1)
        self.progressBar.setValue(0)
        self.btn_replace.setText("Replace")
        # - remove refrence
        mc.file(f, rr=True)
Esempio n. 28
0
 def transfer_uv(self, parent=None, target=None):
     '''
     transfer UV from parent to target
     '''
     if cmds.nodeType(parent) == cmds.nodeType(target) == 'mesh':
         cmds.transferAttributes(parent,
                                 target,
                                 transferUVs=1,
                                 transferColors=0,
                                 searchMethod=3,
                                 sampleSpace=5,
                                 flipUVs=0,
                                 transferPositions=0,
                                 transferNormals=0,
                                 colorBorders=0)
Esempio n. 29
0
    def paste_uv(self, mode="component"):
        if os.path.exists(self.saveFile):
            with open(self.saveFile, "r") as f:
                save_uv_data = json.load(f)
            self.copy_uvs = save_uv_data["copy_uv"]
        else:
            return
        sel = cmds.ls(sl=True, l=True)
        self.paste_uvs = cmds.polyListComponentConversion(sel, tuv=True)
        self.paste_uvs = cmds.filterExpand(self.paste_uvs, sm=35)
        cmds.select(self.paste_uvs, r=True)
        cmds.selectMode(o=True)
        target_obj = [obj.split(".")[0] for obj in cmds.ls(sl=True, l=True)]
        # print('get target :', target_obj)
        freeze_m.main(mesh=target_obj)
        if not self.paste_uvs:
            return
        paste_objects = list(set([uv.split(".")[0] for uv in self.paste_uvs]))
        # cmds.bakePartialHistory(paste_objects, pre=True)
        # print(paste_objects)
        paste_uvs_dict = {obj: [] for obj in paste_objects}
        # print(paste_uvs_dict)
        for uv in map(lambda uv: uv.split("."), self.paste_uvs):
            paste_uvs_dict[uv[0]] += [".".join(uv)]
        # print(paste_uvs_dict)
        for paste_uvs in paste_uvs_dict.values():
            # print(paste_uvs)
            cmds.select(cl=True)
            cmds.select(self.copy_uvs, r=True)
            cmds.select(paste_uvs, add=True)
            if mode == "component":
                sample_space = 4
            if mode == "world":
                sample_space = 0
            # print(mode)
            cmds.transferAttributes(
                flipUVs=0,
                transferPositions=0,
                transferUVs=2,
                searchMethod=3,
                transferNormals=0,
                transferColors=0,
                colorBorders=1,
                sampleSpace=sample_space,
            )

        freeze_m.main(mesh=target_obj)
        cmds.select(target_obj, r=True)
Esempio n. 30
0
def transfertVerticesPositionsInUvsSpace(targets, source):
    """
	Transferts vertices positions from source to targets object in UVs space.

	:param targets: Sources objects.
	:type targets: list
	:param source: Target object.
	:type source: str
	"""

    for target in targets:
        cmds.transferAttributes(source,
                                target,
                                transferPositions=1,
                                sampleSpace=3)
        cmds.delete(source, ch=True)
Esempio n. 31
0
def update_uv(*args):
    """Update Rig deformed geo's UV"""
    def get_meshes(node):
        return cmds.listRelatives(node, shapes=True, path=True, type="mesh")

    def get_target_mesh(meshes):
        """Locate original mesh shape to transfer UV to"""
        return next(m for m in meshes
                    if cmds.getAttr(m + ".intermediateObject")
                    and not cmds.referenceQuery(m, isNodeReferenced=True))

    selection = cmds.ls(sl=True)

    if len(selection) == 2:
        # Update UV from another model
        source, target = selection
        meshes = get_meshes(target)
        target = get_target_mesh(meshes)

    elif len(selection) == 1:
        # Update UV from referenced intermediate shape node
        transform = selection[0]
        meshes = get_meshes(transform)
        target = get_target_mesh(meshes)
        source = meshes[0]

        if target == source:
            raise Exception("Source and target is the same.")
    else:
        raise Exception("No object to update.")

    cmds.setAttr(target + ".intermediateObject", False)

    cmds.transferAttributes(source,
                            target,
                            transferPositions=0,
                            transferNormals=0,
                            transferUVs=2,
                            transferColors=0,
                            sampleSpace=1,
                            searchMethod=3,
                            flipUVs=0)

    cmds.delete(target, constructionHistory=True)

    cmds.setAttr(target + ".intermediateObject", True)
Esempio n. 32
0
def uvtransfer():
    # Store original selection
    selected = cmd.ls(sl=True)

    # Separate first selected element (source) from others (targets)
    targets = cmd.ls(sl=True)
    source = targets.pop(0)

    for object in targets:
        cmd.select([source, object])
        # sampleSpace = 4 (0 is world space, 1 is model space, 4 is component-based, 5 is topology-based)
        # transferUVs = 2 (all UV sets are transferred)
        # transferColors = 2 (all color sets are transferred)
        cmd.transferAttributes(sampleSpace=4, transferUVs=2, transferColors=2)

    # Restore original selection
    cmd.select(selected)
Esempio n. 33
0
def transfer_uvs(source_mesh, target_mesh):
    '''
    # tranfers the uvs
    # takes the source and a target
    '''
    try:
        cmds.transferAttributes(source_mesh,
                                target_mesh,
                                transferUVs=2,
                                transferColors=2,
                                searchMethod=3,
                                flipUVs=0,
                                transferNormals=0,
                                sampleSpace=1)

    except:
        cmds.confirmDialog(title='Error', message='WRONG OBJECT TYPE')
        return
Esempio n. 34
0
def transfertVerticesPositionsInWorldSpace(targets, source, searchMethod=0):
    """
	Transferts vertices positions from source to targets object in world space.

	:param targets: Sources objects.
	:type targets: list
	:param source: Target object.
	:type source: str
	:param searchMethod: Current search method.
	:type searchMethod: int
	"""

    for target in targets:
        cmds.transferAttributes(source,
                                target,
                                transferPositions=1,
                                sampleSpace=0,
                                searchMethod=3)
        cmds.delete(source, ch=True)
Esempio n. 35
0
def transfer_uvs(source_mesh, target_mesh):
    """
    # tranfers the uvs
    # takes the source and a target
    """
    try:
        cmds.transferAttributes(
            source_mesh,
            target_mesh,
            transferUVs=2,
            transferColors=2,
            searchMethod=3,
            flipUVs=0,
            transferNormals=0,
            sampleSpace=1,
        )

    except:
        cmds.confirmDialog(title="Error", message="WRONG OBJECT TYPE")
        return
Esempio n. 36
0
    def on_btn_replace_clicked(self, clicked=None):
        if clicked == None:return


        polyGeometry = mc.ls(type='mesh')
        if not polyGeometry:
            print '# Error # No polyGon geometrys...',
            return
        polyGeometry = (mc.listRelatives(polyGeometry, p=True))
        polyGeometry = dict.fromkeys(polyGeometry).keys()


        modelPath = str(self.let_filePath.text())


        #- refrence
        f = mc.file(modelPath, r=True, namespace='UV')

        self.progressBar.setMaximum(len(polyGeometry))
        for i, geo in enumerate(polyGeometry):
            self.progressBar.setValue(i)
            self.btn_replace.setText('%d%%'%mathTool.setRange(0, len(polyGeometry), 0, 100, i))

            realName = re.search('\w+$', geo).group()
            UVgeo    = 'UV:%s'%realName
            if not mc.objExists(UVgeo):
                print '# Warning # There are no model in new file for %s...'%geo
                continue
            #-
            mc.transferAttributes(UVgeo, geo, pos=0, nml=0, uvs=2, col=0, spa=5, sus="map1", tus="map1", sm=0, fuv=0, clb=1)
            #-
            print '# Result # Copyed UV %s -> %s'%(UVgeo, geo)

            #- delete history
            RemoveUVWasteNode.delUVTransferAttributesNode(geo)

        self.progressBar.setMaximum(1)
        self.progressBar.setValue(0)
        self.btn_replace.setText('Replace')
        #- remove refrence
        mc.file(f, rr=True)
Esempio n. 37
0
 def copy_user_attr(self, shapename=False, topology=False, uv=True, sets=True, history=True):
     match_list = self.find_match(shapename=shapename, topology=topology, uv=uv, sets=sets)
     if match_list:
         for parent in match_list:
             listattrvalue = {}
             listdatatype = {}
             userattr = cmds.listAttr(parent, ud=True)
             target = match_list[parent]
             if uv and cmds.nodeType(target) == 'mesh' and cmds.nodeType(parent) == 'mesh':
                 cmds.transferAttributes(parent, target,
                                         transferUVs=1, transferColors=0, searchMethod=3,
                                         sampleSpace=5, flipUVs=0, transferPositions=0,
                                         transferNormals=0, colorBorders=0)
             if history is True:
                 cmds.delete([parent, target], ch=True)
             if userattr:
                 for attr in userattr:
                     nodetype = cmds.nodeType(parent)
                     checkrendershape = cmds.getAttr(parent + '.intermediateObject')
                     if checkrendershape != 1 or nodetype != 'mesh':
                         value = cmds.getAttr("%s.%s" % (parent, attr))
                         data = cmds.getAttr("%s.%s" % (parent, attr), typ=True)
                         listattrvalue[attr] = value
                         listdatatype[attr] = data
             for attr in listattrvalue:
                 if not cmds.attributeQuery(attr, node=target, ex=True):
                     if listdatatype[attr] == 'string':
                         cmds.addAttr(target, longName=attr, dataType=listdatatype[attr])
                         cmds.setAttr("%s.%s" % (target, attr), listattrvalue[attr], type=listdatatype[attr])
                     else:
                         cmds.addAttr(target, longName=attr)
                         cmds.setAttr("%s.%s" % (target, attr), listattrvalue[attr])
                 else:
                     # cmds.warning('Attribute ' + attr + ' already on ' + seltargetshapes)
                     if cmds.getAttr("%s.%s" % (target, attr), se=True):
                         if listdatatype[attr] == 'string':
                             cmds.setAttr("%s.%s" % (target, attr), listattrvalue[attr], type=listdatatype[attr])
                         else:
                             cmds.setAttr("%s.%s" % (target, attr), listattrvalue[attr])
     else:
         cmds.warning("No matching objects found!")
Esempio n. 38
0
def transfertShape(*args):

    sel = cmds.ls(sl=True)

    if len(sel) == 2:
        sourceCurrentUV = cmds.polyUVSet(sel[0], cuv=True, q=True)
        targetCurrentUV = cmds.polyUVSet(sel[1], cuv=True, q=True)

        cmds.transferAttributes(sel[0],
                                sel[1],
                                pos=1,
                                spa=3,
                                sus=sourceCurrentUV[0],
                                tus=targetCurrentUV[0],
                                sm=3)

        if cmds.checkBox('deleteHistory_checkBox', value=True, q=True) == 1:
            cmds.delete(sel[1], ch=True)
        else:
            pass

    else:
        cmds.warning('Select only 2 objects')
def J_CFXWorkFlow_duplicateObj(inGeo):
    cmds.select(inGeo)
    cmds.duplicate(rr=True, smartTransform=True)
    uuid = cmds.ls(sl=True, uuid=True)
    fullNodePath = cmds.ls(uuid[0])
    newName = inGeo.split('|')[-1].replace(":", "_")
    fullNodePath[0] = cmds.rename(fullNodePath[0], newName)
    #将源模型点位置信息传给要导出的模型
    cmds.transferAttributes(inGeo,
                            fullNodePath[0],
                            transferPositions=1,
                            transferNormals=0,
                            transferUVs=0,
                            transferColors=0,
                            sampleSpace=4,
                            sourceUvSpace="map1",
                            targetUvSpace="map1",
                            searchMethod=3,
                            flipUVs=0,
                            colorBorders=1)

    if (cmds.listRelatives(fullNodePath[0], parent=True) == None):
        return fullNodePath[0]
    return cmds.parent(fullNodePath[0], world=True)[0]
Esempio n. 40
0
	def importForAsset2(self, asset, customNamespace = None ):
		"""import cache and assign to asset"""
		#reference render asset
		#connect cache to objects
		nodes = asset.shadingPath.reference( customNamespace )
		#filter meshes
		mshs = mn.ls( nodes, typ = 'mesh', ni = True, l = True )
		mshs.select()
		abcNode = self.imp( mode = 'import', connect = "/", createIfNotFound = True )
		#reconnect via polyTransfer so we can use the original uvs from shape
		attrs = abcNode.listAttr( c = True, m = True, ro = True, hd = True )
		for a in attrs:
			out = a.output
			if not out:
				continue
			for o in out:
				midMesh = mn.createNode( 'mesh' )
				o.disconnect()
				a >> midMesh.a.inMesh
				polyTrans = mc.transferAttributes( midMesh.name, o.node.name, transferPositions = 1, transferNormals = 1, transferUVs = 0, transferColors = 0, sampleSpace = 5, searchMethod = 3 )
				midMesh.a.intermediateObject.v = 1
				midMesh.parent.delete()
		nodes[0]()
		rf.reloadSelected()
Esempio n. 41
0
import maya.cmds as cmds
import pymel.core as pm

curSel = pm.ls(sl=1,fl=1)
getSd = curSel[0].MaterialInfo()
for sel in curSel[1:]:
	cmds.transferAttributes(curSel[0],sel,pos=0,nml=0,uvs=2,col=0,spa=5,sus='map1',tus='map1',sm=3,fuv=0,clb=1)
	cmds.sets(sel,e -forceElement af_checker_LambertSG;