Beispiel #1
0
 def __init__(self, title, max_value):
     super(MayaProgress, self).__init__()
     pmc.progressWindow(title=title,
                        progress=0,
                        min=0,
                        max=max_value,
                        status='',
                        isInterruptable=False)
Beispiel #2
0
 def wrapper(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except EdgeError:
         pass
     except:
         import traceback
         err = traceback.format_exc()
         msg = u"运行出错,请联系 timmyliang\n%s" % err
         QtWidgets.QMessageBox.warning(
             QtWidgets.QApplication.activeWindow(), u"警告", msg)
     finally:
         pm.progressWindow(ep=1)
Beispiel #3
0
    def onProgress(self, index, total, status):
        """
        Called after every step of the build.
        Override this in subclasses to monitor progress.

        Args:
            index: An int representing the index of the current action
            total: An int representing the total number of actions
            status (str): A status string representing the current step in progress
        """
        if self.showProgressUI:
            if index == 0:
                pm.progressWindow(t='Building Blueprint', min=0)
            pm.progressWindow(e=True, progress=index, max=total, status=status)
    def removeUnusedInfluence(self, skinClusterNode):
        allInfs = pm.skinCluster(skinClusterNode, q=True, inf=True)
        goodInfs = pm.skinCluster(skinClusterNode, q=True, wi=True)
        badInfs = list(set(allInfs).difference(set(goodInfs)))
        if len(badInfs):
            pm.progressWindow(title='',
                              progress=0,
                              status='Remove Unused Influence...',
                              isInterruptable=True,
                              maxValue=len(badInfs))
            nodeState = skinClusterNode.nodeState.get()
            lockState = skinClusterNode.nodeState.get(lock=True)

            skinClusterNode.nodeState.set(1)
            skinClusterNode.nodeState.set(lock=False)

            amount = 0
            for badInf in badInfs:
                if pm.progressWindow(query=True, isCancelled=True):
                    break
                skinClusterNode.removeInfluence(badInf)
                amount += 1
                pm.progressWindow(e=True, progress=amount)
            pm.progressWindow(endProgress=1)
            skinClusterNode.nodeState.set(nodeState)
            skinClusterNode.nodeState.set(lock=lockState)
Beispiel #5
0
def main():

    mesh_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh")
    if not mesh_list:
        return

    csv_path = r"C:\Users\timmyliang\Desktop\file_test\2020-12-1\head.csv"
    pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0)

    with open(csv_path, "r") as f:
        reader = csv.DictReader(f)
        data_list = {
            int(row[" IDX"]): (
                float(row[" COLOR.x"]),
                float(row[" COLOR.y"]),
                float(row[" COLOR.z"]),
                float(row[" COLOR.w"]),
            )
            for row in reader
        }

    mesh = mesh_list[0]
    mfn = mesh.__apimfn__()
    itr = OpenMaya.MItMeshFaceVertex(mesh.__apimobject__())

    face_list = OpenMaya.MIntArray()
    vertex_list = OpenMaya.MIntArray()
    colors = OpenMaya.MColorArray()

    index = -1
    total = len(mesh.vtxFace)
    pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0)
    while not itr.isDone():
        index += 1
        pm.progressWindow(e=1, progress=index / total * 100)
        vert_id = itr.vertId()
        face_id = itr.faceId()
        vertex_list.append(vert_id)
        face_list.append(face_id)

        color = data_list.get(vert_id)
        if not color:
            colors.append(OpenMaya.MColor(0, 0, 0))
            itr.next()
            continue
        r, g, b,a = color
        
        colors.append(OpenMaya.MColor(r, g, b))

        itr.next()

    mfn.setFaceVertexColors(colors, face_list, vertex_list)
    pm.progressWindow(ep=1)
def setupSkinLayers(mll=None, layers=[]):
    '''
    main skinning script to be called from build
    '''
    progressAmt = 0
    pm.progressWindow(title='Skin Layers Setup',
                      status='Initialize skinCluster...',
                      max=len(layers),
                      progress=progressAmt)
    
    if mll is None:
        mll = initBind()
    
    for layer, mask in layers:
        
        progressAmt += 1
        pm.progressWindow(e=True,
                          progress=progressAmt,
                          status='Setup layer "%s"...'%layer)
        
        try:
            func = globals()['layer_'+layer]
        except KeyError:
            print 'No function defined for layer ' + layer
        else:
            if mask:
                func(mll, mask)
            else:
                func(mll)
            
    pm.progressWindow(endProgress=True)
    pm.select(cl=True)
    
    return mll
def updateAOVStrAttr( *args ):
    strAttr = 'object_list'
    sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True)
    
    # filter AOV
    id_aov_sets = [ node for name, node in sceneAOVs if node.find('_id_') == 5 ]
    
    for aov in id_aov_sets:
        if( not( pm.PyNode(aov).hasAttr(strAttr) ) ):
            pm.addAttr( aov, longName=strAttr, dataType='string' )
        pm.PyNode(aov+'.'+strAttr).set('')
    
    
    listMesh = pm.ls(type='mesh')
    amount = 0.0
    maxValue = len(listMesh)
    pm.progressWindow( title='AOV Update Calculation', progress=amount, maxValue=maxValue , isInterruptable=True, status='calculating: 0%' )
    
    for mesh in listMesh:
        amount =  amount + 1
        pm.progressWindow( edit=True, progress=amount, status=('calculating: ' + str( 100 * amount/ maxValue) + '%') )
        if( mesh.hasAttr('mtoa_constant_Id') ):
            idName = mesh.mtoa_constant_Id.get()
            currAOVStrAttr = 'aiAOV_' + idName + '.' + strAttr
            pm.PyNode(currAOVStrAttr).set( pm.PyNode(currAOVStrAttr).get() + mesh + ';' )
    
    pm.progressWindow(endProgress=1)       
    return 1
Beispiel #8
0
def load_information(entry, loading_box):
    r = EntryReader(entry)
    _resources = []
    while True:
        ress = Resource()
        ress.offset = r.s32()
        _resources.append(ress)
        if _resources[0].offset == r.currentIndex:
            break

    for i in range(len(_resources)):
        pm.progressWindow(loading_box,
                          edit=True,
                          progress=20 + math.floor(
                              (80.0 / len(_resources)) * i))
        r.goto(_resources[i].offset)
        if i != len(_resources) - 1:
            while r.currentIndex < _resources[i + 1].offset - 1:
                _resources[i].op_code = r.u8()
                if _resources[i].op_code == 1:  # is Body
                    body = RessBody()
                    body.index = r.u8()
                    body.dataSize = r.u8()
                    body.realIndex = r.s16()
                    body.collisionBoxFlag = r.u8()
                    if body.collisionBoxFlag == 1:
                        r.skip(13)
                    _resources[i].bodies.append(body)
                else:  # is Anim
                    anim = RessAnim()
                    anim.index = r.u16()
                    anim.dataSize = r.u8()
                    anim.realIndex = r.u16()
                    r.skip(anim.dataSize - 3)
                    _resources[i].animations.append(anim)
                if i == len(_resources) - 1:
                    break
        else:
            _resources.pop(len(_resources) - 1)
    return _resources
Beispiel #9
0
def saveSkinWeightsToFile(filePath, *skins):
    """
    Save skin weights to a .weights file for one or more skin clusters.

    Args:
        filePath (str): A full path to the .weights file to write
        *skins (PyNode): One or more skin cluster nodes
    """
    pm.progressWindow(t='Saving Weights...', min=0, max=100, status=None)

    pm.progressWindow(e=True, progress=0)
    skinWeights = getSkinWeightsMap(*skins)

    pm.progressWindow(e=True, progress=80)
    skinWeightsStr = meta.encodeMetaData(skinWeights)

    pm.progressWindow(e=True, progress=90)
    with open(filePath, 'w') as fp:
        fp.write(skinWeightsStr)

    pm.progressWindow(endProgress=True)
    LOG.info(filePath)
Beispiel #10
0
    def onFinish(self):
        """
        Called when the build has completely finished.
        """
        if self.showProgressUI:
            pm.progressWindow(e=True, status=None)
            pm.progressWindow(endProgress=True)

        # clear selection
        pm.select(cl=True)

        # record time
        self.endTime = time.time()
        self.elapsedTime = self.endTime - self.startTime

        # log results
        finishMsg = self.getFinishBuildLogMessage()

        errorCount = len(self.errors)
        lvl = logging.WARNING if errorCount else logging.INFO
        self.log.log(lvl,
                     finishMsg,
                     extra=dict(
                         duration=self.elapsedTime,
                         scenePath=self.blueprintFile,
                     ))

        self.closeFileLogger()

        # show results with in view message
        inViewMsg = self.getFinishBuildInViewMessage()
        if errorCount:
            pm.inViewMessage(amg=inViewMsg,
                             pos='topCenter',
                             backColor=0xaa8336,
                             fade=True,
                             fadeStayTime=3000)
        else:
            pm.inViewMessage(amg=inViewMsg, pos='topCenter', fade=True)
Beispiel #11
0
 def import_command(*args):
     global lba_path
     global body_file
     if body_file is None:
         body_file = HQRReader(lba_path + "/BODY.HQR")
     settings.line_radius = line_radius_checkbox.getValue()
     settings.line_resolution = line_res_checkbox.getValue()
     settings.sphere_resolution = sphere_res_checkbox.getValue()
     loading_box = pm.progressWindow(title="LBA2 Model Generator",
                                     status="Starting...",
                                     isInterruptable=False,
                                     progress=0)
     import_model(scroll_list.getSelectIndexedItem()[0] - 1, settings,
                  loading_box)
     pm.deleteUI(window)
Beispiel #12
0
def convert_joint_to_cluster(targetGeo, skipList=[]):
    """
    Convert a skin cluster to a cluster based setup on a target geometery
    @param targetGeo: the geometery which has the skin cluster
    @param skipList: any joints which should not processed such as a base joint
    @return A dictonary of cluster with the name of the joints as keys

    """
    # Convert to PyNode
    targetGeo = pm.PyNode(targetGeo)
    skin = libUtilities.get_target_defomer(targetGeo, "skinCluster")

    # Create the dictionary
    clusterInfo = {}
    # Progress Info
    pm.progressWindow(title='Converting Skin To Cluster', progress=0, status='Progress: 0%')
    totalJnts = len(skin.getInfluence()) - len(skipList)
    currentJnt = 0.0

    # Go through Each Joint
    for jnt in sorted(skin.getInfluence()):
        if jnt.name() in skipList:
            continue
        # Get the vertex affected and the weight
        vertZip, weightList = skin.getPointsAffectedByInfluence(jnt)
        if not vertZip:
            raise Exception("Current Joint Has No Vertices:%s" % jnt)
        pm.select(vertZip)

        # Iterate through selection and decompress vertic group  into individual index
        vertices = libUtilities.indexize_vertice_group(pm.selected())
        # Select Vertices
        libUtilities.select_vertices(targetGeo, vertices)
        # Make a cluster
        cltr, cTransform = pm.cluster(rel=1)
        jntPos = pm.xform(jnt, q=1, ws=1, rp=1)
        pm.setAttr(cTransform.scalePivot, jntPos)
        pm.setAttr(cTransform.rotatePivot, jntPos)

        # Set the weight
        for index, weight in zip(vertices, weightList):
            cltr.weightList[0].weights[index].set(weight)

        # Add to dictionary
        clusterInfo[jnt.name()] = {"cluster": cltr, "clusterHandle": cTransform}

        # Update Progress
        currentJnt = currentJnt + 1.0
        currentProgress = (currentJnt / totalJnts) * 100
        pm.progressWindow(edit=True, progress=currentProgress, status=('Progress: ' + str(int(currentProgress)) + '%'))
        pm.refresh()
        pyLog.info("Converted: " + jnt.name())

    pm.progressWindow(endProgress=1)
    return clusterInfo
Beispiel #13
0
def load_lba2_folder(*args):
    global lba_path
    global palette
    global resources
    global import_menu

    def find(name, path):
        for root, dirs, files in os.walk(path):
            if name in files:
                return os.path.join(root, name)

    directory = pm.fileDialog2(caption="Select LBA2 Installation Folder",
                               fileMode=2,
                               okCaption="Select")
    if directory is None:
        return
    # Look for essential files before accepting:
    if find("BODY.HQR", directory[0]) is None:
        pm.informBox("Incorrect Folder", "File BODY.HQR not found.")
        return
    if find("RESS.HQR", directory[0]) is None:
        pm.informBox("Incorrect Folder", "File RESS.HQR not found.")
        return
    if find("ANIM.HQR", directory[0]) is None:
        pm.informBox("Incorrect Folder", "File ANIM.HQR not found.")
        return

    lba_path = directory[0]
    # Read RESS.HQR relevant entries
    loading_box = pm.progressWindow(title="LBA2 Model Generator",
                                    status="Opening Folder...",
                                    isInterruptable=False,
                                    progress=0)
    ress_file = HQRReader(lba_path + "/RESS.HQR")
    pm.progressWindow(loading_box,
                      edit=True,
                      status="Loading Palette...",
                      progress=10)
    palette = load_palette(ress_file[0])
    pm.progressWindow(loading_box,
                      edit=True,
                      status="Loading Resources...",
                      progress=20)
    resources = load_information(ress_file[44], loading_box)
    import_menu.setEnable(val=True)
    pm.progressWindow(loading_box, endProgress=1)
Beispiel #14
0
def DeleteNodes(ev=None):
    nodes = FindNodes()
    node = []
    for obj in nodes:
        if obj: node.append(obj)

    for ii in range(len(node)):
        pm.progressWindow(pr=0, min=0, max=100, t='Deleting ...')
        print 'Delete [%s]' % node[ii]
        pm.progressWindow(e=1, pr=(100.0 / len(node)) * ii)
        pm.delete(node[ii])
        PrintNodeLen()
    pm.progressWindow(endProgress=1)
    print 'Clean!'
Beispiel #15
0
def run(simLength, boids, params, vMax, boundry, obstacles, targets, nodes,
        flags):

    amount = 0
    pm.progressWindow(title='Boid Simulation',
                      progress=amount,
                      status='Running: 0%',
                      isInterruptable=True)
    #for i in range(1, simLength+1):
    while True:

        if pm.progressWindow(query=True, isCancelled=True):
            break

        if pm.progressWindow(query=True, progress=True) == simLength:
            break

        #pm.currentTime(i)
        amount += 1

        for b in boids:
            b.wrap(boundry)
            b.closestNeighbor(boids, params[0])
            b.closestObstacle(obstacles, params[1])
            b.closestTarget(targets, params[0])
            b.closestNode(nodes, params[0], params[2])
            flocking(b, flags, params)
            b.moveBoid(vMax)
            pm.select(b.transform_node[0])
            pm.move(b.x, b.y, b.z, worldSpace=True)
            pm.setKeyframe()
        pm.progressWindow(edit=True,
                          progress=amount,
                          status=('Sleeping: ' + ` amount ` + '%'))

    pm.progressWindow(endProgress=1)
Beispiel #16
0
    def export(self, button_value):
        """
        """
        ### get sequenceManager1
        sm = pymel.core.PyNode('sequenceManager1')

        ### get sequencer
        seq1 = sm.sequences.get()[0]
        # set path values
        current_workspace_path = pymel.core.workspace.path
        playblast_output_path = os.path.normpath(
            os.path.join(current_workspace_path, 'Outputs', 'All_Shots')
        )

        edl_path = os.path.normpath(
            os.path.join(
                playblast_output_path,
                '%s_%s.%s' % (seq1.get_sequence_name(), sm.get_version(), 'edl')
            )
        )

        # create shot playblast
        seq1.create_shot_playblasts(playblast_output_path)

        # convert to MXF
        if self.mxf_checkBox.value():
            shot_count = len(seq1.shots.get())
            step = int(100.0/shot_count)
            import time
            core.progressWindow(
                title='Converting To MXFs',
                progress=0,
                status='',
                isInterruptable=True
            )
            for i in seq1.metafuze():
                core.progressWindow(e=1, step=step)
            core.progressWindow(endProgress=1)

        if self.edl_checkBox.value():
            # create EDL file
            l = sm.to_edl()
            with open(edl_path, 'w') as f:
                f.write(l.to_string())
    def get_component_list(self):
        comp_list = []
        compDir = shifter.getComponentDirectories()
        trackLoadComponent = []
        for path, comps in compDir.items():
            pm.progressWindow(title='Loading Components',
                              progress=0,
                              max=len(comps))
            for comp_name in comps:
                pm.progressWindow(e=True,
                                  step=1,
                                  status='\nLoading: %s' % comp_name)
                if comp_name == "__init__.py":
                    continue
                elif comp_name in trackLoadComponent:
                    pm.displayWarning(
                        "Custom component name: %s, already in default "
                        "components. Names should be unique. This component is"
                        " not loaded" % comp_name)
                    continue
                else:
                    trackLoadComponent.append(comp_name)

                if not os.path.exists(
                        os.path.join(path, comp_name, "__init__.py")):
                    continue
                try:
                    module = shifter.importComponentGuide(comp_name)
                    if PY2:
                        reload(module)
                    else:
                        importlib.reload(module)
                    comp_list.append(module.TYPE)
                except Exception as e:
                    pm.displayWarning(
                        "{} can't be load. Error at import".format(comp_name))
                    pm.displayError(e)
                    pm.displayError(traceback.format_exc())

        pm.progressWindow(e=True, endProgress=True)
        return comp_list
Beispiel #18
0
    def export(self, button_value):
        """
        """
        ### get sequenceManager1
        sm = pymel.core.PyNode('sequenceManager1')

        ### get sequencer
        seq1 = sm.sequences.get()[0]
        # set path values
        current_workspace_path = pymel.core.workspace.path
        playblast_output_path = os.path.normpath(
            os.path.join(current_workspace_path, 'Outputs', 'All_Shots'))

        edl_path = os.path.normpath(
            os.path.join(
                playblast_output_path, '%s_%s_%s_%s.%s' %
                (seq1.get_sequence_name(), sm.get_task_name(),
                 sm.get_take_name(), sm.get_version(), 'edl')))

        # create shot playblast
        seq1.create_shot_playblasts(playblast_output_path)

        # convert to MXF
        if self.mxf_checkBox.value():
            shot_count = len(seq1.shots.get())
            step = int(100.0 / shot_count)
            import time
            core.progressWindow(title='Converting To MXFs',
                                progress=0,
                                status='',
                                isInterruptable=True)
            for i in seq1.metafuze():
                core.progressWindow(e=1, step=step)
            core.progressWindow(endProgress=1)

        if self.edl_checkBox.value():
            # create EDL file
            l = sm.to_edl()
            with open(edl_path, 'w') as f:
                f.write(l.to_string())
Beispiel #19
0
def setupPriCtlSecondPass(priCtlMappings):
    '''
    add binds to priCtl based on mappings generated from firstpass
    '''
    allPriCtls = []
    
    ### Start Progress
    progressAmt = 0
    pm.progressWindow(title='Build Control System',
                      status='Initialize controls...',
                      max=len(priCtlMappings.items()),
                      progress=progressAmt)
    ###
    
    for priCtlName, bndMappings in priCtlMappings.items():
        
        ### Progress
        progressAmt += 1
        pm.progressWindow(e=True,
                          progress=progressAmt,
                          status='Setup control "%s"...'%priCtlName)
        ###
        
        # change to bndName
        bndName = priCtlName.replace('_pri_ctrl', '_bnd')
        priCtlBnd = pm.PyNode(bndName)
        priCtl = addPrimaryCtlToBnd(priCtlBnd)
        for secBndName, weight in bndMappings.items():
            secBnd = pm.PyNode(secBndName)
            connectBndToPriCtl(secBnd, priCtl, False, dv=weight)
        allPriCtls.append(priCtl)
    
    ### End Progress
    pm.progressWindow(endProgress=True)
    ###
        
    allPriCtlHms = [ctl.getParent(-1) for ctl in allPriCtls]
    pm.group(allPriCtlHms, n='CT_face_primary_ctls_grp') 
    return allPriCtls    
Beispiel #20
0
def positionLinkForSelected():
    sel = pm.selected()
    if not sel:
        sel = links.getAllLinkedNodes()
        # TODO: sort by parenting hierarchy
    else:
        oldLen = len(sel)
        # filter for only linked nodes
        sel = [s for s in sel if links.isLinked(s)]
        if oldLen > 0 and len(sel) == 0:
            # something was selected, but no linked nodes
            LOG.warning("No linked nodes were selected")

    showProgress = (len(sel) > 20)
    if showProgress:
        pm.progressWindow(t='Positioning Links', min=0, max=len(sel))
    for node in sel:
        links.applyLinkPosition(node)
        if showProgress:
            pm.progressWindow(e=True, step=1)
    if showProgress:
        pm.progressWindow(endProgress=True)
Beispiel #21
0
def progressLoading(ev=None):
    crvs = pm.ls(sl=1)
    geom = pm.checkBoxGrp('geomCb', q=1, v1=1)
    size = pm.floatFieldGrp('sizeIntFd', q=1, v1=1)
    norDir = [
        pm.checkBoxGrp('norDirCbGrp', q=1, v1=1),
        pm.checkBoxGrp('norDirCbGrp', q=1, v2=1),
        pm.checkBoxGrp('norDirCbGrp', q=1, v3=1)
    ]
    nm = pm.textField('NmTxtFid', q=1, tx=1)

    pm.progressWindow(pr=0, min=0, max=100)
    geols = []
    for i, crv in enumerate(crvs):
        pm.progressWindow(e=1, pr=(100.0 / len(crvs)) * i, st=crv.name())
        geo = CurveLoft(crv, geom, size, norDir, nm)
        if geom == 1:
            geo.rename('%s%s_geo' % (nm, (i + 1)))
        elif geom == 0:
            geo.rename('%s%s_sfc' % (nm, (i + 1)))
        geols.append(geo)
    if len(geols) >= 2: pm.group(geols)
    pm.progressWindow(endProgress=1)
def constructVertexTree(loops):
    '''
    Organize verts into a tree
    This helps us to automatically weights joints later
    
    TODO: write a mesh.VertexTree class to make this more object-like
    also, should this inherit from the Tree class?
    
    Select vertex loop round the eyelid
    number of "loops" - based on user input from UI
    '''
    # organise vertices in loops expanding outwards from the selection
    selVerts = pm.ls(sl=True, fl=True)
    vertLoops = mesh.VertexLoops(selVerts, loops)
    
    root = data.Tree()
    
    # recursive function is kind of slow...
    # a progress window gives us something to look at while waiting...
    pm.progressWindow(title='Analyzing vertices', 
                      progress=0, 
                      max=len(vertLoops[0]))
    
    # find children for each vert in selection
    for eachVert in vertLoops[0]:
        vertTree = data.Tree()
        vertTree.data = eachVert
        findChildren(vertTree, vertLoops[1:])
        root.children.append(vertTree)
        # increment progress window
        pm.progressWindow(e=True, step=1, 
                          status='\nAnalysing %s' % eachVert)
    
    pm.progressWindow(e=True, endProgress=True)
    
    return root
Beispiel #23
0
 def finished():
     pmc.progressWindow(endProgress=True)
Beispiel #24
0
 def update(step, status):
     progress = pmc.progressWindow(query=True, progress=True)
     max_value = pmc.progressWindow(query=True, max=True)
     if progress >= max_value:
         pmc.progressWindow(edit=True, progress=0)
     pmc.progressWindow(edit=True, step=step, status=status)
Beispiel #25
0
    def exportGeometry(self, msh, shp):

        # api calls
        dag = shp.__apiobject__()
        mshfn = om.MFnMesh(dag)

        # export materials
        pm.progressWindow( edit=True, status='mesh %s/%s (%s): writing materials...'%(self._prg_count,self._prg_msh,msh) )

        sgs = []
        sgf = []

        def faces(x):
          f = []
          for fs in x:
            if fs.startswith('f'):
              fs = fs.split('[')[1].split(']')[0]
              if ':' in fs:
                a, b = fs.split(':')
                a, b = int(a), int(b)
                f.extend(range(a, b + 1))
              else:
                f.append(int(fs))
          return f

        _o = shp.instObjGroups[0].objectGroups.outputs(type='shadingEngine')
        if _o:
            # multi mat
            for _id in shp.instObjGroups[0].objectGroups.getArrayIndices():
                og = shp.instObjGroups[0].objectGroups[_id]
                f = faces( og.objectGrpCompList.get() )

                _sg = og.outputs()
                if _sg and f:
                    sgs.append(_sg[0])
                    sgf.append(f)

        else:
            # single mat
            _o = shp.instObjGroups[0].outputs(type='shadingEngine')
            sgs += _o

        doColors = shp.displayColors.get()


        sgi = []

        for sg in sgs:
            mat = sg.surfaceShader.inputs()[0]
            if str(mat) in self.materials:
                if doColors:
                    for m in self.db['materials']:
                        if m['name'] == str(mat):
                            m['vertexColors'] = True
                            break
            else:
                i = len(self.materials)
                self.materials.append(str(mat))

                m = {
                    'id' : i,
                    'name' : str(mat),

                    'DbgColor' : 0xFFFFFF,
                    'DbgIndex' : i,
                    'DbgName'  : str(mat),
                }

                self.db['materials'].append(m)


                _nt = pm.nodeType(mat)
                if _nt in ('lambert', 'phong', 'blinn', 'anisotropic'):
                    m['shading'] = 'Phong'
                    m['colorDiffuse'] = roundList( mat.color.get(), DECIMALS_COLOR )
                    _c = pm.dt.Vector(mat.ambientColor.get()) + mat.incandescence.get()
                    m['colorAmbient'] = roundList( _c, DECIMALS_COLOR )
                    #m['colorEmissive'] = mat.incandescence.get()
                    m['colorSpecular'] = [0,0,0]

                    self.setTextureInfo(i, 'mapDiffuse', mat.color )
                    self.setTextureInfo(i, 'mapLight', mat.ambientColor )
                    self.setTextureInfo(i, 'mapBump', mat.normalCamera )

                    _t = mat.transparency.get()
                    _t = 1 - (_t[0]+_t[1]+_t[2]) / 3
                    if _t < 1:
                        m['transparency'] = _t
                        m['transparent'] = True

                if _nt in ('phong', 'blinn', 'anisotropic'):
                    m['colorSpecular'] = roundList( mat.specularColor.get(), DECIMALS_COLOR )
                    m['specularCoef'] = 10
                    if _nt == 'blinn':
                        m['specularCoef'] = 4 / mat.eccentricity.get()
                    elif _nt == 'phong':
                        m['specularCoef'] = mat.cosinePower.get() * 2
                    if _nt == 'anisotropic':
                        m['specularCoef'] = 4 / mat.roughness.get()


                    self.setTextureInfo(i, 'mapSpecular', mat.specularColor )

                if _nt == 'surfaceShader':
                    m['shading'] = 'Basic'
                    m['colorDiffuse'] = roundList( mat.outColor.get(), DECIMALS_COLOR )


                if shp.doubleSided.get():
                    m['doubleSided'] = True
                elif shp.opposite.get():
                    m['flipSided'] = True

                if doColors:
                    m['vertexColors'] = True

            sgi.append( self.materials.index(str(mat)) )



        # export vertices
        _v = mshfn.numVertices()
        _voffset = self.db['metadata']['vertices']
        self.db['metadata']['vertices'] += _v
        self.vertices.append(_v)

        pm.progressWindow( edit=True, status='mesh %s/%s (%s): writing vertices...'%(self._prg_count,self._prg_msh,msh) )


        _pts = om.MPointArray()
        mshfn.getPoints(_pts, om.MSpace.kWorld)

        for i in xrange(_v):
            _p = [ _pts[i][0], _pts[i][1], _pts[i][2] ]
            self.db['vertices'] += roundList( _p, DECIMALS_VERTICES )


        # export faces
        _f = mshfn.numPolygons()
        self.db['metadata']['faces'] += _f
        self.faces.append(_f)

        pm.progressWindow( edit=True, status='mesh %s/%s (%s): writing faces...'%(self._prg_count,self._prg_msh,msh) )


        uvs = {}

        _noffset = len(self.db['normals'])/3
        _normals = om.MFloatVectorArray()
        mshfn.getNormals(_normals,om.MSpace.kWorld)
        for i in xrange(_normals.length()):
            _n = [ _normals[i][0], _normals[i][1], _normals[i][2] ]
            self.db['normals'] += roundList( _n, DECIMALS_NORMALS )
        _npf = om.MIntArray()
        _nid = om.MIntArray()
        mshfn.getNormalIds(_npf, _nid)

        _coffset = len(self.db['colors'])


        _vfoffset = 0

        it = om.MItMeshPolygon(dag)
        while not it.isDone():
            f = it.index()

            # vertices
            _vtx = om.MIntArray()
            it.getVertices( _vtx )
            vtx = [x+_voffset for x in _vtx]

            if len(vtx)>4:
                self.db['metadata']['faces'] -= 1
                self.faces[-1] -= 1
                it.next()
                _vfoffset += len(vtx)
                continue
            else:
                dbf = [0]
                dbf += vtx
                if len(vtx)==4:
                    dbf[0] += FACE_QUAD

            # material
            dbf[0] += FACE_MATERIAL

            if len(sgs)==1:
                dbf.append(sgi[0])
            else:
                for i,fset in enumerate(sgf):
                    if f in fset:
                        dbf.append(sgi[i])
                        break

            # uvs
            _u = om.MFloatArray()
            _v = om.MFloatArray()
            try:
                it.getUVs( _u, _v )
                dbf[0] += FACE_VERTEX_UV

                for v,uv in zip( vtx, zip(_u,_v) ):
                    uv = roundList(uv, DECIMALS_UVS)

                    if not uvs.get(v):
                        uvs[v] = []

                    exported = False
                    for _i,_uv in uvs[v]:
                        if _uv == uv:
                            dbf.append(_i)
                            exported = True
                            break

                    if not exported:
                        i = len(self.db['uvs'][0])/2
                        self.db['uvs'][0] += uv
                        uvs[v].append((i,uv))
                        dbf.append(i)
            except:
                pass
                #print '# warning: %s.f[%s] has no uv' % (shp, f)

            # normals
            dbf[0] += FACE_VERTEX_NORMAL

            for i in xrange( len(vtx) ):
                _n = _nid[i+_vfoffset]
                dbf.append(_n+_noffset)

            # colors
            if doColors:
                dbf[0] += FACE_VERTEX_COLOR

                for i in xrange( len(vtx) ):
                    if it.hasColor( i ):
                        color = om.MColor()
                        it.getColor( color, i )
                        c = (int(color[0]*255)<<16) + (int(color[1]*255)<<8) + int(color[2]*255)
                        self.db['colors'].append(c)
                        dbf.append(i+_vfoffset+_coffset)
                    else:
                        # white for colorless vertex
                        dbf.append(0)
                        _coffset -= 1


            _vfoffset += len(vtx)

            # add face
            self.db['faces'] += dbf
            it.next()


        self._prg_count += 1
        pm.progressWindow( edit=True, step=1 )
def doStopUpdateAOV(*args):
    if isProgress:
        pm.progressWindow(endProgress=1)
    return 1
def updateAOVStrAttr(*args):
    # custom Attr
    strAttr_obj_R = 'obj_R'
    strAttr_obj_G = 'obj_G'
    strAttr_obj_B = 'obj_B'
    strAttr_obj_W = 'obj_W'
    
    sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True)
    
    # filter AOV
    id_aov_sets = [ node for name, node in sceneAOVs if( name.find('id_') == 0 and node.hasAttr('isID') ) ]
    
    # loop each AOV to add custom Attr
    for aov in id_aov_sets:
        if( not( pm.PyNode(aov).hasAttr(strAttr_obj_R) ) ):
            pm.addAttr( aov, longName=strAttr_obj_R, niceName='R', dataType='string' )
            
        if( not( pm.PyNode(aov).hasAttr(strAttr_obj_G) ) ):
            pm.addAttr( aov, longName=strAttr_obj_G, niceName='G', dataType='string' )
            
        if( not( pm.PyNode(aov).hasAttr(strAttr_obj_B) ) ):
            pm.addAttr( aov, longName=strAttr_obj_B, niceName='B', dataType='string' )
            
        if( not( pm.PyNode(aov).hasAttr(strAttr_obj_W) ) ):
            pm.addAttr( aov, longName=strAttr_obj_W, niceName='W', dataType='string' )
                                                     
        # initialize                            
        pm.PyNode(aov+'.'+strAttr_obj_R).set('')
        pm.PyNode(aov+'.'+strAttr_obj_G).set('')
        pm.PyNode(aov+'.'+strAttr_obj_B).set('')
        pm.PyNode(aov+'.'+strAttr_obj_W).set('')
        
    # collect mesh in scene           
    listMesh = pm.ls(type='mesh')
    if( len(listMesh) == 0 ): return "no mesh in scene"
      
    maxValue = len(listMesh)
    global isProgress
    
    pm.progressWindow( title='AOV Update Calculation', progress=0, maxValue=maxValue , isInterruptable=True, status='calculating: 0%' )
    isProgress = True     
    for amount, mesh in enumerate(listMesh, 0):
        pm.progressWindow( edit=True, progress=amount, status=('calculating: ' + str( math.ceil(100 * amount/ maxValue) ) + '%') )
        if pm.progressWindow( query=True, isCancelled=True ) :
            break
        
        ## test if obj has both id and idcolor attrs ##
        if( mesh.hasAttr('mtoa_constant_Id') and mesh.hasAttr('mtoa_constant_idcolor') ):
            print mesh
            idName = mesh.mtoa_constant_Id.get()
            idColor = mesh.mtoa_constant_idcolor.get()
            
            if( idColor == (1.0, 0.0, 0.0) ):
                AOV_attr_obj = 'aiAOV_' + idName + '.' + strAttr_obj_R
                
            if( idColor == (0.0, 1.0, 0.0) ):
                AOV_attr_obj = 'aiAOV_' + idName + '.' + strAttr_obj_G
                
            if( idColor == (0.0, 0.0, 1.0) ):
                AOV_attr_obj = 'aiAOV_' + idName + '.' + strAttr_obj_B
                
            if( idColor == (1.0, 1.0, 1.0) ):
                AOV_attr_obj = 'aiAOV_' + idName + '.' + strAttr_obj_W
            
            # test if shape's aov is not existing in scene AOV
            if( len( pm.ls( 'aiAOV_' + idName ) ) == 0 ):
                continue
            
            # write to object_list Attr     
            pm.PyNode(AOV_attr_obj).set( pm.PyNode(AOV_attr_obj).get() + mesh.getParent() + ';' )

    
    pm.progressWindow( endProgress=1 )
    isProgress = False       
    return 1
Beispiel #28
0
    def __init__(self, *args):

        nodes = pm.ls(args, et='transform')
        if not nodes:
            nodes = pm.selected(et='transform')

        _sl = pm.selected()
        pm.select(nodes, hi=1)
        nodes = pm.selected()
        pm.select(_sl)

        geo = []
        for node in pm.ls(nodes, et='mesh'):
            msh = node.getParent()
            if not msh in geo:
                geo.append(msh)

        self.meshes = []
        self.shapes = []

        for node in geo:
            for shp in node.getShapes():
                if isinstance(shp, pm.nt.Mesh) and shp.io.get()==0 and shp.isVisible():
                    self.meshes.append(node)
                    self.shapes.append(shp)

        if not self.meshes:
            raise RuntimeError('no mesh provided')
        else:
            print '# Exporting MESHES: %s'%str(self.meshes)



        # db init
        self.db = {
            'metadata': {
                'formatVersion' : 3.1,
                'generatedBy'   : "yz Maya2012 Exporter"
                },
            'scale': 1,
        }


        self.materials = []
        self.textures = []
        self.db['materials'] = []

        self.vertices = []
        self.faces = []
        self.db['vertices'] = []
        self.db['faces'] = []
        self.db['uvs'] = [[]]
        self.db['normals'] = []
        self.db['colors'] = [16777215] #white for colorless

        self.db['metadata']['vertices'] = 0
        self.db['metadata']['faces'] = 0

        self._prg_msh = len(self.shapes)
        self._prg_count = 0
        pm.progressWindow( endProgress=True )
        pm.progressWindow( title="Exporting meshes", progress=0, status="", maxValue=self._prg_msh )

        try:
            for msh,shp in zip(self.meshes, self.shapes):
                self.exportGeometry(msh,shp)
        except:
            pm.progressWindow( endProgress=True )
            from traceback import print_tb
            print sys.exc_info()[0]
            print_tb(sys.exc_info()[2])
            return None

        pm.progressWindow( endProgress=True )


        self.db['metadata']['materials'] = len( self.db['materials'] )
        self.db['metadata']['uvs'] = len(self.db['uvs'][0])/2
        self.db['metadata']['normals'] = len(self.db['normals'])/3
Beispiel #29
0
def import_model(body_index, settings, loading_box):
    global body_file
    global palette
    global resources

    lba_model = read_lba2_model(body_file[body_index])
    materials = []
    if settings.use_palette:
        pm.progressWindow(loading_box,
                          edit=True,
                          status="Generating Palette...",
                          progress=5)
        # get list with all used palette values
        for i in range(len(lba_model.polygons)):
            materials.append(lba_model.polygons[i].colour)
        for i in range(len(lba_model.spheres)):
            materials.append(lba_model.spheres[i].colour)
        for i in range(len(lba_model.lines)):
            materials.append(lba_model.lines[i].colour)
        materials = list(dict.fromkeys(materials))
        create_materials(materials)

    bones = None
    if settings.use_rigging:
        pm.progressWindow(loading_box,
                          edit=True,
                          status="Generating Bones...",
                          progress=10)
        bones = bone_generator(lba_model.bones, lba_model.vertices)

    # generate the main mesh
    pm.progressWindow(loading_box,
                      edit=True,
                      status="Generating Mesh...",
                      progress=15)
    model = mesh_generator(lba_model.vertices, lba_model.polygons,
                           lba_model.normals, materials, lba_model.bones,
                           bones, settings)
    # generate the spheres
    pm.progressWindow(loading_box,
                      edit=True,
                      status="Generating Spheres...",
                      progress=20)
    spheres = sphere_generator(lba_model.spheres, lba_model.vertices, bones,
                               settings)
    # generate the lines
    pm.progressWindow(loading_box,
                      edit=True,
                      status="Generating Lines...",
                      progress=25)
    lines = line_generator(lba_model.lines, lba_model.vertices, bones,
                           settings)

    # unite all the rigged meshes
    pm.progressWindow(loading_box,
                      edit=True,
                      status="Unifying...",
                      progress=40)
    pm.select(clear=True)
    pm.select(model, add=True)
    pm.polyAutoProjection()
    pm.select(clear=True)
    pm.select(model, add=True)
    pm.select(spheres, add=True)
    pm.select(lines, add=True)
    unified_mesh = None
    if len(lba_model.spheres) > 0 or len(lba_model.lines) > 0:
        unified_mesh = pm.polyUniteSkinned(
        ) if settings.use_rigging else pm.polyUnite()
    if settings.use_rigging:
        if unified_mesh is None:
            pm.select(model, r=True)
        else:
            pm.select(unified_mesh, r=True)
        pm.select(bones[0], add=True)
        pm.group()
        # ## Load Animations ## #
        if settings.use_animation:
            pm.progressWindow(loading_box,
                              edit=True,
                              status="Loading Animations...",
                              progress=45)
            for resource in resources:
                for body in resource.bodies:
                    if body.realIndex == body_index:
                        if len(resource.animations) > 0:
                            pm.progressWindow(
                                loading_box,
                                edit=True,
                                status="Generating Animations...",
                                progress=50)
                            anim_importer(bones, resource.animations,
                                          loading_box)
                            pm.progressWindow(loading_box, endProgress=1)
                            return
        else:
            pm.progressWindow(loading_box, endProgress=1)
Beispiel #30
0
def SkinToClust ( joints=None, sourceGeometry=None, finalGeometry=None  ):

	#============================================================================
	# user inputs
	if sourceGeometry==None or finalGeometry==None or joints==None:
		geoAndJnts = pm.ls(sl=True)
		sourceGeometry = geoAndJnts[ len (geoAndJnts) -2 ]
		finalGeometry = geoAndJnts[ len (geoAndJnts) -1 ]
		joints = geoAndJnts[:len (geoAndJnts) -2 ]


	#============================================================================
	# find the skinCluster node on given objects

	skinClust =   pm.ls ( pm.listHistory (sourceGeometry ) ,  type = "skinCluster" )[0]



	if skinClust == []:
		pm.error( "Source Object is not skinned." )

	#============================================================================
	# create a list per selected influence containing
	# all the vertices and their weights

	# find shape of sourceShape
	sourceShape = sourceGeometry.getShape()

	# find shape of finalShape
	finalShape = finalGeometry.getShape()

	# find the number of vertices of sourceGeometry
	numOfVtxs = pm.polyEvaluate(finalGeometry) ["vertex"]

	jnt = joints[0]

	for jnt in joints:

		# start progress window
		amount = 0
		pm.progressWindow(    title= str(jnt),
											progress=0,
											status=("  find " + str(jnt) + " weights:"),
											isInterruptable=True )


		# create a dictionary containing all the values
		#==================
		tempDic = {}
		zeroVtxs = []

		# create counter for amount for status present
		if numOfVtxs != 0:
			counter = 100.0 / numOfVtxs

		vtx = 1
		for vtx in range(numOfVtxs):

			# get values from skinCluster
			tempVal = pm.skinPercent ( skinClust  , sourceShape.vtx[vtx] ,q =True , value=True , transform = jnt )

			# if the value is not 0 then add it to dictionary
			if not (  tempVal == 0 ):
				tempDic [vtx] = tempVal

			# else create a list containing 0 valued vertices
			else:
				zeroVtxs.append ( finalGeometry.vtx[vtx]  )

			# change progress window
			# pm.progressWindow ( edit=True, progress= int (amount), status=("  find " + str(jnt) + " weights:") )

			# change amount for status present
			amount += counter

		# end progress window
		pm.progressWindow(endProgress=1)


		# create a cluster in the position of the joint
		#==================
		currentClustAndHandle =  pm.cluster( finalShape , rel=True , n = (str(jnt)+"clust") )

		currentClust  = pm.ls( currentClustAndHandle[0] )[0]
		currentClustHandle = pm.ls( currentClustAndHandle[1] )[0]


		# change membership of cluster
		#==================

		# start progress window
		amount = 0
		pm.progressWindow(    title= str(jnt),
											progress=0,
											status=("  change " + str(jnt) + " membership:"),
											isInterruptable=True )


		# create counter for amount for status present
		if len(zeroVtxs) != 0:
			counter = 100.0 / len(zeroVtxs)

		pm.sets ( currentClust+"Set" , rm = zeroVtxs )

		# end progress window
		pm.progressWindow(endProgress=1)

		# positioning the clusters
		#==================

		# get position from current joint
		clustPos = pm.xform (jnt , q =True , ws=True , t=True )

		# set cluster origin values
		currentClustHandle.origin.set( clustPos )

		# center pivot of cluster
		pm.xform( currentClustHandle , centerPivots=True)



		# start progress window
		#====================

		# create a new progress window
		amount = 0
		pm.progressWindow(    title= str(jnt),
											progress=0,
											status=(" apply " + str(jnt) + " weights:") ,
											isInterruptable=True )

		# create counter for amount for status present
		if len(tempDic) != 0:
			counter = 100.0 / len(tempDic)

		# get the values from dictionary we've created and use them as cluster weights
		#==================
		for vtx in tempDic:

			# applying values
			pm.percent ( currentClust , finalShape.vtx[vtx] ,  v = tempDic [vtx] )

			# change progress window
			#pm.progressWindow ( edit=True, progress= int (amount), status=(" apply " + str(jnt) + " weights:") )

			# change amount for status present
			amount += counter

		# end progress window
		pm.progressWindow(endProgress=1)
    def _addControls(self, crv_ctl, option, sidecut):

        cvs = crv_ctl.getCVs(space="world")

        pm.progressWindow(title='controls', progress=0, max=len(cvs))

        v0 = transform.getTransformFromPos(cvs[0])
        v1 = transform.getTransformFromPos(cvs[-1])
        distSize = vector.getDistance(v0, v1) * 3

        npos = []
        ctls = []
        upvs = []
        params = ["tx", "ty", "tz", "rx", "ry", "rz"]
        joints = self.upJoints + self.lowJoints

        iterator = enumerate(cvs)
        if sidecut:
            iterator = enumerate(cvs[1:-1])

        for i, cv in iterator:

            pm.progressWindow(e=True,
                              step=1,
                              status='\nCreating control for%s' % cv)

            t = transform.getTransformFromPos(cv)

            # Get nearest joint for orientation of controls
            nearest_joint = None
            nearest_distance = None

            for joint in joints:
                distance = vector.getDistance(transform.getTranslation(joint),
                                              cv)
                if nearest_distance is None or distance < nearest_distance:
                    nearest_distance = distance
                    nearest_joint = joint

            if nearest_joint:

                t = transform.setMatrixPosition(
                    transform.getTransform(nearest_joint), cv)
                temp = addTransform(self.root, self.getName("temp"), t)
                # temp.rx.set(0)
                t = transform.getTransform(temp)
                pm.delete(temp)
                # print(i, nearest_joint, temp)

            oName = option[i][0]
            oSide = option[i][1]
            o_icon = option[i][2]
            color = option[i][3]
            wd = option[i][4]
            oPar = option[i][5]

            if oSide == "R":
                scl = [1, 1, -1]
            else:
                scl = [1, 1, 1]
            t = transform.setMatrixScale(t, scl)

            npo = addTransform(self.root, self.getName("%s_npo" % oName,
                                                       oSide), t)
            npos.append(npo)

            ctl = self.addCtl(
                npo,
                self.getName("{}_{}".format(oName, self.ctlName), oSide),
                t,
                color,
                o_icon,
                w=wd * distSize,
                d=wd * distSize,
                ro=datatypes.Vector(1.57079633, 0, 0),
                po=datatypes.Vector(0, 0, .07 * distSize),
            )

            ctls.append(ctl)

            ymt_util.setKeyableAttributesDontLockVisibility(ctl, params + oPar)

            upv = addTransform(ctl, self.getName("%s_upv" % oName, oSide), t)
            upv.attr("tz").set(self.FRONT_OFFSET)
            upvs.append(upv)
            self.addToSubGroup(ctl, self.primaryControllersGroupName)

        pm.progressWindow(e=True, endProgress=True)

        return npos, ctls, upvs
Beispiel #32
0
	def checkNodesMain(self , *args):
		amount = 0
		pm.progressWindow( t = '处理中...' , ii = True , progress = amount)
		while True:
			if pm.progressWindow(q = True , isCancelled = True):
				 break 
			
			if pm.progressWindow(q = True , progress = True) >= 100:
				 break 
			
			if pm.window( 'checkWin' , ex = True):
				pm.deleteUI('checkWin' , window = True)
			
			pm.window('checkWin' , t = '节点信息' , wh = [500 , 650])
			pm.columnLayout('QlookLayout' , adj = True)
			
			checkListNum = 16
			eachCheckListLength = 100/checkListNum
			
			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '重命名的节点:')
			
			if self.checkBox_1.isChecked():
				self.addFrm(self.checkOverNameAllObj , '1' , 'QlookLayout' , '重命名的节点:' )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '命名不正确的Shape:')
			
			if self.checkBox_2.isChecked():
				LayouName = self.addFrm(self.checkOverNameAllShape , '2' , 'QlookLayout' , '命名不正确的Shape:' )
				pm.button(p = LayouName , l = '修复Shape' ,c = functools.partial(self.renameWrongShape2 , LayouName) )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '绑定后不干净的shape:')
			
			if self.checkBox_3.isChecked():
				self.addFrm(self.checkRigShape , '3' , 'QlookLayout' , '绑定后不干净的shape:' )
				
			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '检查是否加smooth节点:')
			
			if self.checkBox_4.isChecked():
				LayouName = self.addFrm(self.checkObjectSmooth , '4' , 'QlookLayout' , 'smooth节点:' )
				pm.button(p = LayouName , l = '设置smooth节点' ,c = functools.partial(self.setObjectSmooth , LayouName) )
				
			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = 'geo组以外的模型是否不可渲染:')
			
			if self.checkBox_6.isChecked():
				LayouName = self.addFrm(self.checkObjectRender , '5' , 'QlookLayout' , '检查geo组以外的模型是否lambert材质不可渲染' )
				pm.button(p = LayouName , l = '设置geo组以外的模型为lambert材质不可渲染' ,c = functools.partial(self.setCheckObjectRender , LayouName) )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '设置geo组下模型可渲染')
			
			if self.checkBox_7.isChecked():
				self.addFrm(self.setGeoGroupRender , '6' , 'QlookLayout' , '设置geo组下模型可渲染:' , False , [0 , 0.5 , 0] )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '驱动,隐藏的物体是否锁定并设置成了不可K帧:')
			
			if self.checkBox_8.isChecked():
				LayouName = self.addFrm(self.checkObjectSetKey , '7' , 'QlookLayout' , '驱动,隐藏的物体是否锁定并设置成了不可K帧:' )
				pm.button(p = LayouName , l = '锁定不可K帧' ,c = functools.partial(self.setObjectSetKey , LayouName) )
				
			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '总控制器属性,颜色,关联显隐:')
			
			if self.checkBox_9.isChecked():
				LayouName = self.addFrm(self.checkMainCtrl , '8' , 'QlookLayout' , '总控制器属性,颜色,关联显隐:'  , False)
				if self.Box_9_v :
					pm.button(p = LayouName , l = '设置关联显隐' ,c = functools.partial(self.setCheckMainCtrl , LayouName) )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = 'RIG层级检查:')
			
			if self.checkBox_10.isChecked():
				self.addFrm(self.checkInterbedded , '9' , 'QlookLayout' , 'RIG层级检查:' , False )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '毛发检查:')
			
			if self.checkBox_11.isChecked():
				LayouName = self.addFrm(self.checkHair , '10' , 'QlookLayout' , '毛发检查:' )
				pm.button(p = LayouName , l = '设置毛发' ,c = functools.partial(self.setCheckHair , LayouName) )
				
			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '检查头和手臂的Global属性:')
			
			if self.checkBox_12.isChecked():
				LayouName = self.addFrm(self.checkGlobalAttr , '11' , 'QlookLayout' , '检查头和手臂的Global属性:' , False )
				pm.button(p = LayouName , l = '设置头和手臂的Global属性' ,c = functools.partial(self.setCheckGlobalAttr , LayouName) )
				
			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '清理多余的层:')
			
			if self.checkBox_13.isChecked():
				self.addFrm(self.cleanUp_SpilthLayer , '12' , 'QlookLayout' , '清理多余的层:' , False , [0 , 0.5 , 0] )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '清理未知节点:' )
			
			if self.checkBox_14.isChecked():
				self.addFrm(self.cleanUnknowNode , '13' , 'QlookLayout' , '清理未知节点:' , False , [0 , 0.5 , 0] )
				
			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '清理多余蒙皮节点:')
			
			if self.checkBox_15.isChecked():
				self.addFrm(self.cleanUnusedSkinNode , '14' , 'QlookLayout' , '清理多余蒙皮节点:' , False , [0 , 0.5 , 0] )

			amount += eachCheckListLength
			pm.progressWindow(e = True , progress = amount , status = '清理多余蒙皮影响:')
			
			if self.checkBox_16.isChecked():
				self.addFrm(self.cleanUnsedInfluence , '15' , 'QlookLayout' , '清理多余蒙皮影响:' , False , [0 , 0.5 , 0] )

			#amount += eachCheckListLength
			#pm.progressWindow(e = True , progress = amount , status = '手动清理暗面模型')
			"""
			if self.checkBox_17.isChecked():
				self.addFrm(self.cleanFaceFixedshader , '16' , 'QlookLayout' , '手动清理暗面模型' )
			"""
	

			pm.progressWindow(e = True , progress = amount , status = '完成:')
			
			break
							
		pm.showWindow('checkWin')
			
		pm.progressWindow(endProgress=1)
Beispiel #33
0
def expoert_mesh_data(path) :

    #------ blendshapeの変化量をJsonに書き出す! -------------
    """
    仕様 ※キーで入れてるので辞書の順番はこの通りではない、インデックスで呼ばないように
    {
        data          :
        {
            name_of_BS
        }
        base : 
        {
            vtx        : [頂点座標],
            connection : [接続頂点]
        }
        
        target : 
        [
            [頂点ごとのblendshapeベクトル]
        ]
    }
    注意
    ブレンドシェイプと同じ名前のオブジェクトを検索し、そこからblendshapeのベクトルを取得しています。
    ブレンドシェイプの元オブジェクトが消えていると書き出せない
    
    """
    #---------------------------------------------------

    # 名前のリスト:ブレンドシェイプの順番に注意

    ObjNameList  = [ "base" ]
    blender      = pm.PyNode('blendShape1')
    #BSlist       = cmds.listAttr(blender + '.w', m=True)
    numOfBS = 0
    for i in blender.w :    # なぜかlenが使えない場合がある.
        numOfBS += 1
        pm.setAttr(i, 0)    # ブレンドシェイプの初期化
    #numOfBS = len(blender.w)

    pm.progressWindow( isInterruptable = 1)

    dict         = {}
    dict["data"] = {}

    dict["data"]["name_of_BS"]  = numOfBS


    # ベースOBJの処理
    name = ObjNameList[0]
    dagPath = tools.getDagPath(name)


    #---- 頂点のイテレータをまわし、保存 -----
    mitMeshVertIns         = om2.MItMeshVertex(dagPath)    

    v_ls = [] 
    con_ls  = []                                    # .resetで現在のindexを初期化できます。
    mitMeshVertIns.reset()
    for n in range(mitMeshVertIns.count()):
        pos = mitMeshVertIns.position(space)     # <type 'OpenMaya.MPoint'>
        v_ls.append( [pos.x, pos.y, pos.z] )     
        # ----- ローカルの方がいい? -----
        
        #makeSphere(pos, 0.02)
        
        connectList = mitMeshVertIns.getConnectedVertices()
        con_ls.append( [i for i in connectList ])
        mitMeshVertIns.next()


    # 辞書に入れる
    base_dic = {}
    base_dic["vtx"] = v_ls
    base_dic["connection"] = con_ls

    dict[name] = base_dic
        

    # ブレンドシェイプのデータを格納
    # ウエイトを実際に変更し,ベースモデルから位置を取得.
    target = []
    for i in blender.w:
        
        for w in blender.w:
            if w == i :
                pm.setAttr(w,1.0)
            else :
                pm.setAttr(w,0.0)
            
        
            
        #dagPath   =  getDagPath(name)    
        #obj_dic   =  {}                 # 法線など別な情報を保存するときはこのオブジェクトごとの辞書に
        
        #---- 頂点のイテレータ -----
        mitMeshVertIns         = om2.MItMeshVertex(dagPath)    
                            
        # BSベクトルを取得
        v_ls = []
        mitMeshVertIns.reset()
        for n in range(mitMeshVertIns.count()):
            
            pos = mitMeshVertIns.position(space)     # <type 'OpenMaya.MPoint'>
            
            
            basePos = dict["base"]["vtx"][n]
            v_ls.append( [
                    pos.x - basePos[0],
                    pos.y - basePos[1],
                    pos.z - basePos[2]   ] )
            # ----- ローカルの方がいい? -----
            
            mitMeshVertIns.next()
            
            
            #if i.index() == 1 :
            #    makeVector(v_ls[n], basePos)
            
        
        for vi in v_ls :
            for p in vi :
                if -0.0001 < p < 0.0001 :
                    p = 0
        
        
        print "len(v_ls) : ", len(v_ls)    
        target.append( v_ls )
        
        
        
        if pm.progressWindow(q = 1, isCancelled=1) :
            break

    [pm.setAttr(w,0.0) for w in blender.w]
        
    dict["target"] = target    
    print dict

    print u"jsonファイル" + path + u"を開きます."
    json_file = open(path, 'w')

    json.dump(dict, json_file)

    json_file.close()

    pm.progressWindow( endProgress = 1)

    """
    json_file = open(path, 'r')
    print type(json.load(json_file)[0])
    json_file.close()
    """
    """
Beispiel #34
0
def eyeRig(eyeMesh,
           edgeLoop,
           blinkH,
           namePrefix,
           offset,
           rigidLoops,
           falloffLoops,
           headJnt,
           doSkin,
           parent=None,
           ctlName="ctl",
           sideRange=False,
           customCorner=False,
           intCorner=None,
           extCorner=None,
           ctlGrp=None,
           defGrp=None):

    """Create eyelid and eye rig

    Args:
        eyeMesh (TYPE): Description
        edgeLoop (TYPE): Description
        blinkH (TYPE): Description
        namePrefix (TYPE): Description
        offset (TYPE): Description
        rigidLoops (TYPE): Description
        falloffLoops (TYPE): Description
        headJnt (TYPE): Description
        doSkin (TYPE): Description
        parent (None, optional): Description
        ctlName (str, optional): Description
        sideRange (bool, optional): Description
        customCorner (bool, optional): Description
        intCorner (None, optional): Description
        extCorner (None, optional): Description
        ctlGrp (None, optional): Description
        defGrp (None, optional): Description

    Returns:
        TYPE: Description
    """
    # Checkers
    if edgeLoop:
        edgeLoopList = [pm.PyNode(e) for e in edgeLoop.split(",")]
    else:
        pm.displayWarning("Please set the edge loop first")
        return

    if eyeMesh:
        try:
            eyeMesh = pm.PyNode(eyeMesh)
        except pm.MayaNodeError:
            pm.displayWarning("The object %s can not be found in the "
                              "scene" % (eyeMesh))
            return
    else:
        pm.displayWarning("Please set the eye mesh first")

    if doSkin:
        if not headJnt:
            pm.displayWarning("Please set the Head Jnt or unCheck "
                              "Compute Topological Autoskin")
            return

    # Initial Data
    bboxCenter = meshNavigation.bboxCenter(eyeMesh)

    extr_v = meshNavigation.getExtremeVertexFromLoop(edgeLoopList, sideRange)
    upPos = extr_v[0]
    lowPos = extr_v[1]
    inPos = extr_v[2]
    outPos = extr_v[3]
    edgeList = extr_v[4]
    vertexList = extr_v[5]

    # Detect the side L or R from the x value
    if inPos.getPosition(space='world')[0] < 0.0:
        side = "R"
        inPos = extr_v[3]
        outPos = extr_v[2]
        normalPos = outPos
        npw = normalPos.getPosition(space='world')
        normalVec = npw - bboxCenter
    else:
        side = "L"
        normalPos = outPos
        npw = normalPos.getPosition(space='world')
        normalVec = bboxCenter - npw
    # Manual Vertex corners
    if customCorner:
        if intCorner:
            try:
                if side == "R":
                    inPos = pm.PyNode(extCorner)
                else:
                    inPos = pm.PyNode(intCorner)
            except pm.MayaNodeError:
                pm.displayWarning("%s can not be found" % intCorner)
                return
        else:
            pm.displayWarning("Please set the internal eyelid corner")
            return

        if extCorner:
            try:
                normalPos = pm.PyNode(extCorner)
                npw = normalPos.getPosition(space='world')
                if side == "R":
                    outPos = pm.PyNode(intCorner)
                    normalVec = npw - bboxCenter
                else:
                    outPos = pm.PyNode(extCorner)
                    normalVec = bboxCenter - npw
            except pm.MayaNodeError:
                pm.displayWarning("%s can not be found" % extCorner)
                return
        else:
            pm.displayWarning("Please set the external eyelid corner")
            return

    # Check if we have prefix:
    if namePrefix:
        namePrefix = string.removeInvalidCharacter(namePrefix)
    else:
        pm.displayWarning("Prefix is needed")
        return

    def setName(name, ind=None):
        namesList = [namePrefix, side, name]
        if ind is not None:
            namesList[1] = side + str(ind)
        name = "_".join(namesList)
        return name

    if pm.ls(setName("root")):
        pm.displayWarning("The object %s already exist in the scene. Please "
                          "choose another name prefix" % setName("root"))
        return

    # Eye root
    eye_root = primitive.addTransform(None, setName("root"))
    eyeCrv_root = primitive.addTransform(eye_root, setName("crvs"))

    # Eyelid Main crvs
    try:
        upEyelid = meshNavigation.edgeRangeInLoopFromMid(
            edgeList, upPos, inPos, outPos)
        upCrv = curve.createCurveFromOrderedEdges(
            upEyelid, inPos, setName("upperEyelid"), parent=eyeCrv_root)
        upCrv_ctl = curve.createCurveFromOrderedEdges(
            upEyelid, inPos, setName("upCrv_%s" % ctlName), parent=eyeCrv_root)
        pm.rebuildCurve(upCrv_ctl, s=2, rt=0, rpo=True, ch=False)

        lowEyelid = meshNavigation.edgeRangeInLoopFromMid(
            edgeList, lowPos, inPos, outPos)
        lowCrv = curve.createCurveFromOrderedEdges(
            lowEyelid, inPos, setName("lowerEyelid"), parent=eyeCrv_root)
        lowCrv_ctl = curve.createCurveFromOrderedEdges(
            lowEyelid,
            inPos,
            setName("lowCrv_%s" % ctlName),
            parent=eyeCrv_root)

        pm.rebuildCurve(lowCrv_ctl, s=2, rt=0, rpo=True, ch=False)

    except UnboundLocalError:
        if customCorner:
            pm.displayWarning("This error is maybe caused because the custom "
                              "Corner vertex is not part of the edge loop")
        pm.displayError(traceback.format_exc())
        return

    upBlink = curve.createCurveFromCurve(
        upCrv, setName("upblink_crv"), nbPoints=30, parent=eyeCrv_root)
    lowBlink = curve.createCurveFromCurve(
        lowCrv, setName("lowBlink_crv"), nbPoints=30, parent=eyeCrv_root)

    upTarget = curve.createCurveFromCurve(
        upCrv, setName("upblink_target"), nbPoints=30, parent=eyeCrv_root)
    lowTarget = curve.createCurveFromCurve(
        lowCrv, setName("lowBlink_target"), nbPoints=30, parent=eyeCrv_root)
    midTarget = curve.createCurveFromCurve(
        lowCrv, setName("midBlink_target"), nbPoints=30, parent=eyeCrv_root)

    rigCrvs = [upCrv,
               lowCrv,
               upCrv_ctl,
               lowCrv_ctl,
               upBlink,
               lowBlink,
               upTarget,
               lowTarget,
               midTarget]

    for crv in rigCrvs:
        crv.attr("visibility").set(False)

    # localBBOX
    localBBox = eyeMesh.getBoundingBox(invisible=True, space='world')
    wRadius = abs((localBBox[0][0] - localBBox[1][0]))
    dRadius = abs((localBBox[0][1] - localBBox[1][1]) / 1.7)

    # Groups
    if not ctlGrp:
        ctlGrp = "rig_controllers_grp"
    try:
        ctlSet = pm.PyNode(ctlGrp)
    except pm.MayaNodeError:
        pm.sets(n=ctlGrp, em=True)
        ctlSet = pm.PyNode(ctlGrp)
    if not defGrp:
        defGrp = "rig_deformers_grp"
    try:
        defset = pm.PyNode(defGrp)
    except pm.MayaNodeError:
        pm.sets(n=defGrp, em=True)
        defset = pm.PyNode(defGrp)

    # Calculate center looking at
    averagePosition = ((upPos.getPosition(space='world')
                        + lowPos.getPosition(space='world')
                        + inPos.getPosition(space='world')
                        + outPos.getPosition(space='world'))
                       / 4)
    if side == "R":
        negate = False
        offset = offset
        over_offset = dRadius
    else:
        negate = False
        over_offset = dRadius

    if side == "R" and sideRange or side == "R" and customCorner:
        axis = "z-x"
        # axis = "zx"
    else:
        axis = "z-x"

    t = transform.getTransformLookingAt(
        bboxCenter,
        averagePosition,
        normalVec,
        axis=axis,
        negate=negate)

    over_npo = primitive.addTransform(
        eye_root, setName("center_lookatRoot"), t)

    over_ctl = icon.create(over_npo,
                           setName("over_%s" % ctlName),
                           t,
                           icon="square",
                           w=wRadius,
                           d=dRadius,
                           ro=datatypes.Vector(1.57079633, 0, 0),
                           po=datatypes.Vector(0, 0, over_offset),
                           color=4)
    node.add_controller_tag(over_ctl)
    attribute.add_mirror_config_channels(over_ctl)
    attribute.setKeyableAttributes(
        over_ctl,
        params=["tx", "ty", "tz", "ro", "rx", "ry", "rz", "sx", "sy", "sz"])

    if side == "R":
        over_npo.attr("rx").set(over_npo.attr("rx").get() * -1)
        over_npo.attr("ry").set(over_npo.attr("ry").get() + 180)
        over_npo.attr("sz").set(-1)

    if len(ctlName.split("_")) == 2 and ctlName.split("_")[-1] == "ghost":
        pass
    else:
        pm.sets(ctlSet, add=over_ctl)

    center_lookat = primitive.addTransform(
        over_ctl, setName("center_lookat"), t)

    # Tracking
    # Eye aim control
    t_arrow = transform.getTransformLookingAt(bboxCenter,
                                              averagePosition,
                                              upPos.getPosition(space='world'),
                                              axis="zy", negate=False)

    radius = abs((localBBox[0][0] - localBBox[1][0]) / 1.7)
    arrow_npo = primitive.addTransform(eye_root, setName("aim_npo"), t_arrow)
    arrow_ctl = icon.create(arrow_npo,
                            setName("aim_%s" % ctlName),
                            t_arrow,
                            icon="arrow",
                            w=1,
                            po=datatypes.Vector(0, 0, radius),
                            color=4)
    if len(ctlName.split("_")) == 2 and ctlName.split("_")[-1] == "ghost":
        pass
    else:
        pm.sets(ctlSet, add=arrow_ctl)
    attribute.setKeyableAttributes(arrow_ctl, params=["rx", "ry", "rz"])

    # tracking custom trigger
    if side == "R":
        tt = t_arrow
    else:
        tt = t
    aimTrigger_root = primitive.addTransform(
        center_lookat, setName("aimTrigger_root"), tt)
    aimTrigger_lvl = primitive.addTransform(
        aimTrigger_root, setName("aimTrigger_lvl"), tt)
    aimTrigger_lvl.attr("tz").set(1.0)
    aimTrigger_ref = primitive.addTransform(
        aimTrigger_lvl, setName("aimTrigger_ref"), tt)
    aimTrigger_ref.attr("tz").set(0.0)
    # connect  trigger with arrow_ctl
    pm.parentConstraint(arrow_ctl, aimTrigger_ref, mo=True)

    # Controls lists
    upControls = []
    trackLvl = []

    # upper eyelid controls
    upperCtlNames = ["inCorner", "upInMid", "upMid", "upOutMid", "outCorner"]
    cvs = upCrv_ctl.getCVs(space="world")
    if side == "R" and not sideRange:
        # if side == "R":
        cvs = [cv for cv in reversed(cvs)]
    for i, cv in enumerate(cvs):
        if utils.is_odd(i):
            color = 14
            wd = .5
            icon_shape = "circle"
            params = ["tx", "ty", "tz"]
        else:
            color = 4
            wd = .7
            icon_shape = "square"
            params = ["tx",
                      "ty",
                      "tz",
                      "ro",
                      "rx",
                      "ry",
                      "rz",
                      "sx",
                      "sy",
                      "sz"]

        t = transform.setMatrixPosition(t, cvs[i])
        npo = primitive.addTransform(center_lookat,
                                     setName("%s_npo" % upperCtlNames[i]),
                                     t)
        npoBase = npo
        if i == 2:
            # we add an extra level to input the tracking ofset values
            npo = primitive.addTransform(npo,
                                         setName("%s_trk" % upperCtlNames[i]),
                                         t)
            trackLvl.append(npo)

        ctl = icon.create(npo,
                          setName("%s_%s" % (upperCtlNames[i], ctlName)),
                          t,
                          icon=icon_shape,
                          w=wd,
                          d=wd,
                          ro=datatypes.Vector(1.57079633, 0, 0),
                          po=datatypes.Vector(0, 0, offset),
                          color=color)
        attribute.add_mirror_config_channels(ctl)
        node.add_controller_tag(ctl, over_ctl)
        upControls.append(ctl)
        if len(ctlName.split("_")) == 2 and ctlName.split("_")[-1] == "ghost":
            pass
        else:
            pm.sets(ctlSet, add=ctl)
        attribute.setKeyableAttributes(ctl, params)
        if side == "R":
            npoBase.attr("ry").set(180)
            npoBase.attr("sz").set(-1)

    # adding parent average contrains to odd controls
    for i, ctl in enumerate(upControls):
        if utils.is_odd(i):
            pm.parentConstraint(upControls[i - 1],
                                upControls[i + 1],
                                ctl.getParent(),
                                mo=True)

    # lower eyelid controls
    lowControls = [upControls[0]]
    lowerCtlNames = ["inCorner",
                     "lowInMid",
                     "lowMid",
                     "lowOutMid",
                     "outCorner"]

    cvs = lowCrv_ctl.getCVs(space="world")
    if side == "R" and not sideRange:
        cvs = [cv for cv in reversed(cvs)]
    for i, cv in enumerate(cvs):
        # we skip the first and last point since is already in the uper eyelid
        if i in [0, 4]:
            continue
        if utils.is_odd(i):
            color = 14
            wd = .5
            icon_shape = "circle"
            params = ["tx", "ty", "tz"]
        else:
            color = 4
            wd = .7
            icon_shape = "square"
            params = ["tx",
                      "ty",
                      "tz",
                      "ro",
                      "rx",
                      "ry",
                      "rz",
                      "sx",
                      "sy",
                      "sz"]

        t = transform.setMatrixPosition(t, cvs[i])
        npo = primitive.addTransform(center_lookat,
                                     setName("%s_npo" % lowerCtlNames[i]),
                                     t)
        npoBase = npo
        if i == 2:
            # we add an extra level to input the tracking ofset values
            npo = primitive.addTransform(npo,
                                         setName("%s_trk" % lowerCtlNames[i]),
                                         t)
            trackLvl.append(npo)
        ctl = icon.create(npo,
                          setName("%s_%s" % (lowerCtlNames[i], ctlName)),
                          t,
                          icon=icon_shape,
                          w=wd,
                          d=wd,
                          ro=datatypes.Vector(1.57079633, 0, 0),
                          po=datatypes.Vector(0, 0, offset),
                          color=color)
        attribute.add_mirror_config_channels(ctl)

        lowControls.append(ctl)
        if len(ctlName.split("_")) == 2 and ctlName.split("_")[-1] == "ghost":
            pass
        else:
            pm.sets(ctlSet, add=ctl)
        attribute.setKeyableAttributes(ctl, params)
        # mirror behaviout on R side controls
        if side == "R":
            npoBase.attr("ry").set(180)
            npoBase.attr("sz").set(-1)
    for lctl in reversed(lowControls[1:]):
        node.add_controller_tag(lctl, over_ctl)
    lowControls.append(upControls[-1])

    # adding parent average contrains to odd controls
    for i, ctl in enumerate(lowControls):
        if utils.is_odd(i):
            pm.parentConstraint(lowControls[i - 1],
                                lowControls[i + 1],
                                ctl.getParent(),
                                mo=True)

    # Connecting control crvs with controls
    applyop.gear_curvecns_op(upCrv_ctl, upControls)
    applyop.gear_curvecns_op(lowCrv_ctl, lowControls)

    # adding wires
    w1 = pm.wire(upCrv, w=upBlink)[0]
    w2 = pm.wire(lowCrv, w=lowBlink)[0]

    w3 = pm.wire(upTarget, w=upCrv_ctl)[0]
    w4 = pm.wire(lowTarget, w=lowCrv_ctl)[0]

    # adding blendshapes
    bs_upBlink = pm.blendShape(upTarget,
                               midTarget,
                               upBlink,
                               n="blendShapeUpBlink")
    bs_lowBlink = pm.blendShape(lowTarget,
                                midTarget,
                                lowBlink,
                                n="blendShapeLowBlink")
    bs_mid = pm.blendShape(lowTarget,
                           upTarget,
                           midTarget,
                           n="blendShapeLowBlink")

    # setting blendshape reverse connections
    rev_node = pm.createNode("reverse")
    pm.connectAttr(bs_upBlink[0].attr(midTarget.name()), rev_node + ".inputX")
    pm.connectAttr(rev_node + ".outputX", bs_upBlink[0].attr(upTarget.name()))
    rev_node = pm.createNode("reverse")
    pm.connectAttr(bs_lowBlink[0].attr(midTarget.name()), rev_node + ".inputX")
    pm.connectAttr(rev_node + ".outputX",
                   bs_lowBlink[0].attr(lowTarget.name()))
    rev_node = pm.createNode("reverse")
    pm.connectAttr(bs_mid[0].attr(upTarget.name()), rev_node + ".inputX")
    pm.connectAttr(rev_node + ".outputX", bs_mid[0].attr(lowTarget.name()))

    # setting default values
    bs_mid[0].attr(upTarget.name()).set(blinkH)

    # joints root
    jnt_root = primitive.addTransformFromPos(
        eye_root, setName("joints"), pos=bboxCenter)

    # head joint
    if headJnt:
        try:
            headJnt = pm.PyNode(headJnt)
            jnt_base = headJnt
        except pm.MayaNodeError:
            pm.displayWarning(
                "Aborted can not find %s " % headJnt)
            return
    else:
        # Eye root
        jnt_base = jnt_root

    eyeTargets_root = primitive.addTransform(eye_root,
                                             setName("targets"))

    eyeCenter_jnt = rigbits.addJnt(arrow_ctl,
                                   jnt_base,
                                   grp=defset,
                                   jntName=setName("center_jnt"))

    # Upper Eyelid joints ##################################################

    cvs = upCrv.getCVs(space="world")
    upCrv_info = node.createCurveInfoNode(upCrv)

    # aim constrain targets and joints
    upperEyelid_aimTargets = []
    upperEyelid_jnt = []
    upperEyelid_jntRoot = []

    for i, cv in enumerate(cvs):

        # aim targets
        trn = primitive.addTransformFromPos(eyeTargets_root,
                                            setName("upEyelid_aimTarget", i),
                                            pos=cv)
        upperEyelid_aimTargets.append(trn)
        # connecting positions with crv
        pm.connectAttr(upCrv_info + ".controlPoints[%s]" % str(i),
                       trn.attr("translate"))

        # joints
        jntRoot = primitive.addJointFromPos(jnt_root,
                                            setName("upEyelid_jnt_base", i),
                                            pos=bboxCenter)
        jntRoot.attr("radius").set(.08)
        jntRoot.attr("visibility").set(False)
        upperEyelid_jntRoot.append(jntRoot)
        applyop.aimCns(jntRoot, trn, axis="zy", wupObject=jnt_root)

        jnt_ref = primitive.addJointFromPos(jntRoot,
                                            setName("upEyelid_jnt_ref", i),
                                            pos=cv)
        jnt_ref.attr("radius").set(.08)
        jnt_ref.attr("visibility").set(False)

        jnt = rigbits.addJnt(jnt_ref,
                             jnt_base,
                             grp=defset,
                             jntName=setName("upEyelid_jnt", i))
        upperEyelid_jnt.append(jnt)

    # Lower Eyelid joints ##################################################

    cvs = lowCrv.getCVs(space="world")
    lowCrv_info = node.createCurveInfoNode(lowCrv)

    # aim constrain targets and joints
    lowerEyelid_aimTargets = []
    lowerEyelid_jnt = []
    lowerEyelid_jntRoot = []

    for i, cv in enumerate(cvs):
        if i in [0, len(cvs) - 1]:
            continue

        # aim targets
        trn = primitive.addTransformFromPos(eyeTargets_root,
                                            setName("lowEyelid_aimTarget", i),
                                            pos=cv)
        lowerEyelid_aimTargets.append(trn)
        # connecting positions with crv
        pm.connectAttr(lowCrv_info + ".controlPoints[%s]" % str(i),
                       trn.attr("translate"))

        # joints
        jntRoot = primitive.addJointFromPos(jnt_root,
                                            setName("lowEyelid_base", i),
                                            pos=bboxCenter)
        jntRoot.attr("radius").set(.08)
        jntRoot.attr("visibility").set(False)
        lowerEyelid_jntRoot.append(jntRoot)
        applyop.aimCns(jntRoot, trn, axis="zy", wupObject=jnt_root)

        jnt_ref = primitive.addJointFromPos(jntRoot,
                                            setName("lowEyelid_jnt_ref", i),
                                            pos=cv)
        jnt_ref.attr("radius").set(.08)
        jnt_ref.attr("visibility").set(False)

        jnt = rigbits.addJnt(jnt_ref,
                             jnt_base,
                             grp=defset,
                             jntName=setName("lowEyelid_jnt", i))
        lowerEyelid_jnt.append(jnt)

    # Channels
    # Adding and connecting attributes for the blink
    up_ctl = upControls[2]
    blink_att = attribute.addAttribute(
        over_ctl, "blink", "float", 0, minValue=0, maxValue=1)
    blinkMult_att = attribute.addAttribute(
        over_ctl, "blinkMult", "float", 1, minValue=1, maxValue=2)
    midBlinkH_att = attribute.addAttribute(
        over_ctl, "blinkHeight", "float", blinkH, minValue=0, maxValue=1)
    mult_node = node.createMulNode(blink_att, blinkMult_att)
    pm.connectAttr(mult_node + ".outputX",
                   bs_upBlink[0].attr(midTarget.name()))
    pm.connectAttr(mult_node + ".outputX",
                   bs_lowBlink[0].attr(midTarget.name()))
    pm.connectAttr(midBlinkH_att, bs_mid[0].attr(upTarget.name()))

    low_ctl = lowControls[2]

    # Adding channels for eye tracking
    upVTracking_att = attribute.addAttribute(up_ctl,
                                             "vTracking",
                                             "float",
                                             .02,
                                             minValue=0,
                                             maxValue=1,
                                             keyable=False,
                                             channelBox=True)
    upHTracking_att = attribute.addAttribute(up_ctl,
                                             "hTracking",
                                             "float",
                                             .01,
                                             minValue=0,
                                             maxValue=1,
                                             keyable=False,
                                             channelBox=True)

    lowVTracking_att = attribute.addAttribute(low_ctl,
                                              "vTracking",
                                              "float",
                                              .01,
                                              minValue=0,
                                              maxValue=1,
                                              keyable=False,
                                              channelBox=True)
    lowHTracking_att = attribute.addAttribute(low_ctl,
                                              "hTracking",
                                              "float",
                                              .01,
                                              minValue=0,
                                              maxValue=1,
                                              keyable=False,
                                              channelBox=True)

    mult_node = node.createMulNode(upVTracking_att, aimTrigger_ref.attr("ty"))
    pm.connectAttr(mult_node + ".outputX", trackLvl[0].attr("ty"))
    mult_node = node.createMulNode(upHTracking_att, aimTrigger_ref.attr("tx"))
    pm.connectAttr(mult_node + ".outputX", trackLvl[0].attr("tx"))

    mult_node = node.createMulNode(lowVTracking_att, aimTrigger_ref.attr("ty"))
    pm.connectAttr(mult_node + ".outputX", trackLvl[1].attr("ty"))
    mult_node = node.createMulNode(lowHTracking_att, aimTrigger_ref.attr("tx"))
    pm.connectAttr(mult_node + ".outputX", trackLvl[1].attr("tx"))

    # Tension on blink
    node.createReverseNode(blink_att, w1.scale[0])
    node.createReverseNode(blink_att, w3.scale[0])
    node.createReverseNode(blink_att, w2.scale[0])
    node.createReverseNode(blink_att, w4.scale[0])

    ###########################################
    # Reparenting
    ###########################################
    if parent:
        try:
            if isinstance(parent, basestring):
                parent = pm.PyNode(parent)
            parent.addChild(eye_root)
        except pm.MayaNodeError:
            pm.displayWarning("The eye rig can not be parent to: %s. Maybe "
                              "this object doesn't exist." % parent)

    ###########################################
    # Auto Skinning
    ###########################################
    if doSkin:
        # eyelid vertex rows
        totalLoops = rigidLoops + falloffLoops
        vertexLoopList = meshNavigation.getConcentricVertexLoop(vertexList,
                                                                totalLoops)
        vertexRowList = meshNavigation.getVertexRowsFromLoops(vertexLoopList)

        # we set the first value 100% for the first initial loop
        skinPercList = [1.0]
        # we expect to have a regular grid topology
        for r in range(rigidLoops):
            for rr in range(2):
                skinPercList.append(1.0)
        increment = 1.0 / float(falloffLoops)
        # we invert to smooth out from 100 to 0
        inv = 1.0 - increment
        for r in range(falloffLoops):
            for rr in range(2):
                if inv < 0.0:
                    inv = 0.0
                skinPercList.append(inv)
            inv -= increment

        # this loop add an extra 0.0 indices to avoid errors
        for r in range(10):
            for rr in range(2):
                skinPercList.append(0.0)

        # base skin
        geo = pm.listRelatives(edgeLoopList[0], parent=True)[0]
        # Check if the object has a skinCluster
        objName = pm.listRelatives(geo, parent=True)[0]

        skinCluster = skin.getSkinCluster(objName)
        if not skinCluster:
            skinCluster = pm.skinCluster(headJnt,
                                         geo,
                                         tsb=True,
                                         nw=2,
                                         n='skinClsEyelid')

        eyelidJoints = upperEyelid_jnt + lowerEyelid_jnt
        pm.progressWindow(title='Auto skinning process',
                          progress=0,
                          max=len(eyelidJoints))
        firstBoundary = False
        for jnt in eyelidJoints:
            pm.progressWindow(e=True, step=1, status='\nSkinning %s' % jnt)
            skinCluster.addInfluence(jnt, weight=0)
            v = meshNavigation.getClosestVertexFromTransform(geo, jnt)

            for row in vertexRowList:

                if v in row:
                    it = 0  # iterator
                    inc = 1  # increment
                    for i, rv in enumerate(row):
                        try:
                            perc = skinPercList[it]
                            t_val = [(jnt, perc), (headJnt, 1.0 - perc)]
                            pm.skinPercent(skinCluster,
                                           rv,
                                           transformValue=t_val)
                            if rv.isOnBoundary():
                                # we need to compare with the first boundary
                                # to check if the row have inverted direction
                                # and offset the value
                                if not firstBoundary:
                                    firstBoundary = True
                                    firstBoundaryValue = it

                                else:
                                    if it < firstBoundaryValue:
                                        it -= 1
                                    elif it > firstBoundaryValue:
                                        it += 1
                                inc = 2
                        except IndexError:
                            continue

                        it = it + inc
        pm.progressWindow(e=True, endProgress=True)

        # Eye Mesh skinning
        skinCluster = skin.getSkinCluster(eyeMesh)
        if not skinCluster:
            skinCluster = pm.skinCluster(eyeCenter_jnt,
                                         eyeMesh,
                                         tsb=True,
                                         nw=1,
                                         n='skinClsEye')
Beispiel #35
0
def convert_joint_to_cluster(targetGeo, skipList=None, info=False):
    """
    Convert a skin cluster to a cluster based setup on a target geometery
    @param info: Whether to just query the data for in case we are building it later
    @param skipList: The joints which need to be skipped
    @param targetGeo: (string/pynode) The geometry which has the skin cluster
    @param skipList: (list) Any joints which should not processed such as a base joint
    @return A dictionary of cluster with the name of the joints as keys

    """
    if skipList is None:
        skipList = []
        # Convert to PyNode
    targetGeo = libUtilities.force_pynode(targetGeo)
    skin_name = libUtilities.get_target_defomer(targetGeo, "skinCluster")
    skin = libUtilities.force_pynode(skin_name)
    # Create the dictionary
    clusterInfo = {}
    # Progress Info
    pm.progressWindow(title='Converting Skin To Cluster', progress=0, status='Progress: 0%')
    totalJnts = len(skin.getInfluence()) - len(skipList)
    currentJnt = 0.0

    # Go through Each Joint
    for jnt in sorted(skin.getInfluence()):
        if jnt.name() in skipList:
            continue
        # Get the vertex affected and the weight
        vertZip, weightList = skin.getPointsAffectedByInfluence(jnt)
        if not vertZip:
            raise RuntimeError("Current Joint Has No Vertices:%s" % jnt)
        pm.select(vertZip)

        # Iterate through selection and decompress vertix group into individual index
        vertices = libUtilities.indexize_vertice_group(pm.selected())

        joint_position = pm.xform(jnt, q=1, ws=1, rp=1)
        # Select Vertices
        if info:
            clusterInfo[jnt.name()] = {"vertices": libUtilities.stringList(vertices),
                                       "weight": weightList,
                                       "position": joint_position}
        else:
            libUtilities.select_vertices(targetGeo, vertices)
            # Make a cluster
            cluster_info = weighted_cluster(targetGeo, vertices, weightList, joint_position)

            # Add to dictionary
            clusterInfo[jnt.name()] = cluster_info

        # Update Progress
        currentJnt += 1.0
        currentProgress = (currentJnt / totalJnts) * 100
        pm.progressWindow(edit=True, progress=currentProgress, status=('Progress: ' + str(int(currentProgress)) + '%'))
        pm.refresh()
        if info:
            logger.info("Info gathered: " + jnt.name())
        else:
            logger.info("Converted: " + jnt.name())

    pm.progressWindow(endProgress=1)
    return clusterInfo
Beispiel #36
0
def main():
    sel_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh")
    if not sel_list:
        QtWidgets.QMessageBox.warning(None, u"警告", u"请选择一个模型")
        return
    sel = sel_list[0]
    # pm.undoInfo(ock=1)

    num_list, total = sel.getUvShellsIds()
    shell_dict = {num: i for i, num in enumerate(num_list)}
    border_dict = defaultdict(dict)
    uv_dict = {}

    for i, uv in shell_dict.items():
        pm.select(sel.map[uv])
        pm.polySelectConstraint(uv=1, bo=0, m=2)
        uv_list = pm.ls(pm.polySelectConstraint(uv=0, rs=1), fl=1)
        face_list = pm.polyListComponentConversion(fuv=1, tf=1)
        border_list = pm.ls(pm.polyListComponentConversion(fuv=1, te=1, bo=1),
                            fl=1)
        _border_list = [e.index() for e in border_list]

        edge_dict = {
            edge: {
                face.getUVIndex(j): face.getUV(j)
                for j in range(face.polygonVertexCount())
            }
            for face in pm.ls(face_list, fl=1) for edge in face.getEdges()
            if edge in _border_list
        }

        border_dict = {}
        border_uvs = pm.polyListComponentConversion(border_list, fe=1, tuv=1)
        border_uvs = [uv for uv in pm.ls(border_uvs, fl=1) if uv in uv_list]
        for uv in border_uvs:
            edges = pm.polyListComponentConversion(uv, fuv=1, te=1)
            edges = [e for e in pm.ls(edges, fl=1) if e in border_list]
            uvs = pm.polyListComponentConversion(edges, fe=1, tuv=1)
            uvs = [
                _uv for _uv in pm.ls(uvs, fl=1)
                if _uv != uv and _uv in border_uvs
            ]
            border_dict[uv] = uvs

        print(border_dict)
        break
        # print(json.dumps(edge_dict))

    return

    # TODO 遍历 polygon 找 UV 对应关系

    dag_path = sel.__apimdagpath__()
    itr = OpenMaya.MItMeshPolygon(dag_path)

    util = OpenMaya.MScriptUtil()

    edge_dict = defaultdict(list)
    while not itr.isDone():
        face_idx = itr.index()

        uv = {}
        for i in range(itr.polygonVertexCount()):
            idx_ptr = util.asIntPtr()
            u_ptr = util.asFloatPtr()
            v_ptr = util.asFloatPtr()
            itr.getUVIndex(i, idx_ptr, u_ptr, v_ptr)
            idx = util.getInt(idx_ptr)
            u = util.getFloat(u_ptr)
            v = util.getFloat(v_ptr)
            uv[idx] = (u, v)

        edges = OpenMaya.MIntArray()
        itr.getEdges(edges)
        for i in range(edges.length()):
            edge = edges[i]
            edge_dict[edge].append({"uv": uv, "face_idx": face_idx})

        itr.next()

    edge_list = []
    for edge_idx, data in edge_dict.items():
        print(len(data))
        if len(data) == 1:
            edge_list.append(edge_idx)
    print(edge_list)
    # print(json.dumps(edge_dict))

    return

    pm.progressWindow(title=u"获取 uv border",
                      status=u"获取模型 uv border...",
                      progress=0.0)
    for i, uv in shell_dict.items():
        pm.progressWindow(e=1, progress=i / total * 100)
        # NOTES(timmyliang) 如果 uv 不在 0,1 象限则跳过
        x, y = sel.getUV(uv)

        if not 0 < x < 1 or not 0 < y < 1:
            continue

        pm.select(sel.map[uv])
        pm.polySelectConstraint(uv=1, bo=0, m=2)
        uv_list = pm.polySelectConstraint(t=0x0010, uv=0, bo=1, m=2, rs=1)
        uv_list = [_uv.currentItemIndex() for _uv in pm.ls(uv_list, fl=1)]
        pos_list = {uv: sel.getUV(uv) for uv in uv_list}
        x = sum([pos[0] for pos in pos_list.values()]) / len(pos_list)
        y = sum([pos[1] for pos in pos_list.values()]) / len(pos_list)
        uv_dict.update(pos_list)
        borders = pm.polyListComponentConversion(fuv=1, te=1, bo=1)
        borders = pm.ls(borders, fl=1)
        for uv in uv_list:
            edges = pm.polyListComponentConversion(sel.map[uv], fuv=1, te=1)
            edges = [e for e in pm.ls(edges, fl=1) if e in borders]
            uvs = pm.polyListComponentConversion(edges, fe=1, tuv=1)
            uvs = [_uv.currentItemIndex() for _uv in pm.ls(uvs, fl=1)]
            uvs = [_uv for _uv in uvs if _uv != uv and _uv in uv_list]
            border_dict[uv] = {"uvs": uvs, "center": (x, y)}

    pm.progressWindow(ep=1)
    pm.polySelectConstraint(uv=0, bo=0, rs=1)

    distant = 0.01

    for uv, data in border_dict.items():
        uvs = data.get("uvs", [])
        if len(uvs) <= 1:
            continue
        uv1, uv2 = uvs
        x, y = data.get("center")
        center = dt.Vector(x, y)

        pos = dt.Vector(*uv_dict[uv])
        pos1 = dt.Vector(*uv_dict[uv1])
        pos2 = dt.Vector(*uv_dict[uv2])
        vec1 = pos - pos1
        vec2 = pos2 - pos

        x, y = get_pt(pos, pos1, pos2, vec1, vec2, distant)
        pt = dt.Vector(x, y)
        vec = pos - pt
        line = pos - center
        # NOTE reverse
        if vec.dot(line) > 0:
            x, y = get_pt(pos, pos1, pos2, vec1, vec2, distant, True)
        sel.setUV(uv, x, y)

    face_list = pm.polyUVOverlap(sel.faces, oc=True)
    pm.undoInfo(cck=1)
    def _addControlJoints(self,
                          crv,
                          name,
                          rope_root,
                          rope,
                          rope_upv,
                          skipHeadAndTail=False):

        lvlType = "transform"
        cvs = crv.getCVs(space="world")
        local_cvs = crv.getCVs(space="object")
        controls = []
        t = getTransform(self.root)

        icon_shape = "sphere"
        color = 4
        wd = .3
        po = self.offset * 0.3

        pm.progressWindow(title='Creating Upper Joints',
                          progress=0,
                          max=len(cvs))

        for i, cv in enumerate(cvs):
            if skipHeadAndTail and i == 0:
                continue

            if skipHeadAndTail and (i == len(cvs) - 1):
                continue

            pm.progressWindow(e=True,
                              step=1,
                              status='\nCreating Joint for  %s' % cv)

            upv = addTransform(
                rope_root,
                self.getName("{}LipRope_upv{}".format(name,
                                                      str(i).zfill(3))))
            npo = addTransform(
                rope_root,
                self.getName("{}LipRope_npo{}".format(name,
                                                      str(i).zfill(3))))

            oParam, oLength = curve.getCurveParamAtPosition(rope, local_cvs[i])
            uLength = curve.findLenghtFromParam(rope, oParam)
            u = uLength / oLength

            cns = applyPathCnsLocal(upv, rope_upv, u)
            cns = applyPathCnsLocal(npo, rope, u)

            pm.connectAttr(upv.attr("worldMatrix[0]"),
                           cns.attr("worldUpMatrix"))

            ctl_name = self.getName("%s_crvdetail%s_%s" %
                                    (name, i, self.ctlName))

            self.thickness = 0.0
            if i == 0:
                # we know the curv starts from right to left
                offset = [
                    cv[0] + self.thickness, cv[1], cv[2] + self.thickness
                ]

            elif i == len(cvs) - 1:
                offset = [
                    cv[0] - self.thickness, cv[1], cv[2] + self.thickness
                ]

            else:
                offset = [cv[0], cv[1] - self.thickness, cv[2]]

            # offset = [cv[0], cv[1], cv[2] - self.FRONT_OFFSET]
            m = getTransform(npo)
            x = datatypes.Vector(m[0][0], m[0][1], m[0][2])
            y = datatypes.Vector(m[1][0], m[1][1], m[1][2])
            z = datatypes.Vector(m[2][0], m[2][1], m[2][2])
            rot = [x, y, z]
            xform = setMatrixPosition(t, offset)
            xform = setMatrixRotation(xform, rot)
            # xform = setMatrixPosition(t, cv)

            npo_name = self.getName("{}LipRope_jnt{}_npo".format(name, str(i)))
            npo = addTransform(npo, npo_name, xform)

            ctl = self.addCtl(npo,
                              ctl_name,
                              xform,
                              color,
                              icon_shape,
                              w=wd,
                              d=wd,
                              ro=datatypes.Vector(1.57079633, 0, 0),
                              po=po)

            controls.append(ctl)

            # getting joint parent
            # jnt = rigbits.addJnt(npo, noReplace=True, parent=self.j_parent)
            self.jnt_pos.append([ctl, "{}{}".format(name, i)])
            self.addToSubGroup(ctl, self.detailControllersGroupName)

        pm.progressWindow(e=True, endProgress=True)
        return controls
Beispiel #38
0
def rig(edge_loop="",
        up_vertex="",
        low_vertex="",
        name_prefix="",
        thickness=0.3,
        do_skin=True,
        rigid_loops=5,
        falloff_loops=8,
        head_joint=None,
        jaw_joint=None,
        parent_node=None,
        control_name="ctl",
        upper_lip_ctl=None,
        lower_lip_ctl=None):

    ######
    # Var
    ######

    FRONT_OFFSET = .02
    NB_ROPE = 15

    ##################
    # Helper functions
    ##################
    def setName(name, side="C", idx=None):
        namesList = [name_prefix, side, name]
        if idx is not None:
            namesList[1] = side + str(idx)
        name = "_".join(namesList)
        return name

    ###############
    # Checkers
    ##############

    # Loop
    if edge_loop:
        try:
            edge_loop = [pm.PyNode(e) for e in edge_loop.split(",")]
        except pm.MayaNodeError:
            pm.displayWarning(
                "Some of the edges listed in edge loop can not be found")
            return
    else:
        pm.displayWarning("Please set the edge loop first")
        return

    # Vertex
    if up_vertex:
        try:
            up_vertex = pm.PyNode(up_vertex)
        except pm.MayaNodeError:
            pm.displayWarning("%s can not be found" % up_vertex)
            return
    else:
        pm.displayWarning("Please set the upper lip central vertex")
        return

    if low_vertex:
        try:
            low_vertex = pm.PyNode(low_vertex)
        except pm.MayaNodeError:
            pm.displayWarning("%s can not be found" % low_vertex)
            return
    else:
        pm.displayWarning("Please set the lower lip central vertex")
        return

    # skinnign data
    if do_skin:
        if not head_joint:
            pm.displayWarning("Please set the Head Jnt or unCheck Compute "
                              "Topological Autoskin")
            return
        else:
            try:
                head_joint = pm.PyNode(head_joint)
            except pm.MayaNodeError:
                pm.displayWarning(
                    "Head Joint: %s can not be found" % head_joint
                )
                return
        if not jaw_joint:
            pm.displayWarning("Please set the Jaw Jnt or unCheck Compute "
                              "Topological Autoskin")
            return
        else:
            try:
                jaw_joint = pm.PyNode(jaw_joint)
            except pm.MayaNodeError:
                pm.displayWarning("Jaw Joint: %s can not be found" % jaw_joint)
                return
    # check if the rig already exist in the current scene
    if pm.ls(setName("root")):
        pm.displayWarning("The object %s already exist in the scene. Please "
                          "choose another name prefix" % setName("root"))
        return

    #####################
    # Root creation
    #####################
    lips_root = primitive.addTransform(None, setName("root"))
    lipsCrv_root = primitive.addTransform(lips_root, setName("crvs"))
    lipsRope_root = primitive.addTransform(lips_root, setName("rope"))

    #####################
    # Geometry
    #####################
    geo = pm.listRelatives(edge_loop[0], parent=True)[0]

    #####################
    # Groups
    #####################
    try:
        ctlSet = pm.PyNode("rig_controllers_grp")
    except pm.MayaNodeError:
        pm.sets(n="rig_controllers_grp", em=True)
        ctlSet = pm.PyNode("rig_controllers_grp")
    try:
        defset = pm.PyNode("rig_deformers_grp")
    except pm.MayaNodeError:
        pm.sets(n="rig_deformers_grp", em=True)
        defset = pm.PyNode("rig_deformers_grp")

    #####################
    # Curves creation
    #####################

    # get extreme position using the outer loop
    extr_v = meshNavigation.getExtremeVertexFromLoop(edge_loop)
    upPos = extr_v[0]
    lowPos = extr_v[1]
    inPos = extr_v[2]
    outPos = extr_v[3]
    edgeList = extr_v[4]
    vertexList = extr_v[5]
    upPos = up_vertex
    lowPos = low_vertex

    # upper crv
    upLip_edgeRange = meshNavigation.edgeRangeInLoopFromMid(edgeList,
                                                            upPos,
                                                            inPos,
                                                            outPos)
    upCrv = curve.createCuveFromEdges(upLip_edgeRange,
                                      setName("upperLip"),
                                      parent=lipsCrv_root)
    # store the closest vertex by curv cv index. To be use fo the auto skining
    upLip_closestVtxList = []
    # offset upper lip Curve
    cvs = upCrv.getCVs(space="world")
    for i, cv in enumerate(cvs):

        closestVtx = meshNavigation.getClosestVertexFromTransform(geo, cv)
        upLip_closestVtxList.append(closestVtx)
        if i == 0:
            # we know the curv starts from right to left
            offset = [cv[0] - thickness, cv[1], cv[2] - thickness]
        elif i == len(cvs) - 1:
            offset = [cv[0] + thickness, cv[1], cv[2] - thickness]
        else:
            offset = [cv[0], cv[1] + thickness, cv[2]]
        upCrv.setCV(i, offset, space='world')

    # lower crv
    lowLip_edgeRange = meshNavigation.edgeRangeInLoopFromMid(edgeList,
                                                             lowPos,
                                                             inPos,
                                                             outPos)
    lowCrv = curve.createCuveFromEdges(lowLip_edgeRange,
                                       setName("lowerLip"),
                                       parent=lipsCrv_root)
    lowLip_closestVtxList = []
    # offset lower lip Curve
    cvs = lowCrv.getCVs(space="world")
    for i, cv in enumerate(cvs):
        closestVtx = meshNavigation.getClosestVertexFromTransform(geo, cv)
        lowLip_closestVtxList.append(closestVtx)
        if i == 0:
            # we know the curv starts from right to left
            offset = [cv[0] - thickness, cv[1], cv[2] - thickness]
        elif i == len(cvs) - 1:
            offset = [cv[0] + thickness, cv[1], cv[2] - thickness]
        else:
            # we populate the closest vertext list here to skipt the first
            # and latest point
            offset = [cv[0], cv[1] - thickness, cv[2]]
        lowCrv.setCV(i, offset, space='world')

    upCrv_ctl = curve.createCurveFromCurve(upCrv,
                                           setName("upCtl_crv"),
                                           nbPoints=7,
                                           parent=lipsCrv_root)
    lowCrv_ctl = curve.createCurveFromCurve(lowCrv,
                                            setName("lowCtl_crv"),
                                            nbPoints=7,
                                            parent=lipsCrv_root)

    upRope = curve.createCurveFromCurve(upCrv,
                                        setName("upRope_crv"),
                                        nbPoints=NB_ROPE,
                                        parent=lipsCrv_root)
    lowRope = curve.createCurveFromCurve(lowCrv,
                                         setName("lowRope_crv"),
                                         nbPoints=NB_ROPE,
                                         parent=lipsCrv_root)

    upCrv_upv = curve.createCurveFromCurve(upCrv,
                                           setName("upCrv_upv"),
                                           nbPoints=7,
                                           parent=lipsCrv_root)
    lowCrv_upv = curve.createCurveFromCurve(lowCrv,
                                            setName("lowCrv_upv"),
                                            nbPoints=7,
                                            parent=lipsCrv_root)

    upRope_upv = curve.createCurveFromCurve(upCrv,
                                            setName("upRope_upv"),
                                            nbPoints=NB_ROPE,
                                            parent=lipsCrv_root)
    lowRope_upv = curve.createCurveFromCurve(lowCrv,
                                             setName("lowRope_upv"),
                                             nbPoints=NB_ROPE,
                                             parent=lipsCrv_root)

    # offset upv curves

    for crv in [upCrv_upv, lowCrv_upv, upRope_upv, lowRope_upv]:
        cvs = crv.getCVs(space="world")
        for i, cv in enumerate(cvs):

            # we populate the closest vertext list here to skipt the first
            # and latest point
            offset = [cv[0], cv[1], cv[2] + FRONT_OFFSET]
            crv.setCV(i, offset, space='world')

    rigCrvs = [upCrv,
               lowCrv,
               upCrv_ctl,
               lowCrv_ctl,
               upRope,
               lowRope,
               upCrv_upv,
               lowCrv_upv,
               upRope_upv,
               lowRope_upv]

    for crv in rigCrvs:
        crv.attr("visibility").set(False)

    ##################
    # Joints
    ##################

    lvlType = "transform"

    # upper joints
    upperJoints = []
    cvs = upCrv.getCVs(space="world")
    pm.progressWindow(title='Creating Upper Joints', progress=0, max=len(cvs))

    for i, cv in enumerate(cvs):
        pm.progressWindow(e=True,
                          step=1,
                          status='\nCreating Joint for  %s' % cv)
        oTransUpV = pm.PyNode(pm.createNode(
            lvlType,
            n=setName("upLipRopeUpv", idx=str(i).zfill(3)),
            p=lipsRope_root,
            ss=True))
        oTrans = pm.PyNode(
            pm.createNode(lvlType,
                          n=setName("upLipRope", idx=str(i).zfill(3)),
                          p=lipsRope_root, ss=True))

        oParam, oLength = curve.getCurveParamAtPosition(upRope, cv)
        uLength = curve.findLenghtFromParam(upRope, oParam)
        u = uLength / oLength

        applyop.pathCns(
            oTransUpV, upRope_upv, cnsType=False, u=u, tangent=False)

        cns = applyop.pathCns(
            oTrans, upRope, cnsType=False, u=u, tangent=False)

        cns.setAttr("worldUpType", 1)
        cns.setAttr("frontAxis", 0)
        cns.setAttr("upAxis", 1)

        pm.connectAttr(oTransUpV.attr("worldMatrix[0]"),
                       cns.attr("worldUpMatrix"))

        # getting joint parent
        if head_joint and isinstance(head_joint, (str, string_types)):
            try:
                j_parent = pm.PyNode(head_joint)
            except pm.MayaNodeError:
                j_parent = False
        elif head_joint and isinstance(head_joint, pm.PyNode):
            j_parent = head_joint
        else:
            j_parent = False

        jnt = rigbits.addJnt(oTrans, noReplace=True, parent=j_parent)
        upperJoints.append(jnt)
        pm.sets(defset, add=jnt)
    pm.progressWindow(e=True, endProgress=True)

    # lower joints
    lowerJoints = []
    cvs = lowCrv.getCVs(space="world")
    pm.progressWindow(title='Creating Lower Joints', progress=0, max=len(cvs))

    for i, cv in enumerate(cvs):
        pm.progressWindow(e=True,
                          step=1,
                          status='\nCreating Joint for  %s' % cv)
        oTransUpV = pm.PyNode(pm.createNode(
            lvlType,
            n=setName("lowLipRopeUpv", idx=str(i).zfill(3)),
            p=lipsRope_root,
            ss=True))

        oTrans = pm.PyNode(pm.createNode(
            lvlType,
            n=setName("lowLipRope", idx=str(i).zfill(3)),
            p=lipsRope_root,
            ss=True))

        oParam, oLength = curve.getCurveParamAtPosition(lowRope, cv)
        uLength = curve.findLenghtFromParam(lowRope, oParam)
        u = uLength / oLength

        applyop.pathCns(oTransUpV,
                        lowRope_upv,
                        cnsType=False,
                        u=u,
                        tangent=False)
        cns = applyop.pathCns(oTrans,
                              lowRope,
                              cnsType=False,
                              u=u,
                              tangent=False)

        cns.setAttr("worldUpType", 1)
        cns.setAttr("frontAxis", 0)
        cns.setAttr("upAxis", 1)

        pm.connectAttr(oTransUpV.attr("worldMatrix[0]"),
                       cns.attr("worldUpMatrix"))

        # getting joint parent
        if jaw_joint and isinstance(jaw_joint, (str, string_types)):
            try:
                j_parent = pm.PyNode(jaw_joint)
            except pm.MayaNodeError:
                pass
        elif jaw_joint and isinstance(jaw_joint, pm.PyNode):
            j_parent = jaw_joint
        else:
            j_parent = False
        jnt = rigbits.addJnt(oTrans, noReplace=True, parent=j_parent)
        lowerJoints.append(jnt)
        pm.sets(defset, add=jnt)
    pm.progressWindow(e=True, endProgress=True)

    ##################
    # Controls
    ##################

    # Controls lists
    upControls = []
    upVec = []
    upNpo = []
    lowControls = []
    lowVec = []
    lowNpo = []
    # controls options
    axis_list = ["sx", "sy", "sz", "ro"]
    upCtlOptions = [["corner", "R", "square", 4, .05, axis_list],
                    ["upOuter", "R", "circle", 14, .03, []],
                    ["upInner", "R", "circle", 14, .03, []],
                    ["upper", "C", "square", 4, .05, axis_list],
                    ["upInner", "L", "circle", 14, .03, []],
                    ["upOuter", "L", "circle", 14, .03, []],
                    ["corner", "L", "square", 4, .05, axis_list]]

    lowCtlOptions = [["lowOuter", "R", "circle", 14, .03, []],
                     ["lowInner", "R", "circle", 14, .03, []],
                     ["lower", "C", "square", 4, .05, axis_list],
                     ["lowInner", "L", "circle", 14, .03, []],
                     ["lowOuter", "L", "circle", 14, .03, []]]

    params = ["tx", "ty", "tz", "rx", "ry", "rz"]

    # upper controls
    cvs = upCrv_ctl.getCVs(space="world")
    pm.progressWindow(title='Upper controls', progress=0, max=len(cvs))

    v0 = transform.getTransformFromPos(cvs[0])
    v1 = transform.getTransformFromPos(cvs[-1])
    distSize = vector.getDistance(v0, v1) * 3

    for i, cv in enumerate(cvs):
        pm.progressWindow(e=True,
                          step=1,
                          status='\nCreating control for%s' % cv)
        t = transform.getTransformFromPos(cv)

        # Get nearest joint for orientation of controls
        joints = upperJoints + lowerJoints
        nearest_joint = None
        nearest_distance = None
        for joint in joints:
            distance = vector.getDistance(
                transform.getTranslation(joint),
                cv
            )
            if nearest_distance is None or distance < nearest_distance:
                nearest_distance = distance
                nearest_joint = joint

        if nearest_joint:
            t = transform.setMatrixPosition(
                transform.getTransform(nearest_joint), cv
            )
            temp = primitive.addTransform(
                lips_root, setName("temp"), t
            )
            temp.rx.set(0)
            t = transform.getTransform(temp)
            pm.delete(temp)

        oName = upCtlOptions[i][0]
        oSide = upCtlOptions[i][1]
        o_icon = upCtlOptions[i][2]
        color = upCtlOptions[i][3]
        wd = upCtlOptions[i][4]
        oPar = upCtlOptions[i][5]
        npo = primitive.addTransform(lips_root,
                                     setName("%s_npo" % oName, oSide),
                                     t)
        upNpo.append(npo)
        ctl = icon.create(npo,
                          setName("%s_%s" % (oName, control_name), oSide),
                          t,
                          icon=o_icon,
                          w=wd * distSize,
                          d=wd * distSize,
                          ro=datatypes.Vector(1.57079633, 0, 0),
                          po=datatypes.Vector(0, 0, .07 * distSize),
                          color=color)

        upControls.append(ctl)
        name_split = control_name.split("_")
        if len(name_split) == 2 and name_split[-1] == "ghost":
            pass
        else:
            pm.sets(ctlSet, add=ctl)
        attribute.addAttribute(ctl, "isCtl", "bool", keyable=False)
        attribute.setKeyableAttributes(ctl, params + oPar)

        upv = primitive.addTransform(ctl, setName("%s_upv" % oName, oSide), t)
        upv.attr("tz").set(FRONT_OFFSET)
        upVec.append(upv)
        if oSide == "R":
            npo.attr("sx").set(-1)
    pm.progressWindow(e=True, endProgress=True)

    # lower controls
    cvs = lowCrv_ctl.getCVs(space="world")
    pm.progressWindow(title='Lower controls', progress=0, max=len(cvs))

    for i, cv in enumerate(cvs[1:-1]):
        pm.progressWindow(e=True,
                          step=1,
                          status='\nCreating control for%s' % cv)

        t = transform.getTransformFromPos(cv)

        # Get nearest joint for orientation of controls
        joints = upperJoints + lowerJoints
        nearest_joint = None
        nearest_distance = None
        for joint in joints:
            distance = vector.getDistance(
                transform.getTranslation(joint),
                cv
            )
            if nearest_distance is None or distance < nearest_distance:
                nearest_distance = distance
                nearest_joint = joint

        if nearest_joint:
            t = transform.setMatrixPosition(
                transform.getTransform(nearest_joint), cv
            )
            temp = primitive.addTransform(
                lips_root, setName("temp"), t
            )
            temp.rx.set(0)
            t = transform.getTransform(temp)
            pm.delete(temp)

        oName = lowCtlOptions[i][0]
        oSide = lowCtlOptions[i][1]
        o_icon = lowCtlOptions[i][2]
        color = lowCtlOptions[i][3]
        wd = lowCtlOptions[i][4]
        oPar = lowCtlOptions[i][5]
        npo = primitive.addTransform(lips_root,
                                     setName("%s_npo" % oName, oSide),
                                     t)
        lowNpo.append(npo)
        ctl = icon.create(npo,
                          setName("%s_%s" % (oName, control_name), oSide),
                          t,
                          icon=o_icon,
                          w=wd * distSize,
                          d=wd * distSize,
                          ro=datatypes.Vector(1.57079633, 0, 0),
                          po=datatypes.Vector(0, 0, .07 * distSize),
                          color=color)
        lowControls.append(ctl)
        name_split = control_name.split("_")
        if len(name_split) == 2 and control_name.split("_")[-1] == "ghost":
            pass
        else:
            pm.sets(ctlSet, add=ctl)
        attribute.addAttribute(ctl, "isCtl", "bool", keyable=False)
        attribute.setKeyableAttributes(ctl, params + oPar)

        upv = primitive.addTransform(ctl, setName("%s_upv" % oName, oSide), t)
        upv.attr("tz").set(FRONT_OFFSET)
        lowVec.append(upv)
        if oSide == "R":
            npo.attr("sx").set(-1)
    pm.progressWindow(e=True, endProgress=True)

    # reparentig controls
    pm.parent(upNpo[1], lowNpo[0], upControls[0])
    pm.parent(upNpo[2], upNpo[4], upControls[3])
    pm.parent(upNpo[-2], lowNpo[-1], upControls[-1])
    pm.parent(lowNpo[1], lowNpo[3], lowControls[2])

    # Connecting control crvs with controls
    applyop.gear_curvecns_op(upCrv_ctl, upControls)
    applyop.gear_curvecns_op(lowCrv_ctl,
                             [upControls[0]] + lowControls + [upControls[-1]])

    applyop.gear_curvecns_op(upCrv_upv, upVec)
    applyop.gear_curvecns_op(lowCrv_upv, [upVec[0]] + lowVec + [upVec[-1]])

    # adding wires
    pm.wire(upCrv, w=upCrv_ctl, dropoffDistance=[0, 1000])
    pm.wire(lowCrv, w=lowCrv_ctl, dropoffDistance=[0, 1000])
    pm.wire(upRope, w=upCrv_ctl, dropoffDistance=[0, 1000])
    pm.wire(lowRope, w=lowCrv_ctl, dropoffDistance=[0, 1000])

    pm.wire(upRope_upv, w=upCrv_upv, dropoffDistance=[0, 1000])
    pm.wire(lowRope_upv, w=lowCrv_upv, dropoffDistance=[0, 1000])

    # setting constrains
    # up
    cns_node = pm.parentConstraint(upControls[0],
                                   upControls[3],
                                   upControls[1].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(upControls[0].name() + "W0").set(.75)
    cns_node.attr(upControls[3].name() + "W1").set(.25)
    cns_node.interpType.set(0)  # noFlip

    cns_node = pm.parentConstraint(upControls[0],
                                   upControls[3],
                                   upControls[2].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(upControls[0].name() + "W0").set(.25)
    cns_node.attr(upControls[3].name() + "W1").set(.75)
    cns_node.interpType.set(0)  # noFlip

    cns_node = pm.parentConstraint(upControls[3],
                                   upControls[6],
                                   upControls[4].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(upControls[3].name() + "W0").set(.75)
    cns_node.attr(upControls[6].name() + "W1").set(.25)
    cns_node.interpType.set(0)  # noFlip

    cns_node = pm.parentConstraint(upControls[3],
                                   upControls[6],
                                   upControls[5].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(upControls[3].name() + "W0").set(.25)
    cns_node.attr(upControls[6].name() + "W1").set(.75)
    cns_node.interpType.set(0)  # noFlip

    # low
    cns_node = pm.parentConstraint(upControls[0],
                                   lowControls[2],
                                   lowControls[0].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(upControls[0].name() + "W0").set(.75)
    cns_node.attr(lowControls[2].name() + "W1").set(.25)
    cns_node.interpType.set(0)  # noFlip

    cns_node = pm.parentConstraint(upControls[0],
                                   lowControls[2],
                                   lowControls[1].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(upControls[0].name() + "W0").set(.25)
    cns_node.attr(lowControls[2].name() + "W1").set(.75)
    cns_node.interpType.set(0)  # noFlip

    cns_node = pm.parentConstraint(lowControls[2],
                                   upControls[6],
                                   lowControls[3].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(lowControls[2].name() + "W0").set(.75)
    cns_node.attr(upControls[6].name() + "W1").set(.25)
    cns_node.interpType.set(0)  # noFlip

    cns_node = pm.parentConstraint(lowControls[2],
                                   upControls[6],
                                   lowControls[4].getParent(),
                                   mo=True,
                                   skipRotate=["x", "y", "z"])
    cns_node.attr(lowControls[2].name() + "W0").set(.25)
    cns_node.attr(upControls[6].name() + "W1").set(.75)
    cns_node.interpType.set(0)  # noFlip

    ###########################################
    # Connecting rig
    ###########################################
    if parent_node:
        try:
            if isinstance(parent_node, string_types):
                parent_node = pm.PyNode(parent_node)
            parent_node.addChild(lips_root)
        except pm.MayaNodeError:
            pm.displayWarning("The Lips rig can not be parent to: %s. Maybe "
                              "this object doesn't exist." % parent_node)
    if head_joint and jaw_joint:
        try:
            if isinstance(head_joint, string_types):
                head_joint = pm.PyNode(head_joint)
        except pm.MayaNodeError:
            pm.displayWarning("Head Joint or Upper Lip Joint %s. Can not be "
                              "fount in the scene" % head_joint)
            return
        try:
            if isinstance(jaw_joint, string_types):
                jaw_joint = pm.PyNode(jaw_joint)
        except pm.MayaNodeError:
            pm.displayWarning("Jaw Joint or Lower Lip Joint %s. Can not be "
                              "fount in the scene" % jaw_joint)
            return

        ref_ctls = [head_joint, jaw_joint]

        if upper_lip_ctl and lower_lip_ctl:
            try:
                if isinstance(upper_lip_ctl, string_types):
                    upper_lip_ctl = pm.PyNode(upper_lip_ctl)
            except pm.MayaNodeError:
                pm.displayWarning("Upper Lip Ctl %s. Can not be "
                                  "fount in the scene" % upper_lip_ctl)
                return
            try:
                if isinstance(lower_lip_ctl, string_types):
                    lower_lip_ctl = pm.PyNode(lower_lip_ctl)
            except pm.MayaNodeError:
                pm.displayWarning("Lower Lip Ctl %s. Can not be "
                                  "fount in the scene" % lower_lip_ctl)
                return
            ref_ctls = [upper_lip_ctl, lower_lip_ctl]

        # in order to avoid flips lets create a reference transform
        # also to avoid flips, set any multi target parentConstraint to noFlip
        ref_cns_list = []
        print (ref_ctls)
        for cns_ref in ref_ctls:

            t = transform.getTransformFromPos(
                cns_ref.getTranslation(space='world'))
            ref = pm.createNode("transform",
                                n=cns_ref.name() + "_cns",
                                p=cns_ref,
                                ss=True)
            ref.setMatrix(t, worldSpace=True)
            ref_cns_list.append(ref)
        # right corner connection
        cns_node = pm.parentConstraint(ref_cns_list[0],
                                       ref_cns_list[1],
                                       upControls[0].getParent(),
                                       mo=True)
        cns_node.interpType.set(0)  # noFlip
        # left corner connection
        cns_node = pm.parentConstraint(ref_cns_list[0],
                                       ref_cns_list[1],
                                       upControls[-1].getParent(),
                                       mo=True)
        cns_node.interpType.set(0)  # noFlip
        # up control connection
        cns_node = pm.parentConstraint(ref_cns_list[0],
                                       upControls[3].getParent(),
                                       mo=True)
        # low control connection
        cns_node = pm.parentConstraint(ref_cns_list[1],
                                       lowControls[2].getParent(),
                                       mo=True)

    ###########################################
    # Auto Skinning
    ###########################################
    if do_skin:
        # eyelid vertex rows
        totalLoops = rigid_loops + falloff_loops
        vertexLoopList = meshNavigation.getConcentricVertexLoop(vertexList,
                                                                totalLoops)
        vertexRowList = meshNavigation.getVertexRowsFromLoops(vertexLoopList)

        # we set the first value 100% for the first initial loop
        skinPercList = [1.0]
        # we expect to have a regular grid topology
        for r in range(rigid_loops):
            for rr in range(2):
                skinPercList.append(1.0)
        increment = 1.0 / float(falloff_loops)
        # we invert to smooth out from 100 to 0
        inv = 1.0 - increment
        for r in range(falloff_loops):
            for rr in range(2):
                if inv < 0.0:
                    inv = 0.0
                skinPercList.append(inv)
            inv -= increment

        # this loop add an extra 0.0 indices to avoid errors
        for r in range(10):
            for rr in range(2):
                skinPercList.append(0.0)

        # base skin
        if head_joint:
            try:
                head_joint = pm.PyNode(head_joint)
            except pm.MayaNodeError:
                pm.displayWarning(
                    "Auto skin aborted can not find %s " % head_joint)
                return

        # Check if the object has a skinCluster
        objName = pm.listRelatives(geo, parent=True)[0]

        skinCluster = skin.getSkinCluster(objName)
        if not skinCluster:
            skinCluster = pm.skinCluster(head_joint,
                                         geo,
                                         tsb=True,
                                         nw=2,
                                         n='skinClsEyelid')

        lipsJoints = upperJoints + lowerJoints
        closestVtxList = upLip_closestVtxList + lowLip_closestVtxList
        pm.progressWindow(title='Auto skinning process',
                          progress=0,
                          max=len(lipsJoints))

        for i, jnt in enumerate(lipsJoints):
            pm.progressWindow(e=True, step=1, status='\nSkinning %s' % jnt)
            skinCluster.addInfluence(jnt, weight=0)
            v = closestVtxList[i]
            for row in vertexRowList:
                if v in row:
                    for i, rv in enumerate(row):
                        # find the deformer with max value for each vertex
                        w = pm.skinPercent(skinCluster,
                                           rv,
                                           query=True,
                                           value=True)
                        transJoint = pm.skinPercent(skinCluster,
                                                    rv,
                                                    query=True,
                                                    t=None)
                        max_value = max(w)
                        max_index = w.index(max_value)

                        perc = skinPercList[i]
                        t_value = [(jnt, perc),
                                   (transJoint[max_index], 1.0 - perc)]
                        pm.skinPercent(skinCluster,
                                       rv,
                                       transformValue=t_value)
        pm.progressWindow(e=True, endProgress=True)
Beispiel #39
0
	def cleanup_vrscene(self, vrsceneFile, palName):

		vrsceneDir = os.path.dirname(vrsceneFile)
		all_vrsfiles = os.listdir(vrsceneDir)

		vrsType = ['bitmaps', 'geometry', 'materials', 'nodes', 'textures']

		if not all_vrsfiles:
			self.notifyMsg('.vrscene dir is empty.', 2)
			pm.error('[XGen Hub] : .vrscene dir is empty. -> ' + vrsceneDir)
			return None

		amount = 0
		pm.progressWindow(title='cleanup vrscene',
						  progress=amount,
						  status='Cleaning...',
						  maxValue=len(all_vrsfiles),
						  isInterruptable=False)
		try:
			for vrsfile in all_vrsfiles:
				amount += 1
				pm.progressWindow(edit=True, progress=amount)

				if not vrsfile.endswith(".vrscene"):
					continue
				if any(vrsfile.endswith("_{}.vrscene".format(typ)) for typ in vrsType):
					continue

				vrsfile_path = os.path.join(vrsceneDir, vrsfile)

				# read
				headnotes = ''
				samplers = ''
				include = ''
				with open(vrsfile_path, 'r') as vrscene:
					is_processed = False
					is_sampler = False
					for i, line in enumerate(vrscene):
						if i <= 8:
							if "(Processed)" in line:
								is_processed = True
								break
							headnotes += line

						if line.startswith('TexHairSampler'):
							is_sampler = True
						if is_sampler:
							samplers += line
							if line.startswith('}'):
								samplers += '\n'
								is_sampler = False

						if line.startswith('#include'):
							include += line

				if is_processed:
					continue

				# mark processed
				headnotes = headnotes.replace("Exported by V-Ray Plugins Exporter",
								  			  "Exported by V-Ray Plugins Exporter (Processed)")

				# write
				with open(vrsfile_path, 'w') as vrscene:
					vrscene.write(headnotes + samplers + include)
		finally:
			pm.progressWindow(endProgress=1)
 def MirrorModules(self):
     mirrorModulesProgress_UI = pm.progressWindow(title = "Mirror Module(s)", status = "This may take a few minutes...", isInterruptable = False)
     mirrorModulesProgress = 0
     
     mirrorModulesProgress_stage1_proportion = 15
     mirrorModulesProgress_stage2_proportion = 70
     mirrorModulesProgress_stage3_proportion = 10
     
     moduleNameInfo = utils.FindAllModuleNames("/Modules/Blueprint")
     validModules = moduleNameInfo[0]
     validModuleNames = moduleNameInfo[1]
     
     for module in self.moduleInfo:
         moduleName = module[0].partition("__")[0]
         
         if moduleName in validModuleNames:
             index = validModuleNames.index(moduleName)
             module.append(validModules[index])
     
     
     # COLLECT DATA FOR MIRRORING
     mirrorModulesProgress_progressIncrement = mirrorModulesProgress_stage1_proportion / len(self.moduleInfo)
     for module in self.moduleInfo:
         userSpecifiedName = module[0].partition("__")[2]
         
         mod = __import__("Blueprint.%s" %module[5], {}, {}, [module[5]])
         reload(mod)
         
         moduleClass = getattr(mod, mod.CLASS_NAME)
         moduleInst = moduleClass(userSpecifiedName, None)
         
         hookObject = moduleInst.FindHookObject()
         
         newHookObject = None
         hookModule = utils.StripLeadingNamespace(hookObject)[0]
         
         hookFound = False
         for m in self.moduleInfo:
             if hookModule == m[0]:
                 hookFound = True
                 
                 if m == module:
                     continue
                 
                 hookObjectName = utils.StripLeadingNamespace(hookObject)[1]
                 newHookObject = "%s:%s" %(m[1], hookObjectName)
         
         if not hookFound:
             newHookObject = hookObject
         
         module.append(newHookObject)
         
         hookConstrained = moduleInst.IsRootConstrained()
         module.append(hookConstrained)
         
         
         # Increment progress bar
         mirrorModulesProgress += mirrorModulesProgress_progressIncrement
         pm.progressWindow(mirrorModulesProgress_UI, edit = True, progress = mirrorModulesProgress)
     
     
     
     
     # MIRROR MODULE
     mirrorModulesProgress_progressIncrement = mirrorModulesProgress_stage2_proportion / len(self.moduleInfo)
     for module in self.moduleInfo:
         newUserSpecifiedName = module[1].partition("__")[2]
         
         mod = __import__("Blueprint.%s" %module[5], {}, {}, [module[5]])
         reload(mod)
     
         moduleClass = getattr(mod, mod.CLASS_NAME)
         moduleInst = moduleClass(newUserSpecifiedName, None)
         
         moduleInst.Mirror(module[0], module[2], module[3], module[4])
         
         # Increment progress bar
         mirrorModulesProgress += mirrorModulesProgress_progressIncrement
         pm.progressWindow(mirrorModulesProgress_UI, edit = True, progress = mirrorModulesProgress)
     
     
     
     
     # MIRROR HOOKED RELATIONS
     mirrorModulesProgress_progressIncrement = mirrorModulesProgress_stage3_proportion / len (self.moduleInfo)
     for module in self.moduleInfo:
         newUserSpecifiedName = module[1].partition("__")[2]
         
         mod = __import__("Blueprint.%s" %module[5], {}, {}, [module[5]])
         reload(mod)
         
         moduleClass = getattr(mod, mod.CLASS_NAME)
         moduleInst = moduleClass(newUserSpecifiedName, None)
         
         moduleInst.Rehook(module[6])
         
         hookConstrained = module[7]
         if hookConstrained:
             moduleInst.ConstrainRootToHook()
         
         mirrorModulesProgress += mirrorModulesProgress_progressIncrement
         pm.progressWindow(mirrorModulesProgress_UI, edit = True, progress = mirrorModulesProgress)
     
     
     
     if self.group != None:
         pm.lockNode("Group_container", lock = False, lockUnpublished = False)
         
         groupParent = pm.listRelatives(self.group, parent = True)
         
         if groupParent != []:
             groupParent = groupParent = [0]
         
         self.ProcessGroup(self.group, groupParent)
         
         pm.lockNode("Group_container", lock = True, lockUnpublished = True)
         
         pm.select(clear = True)
     
     
     pm.progressWindow(mirrorModulesProgress_UI, edit = True, endProgress = True)
     
     utils.ForceSceneUpdate()
def doSelInvNRMFace( *args ):
    print "start!"
    # pm.delete( pm.ls(sl=True), ch=1 )
    selShape = pm.ls( sl=True, dag=True, type='shape' )

        
    faceInvertNRM = []
    
    offset = pm.floatFieldGrp( 'valOffset', q=True, value1=True )
    _x = pm.floatFieldGrp( 'valDir', q=True, value1=True )
    _y = pm.floatFieldGrp( 'valDir', q=True, value2=True )
    _z = pm.floatFieldGrp( 'valDir', q=True, value3=True )
    testRayDir = dt.Vector(_x, _y, _z)

    for shape in selShape:
        ## test if selected object type is "mesh"
        if( pm.nodeType(shape) != 'mesh' ):
            pm.confirmDialog( t="Error", message= shape.getParent() + " is not a mesh object! ", icon='critical' )
            return 0
            
        #pm.delete( shape, ch=1 )
        maxValue = float(len(shape.faces))
       
        pm.progressWindow( title='normal test Calculation', progress=0, maxValue=maxValue, isInterruptable=True, status='calculating: 0%' )
        for i, face in enumerate(shape.faces):
            try:
                pm.progressWindow( edit=True, progress=i, status=('calculating: ' + str( math.ceil( 100 * i/ maxValue) ) + '%') )
                
                ## ESC to cancel progress windows
                if pm.progressWindow( query=True, isCancelled=True ):
                    pm.progressWindow(endProgress=1)
                    break
                           
                curr_face = face
                obj_faces = shape.faces
                del_tmp_obj = [] 
                #// Test if face is NGon   
                if face.numTriangles() > 2:
                    tmp_obj = pm.duplicate( selShape, rr=True )[0]
                    del_face_id = [ id for id in range( len(obj_faces) ) if id != i  ]
                    pm.delete( tmp_obj.getShape().f[del_face_id] )
                    
                    #// triangulate N-Gon
                    pm.polyTriangulate( tmp_obj, ch=False )
                    
                    #//
                    curr_face = tmp_obj.getShape().f[0]
                    
                    #//
                    del_tmp_obj.append(tmp_obj)
                    
                    
                    
                pm.select( curr_face, r=1) 
                cenPos = getFaceCenter()
    
                faceNRM = curr_face.getNormal('world')
                offsetPos = cenPos + faceNRM * offset
                #testObj = pm.polySphere( r=5, sx=4, sy=4 )
                #testObj[0].setTranslation(offsetPos)
                
                ## test if point inside object
                testInside = isPointInsdeObject( shape, offsetPos, testRayDir )
                pm.delete(del_tmp_obj)
                
                if( testInside ):
                    faceInvertNRM.append( face )
            except:
                continue
   
    pm.progressWindow(endProgress=1) 
    pm.select( faceInvertNRM, r=1 )    
        
    return 1