Example #1
0
def cgmSimChain():
    try:
        from cgm.core.tools import dynFKTool
        reload(dynFKTool)
        dynFKTool.ui()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #2
0
def mrsShots():
    try:
        import cgm.core.mrs.Shots as SHOTS
        reload(SHOTS)
        x = SHOTS.ShotUI()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #3
0
def mrsScene():
    try:
        import cgm.core.mrs.Scene as SCENE
        reload(SCENE)
        x = SCENE.ui()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #4
0
def cgmProject():
    try:
        import cgm.core.tools.Project as PROJECT
        reload(PROJECT)
        x = PROJECT.ui()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #5
0
def mrsUI():
    try:
        import cgm.core.mrs.Builder as MRSBUILDER
        reload(MRSBUILDER)
        MRSBUILDER.ui()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #6
0
def camelCase(arg = None):
    """
    """
    _str_funcName = 'camelCase'
    try:
        l_split = arg.split(' ')
        l_new = []
        _first = False
        #pprint.pprint(l_split)
        if len(l_split) == 1:
            for i,a in enumerate(l_split):
                if a and len(a)>1:
                    l_new.append(a[0].lower()+a[1:])
        else:
            for i,a in enumerate(l_split):
                if a and len(a)>1:
                    if not _first:
                        l_new.append(a)
                        _first = True
                    else:
                        l_new.append(a[0].capitalize()+a[1:])
                
        return ''.join(l_new)


    except Exception,err:
        cgmGEN.cgmException(Exception,err)
def mrsScene():
    try:
        import cgm.core.mrs.Scene as SCENE
        reload(SCENE)
        #mel.eval('python "import cgm.core.mrs.Scene as SCENE;cgmSceneUI = SCENE.ui()"')
        SCENE.ui()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #8
0
def loadCGMSimpleGUI(*a):
    try:

        from cgm.core.classes import GuiFactory as uiFactory
        reload(uiFactory)
        uiFactory.cgmGUI()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #9
0
def animFilter():
    try:
        import cgm.core.tools.animFilterTool as ANIMFILTER
        reload(ANIMFILTER)
        mel.eval(
            'python "import cgm.core.tools.animFilterTool as ANIMFILTER;cgmAnimFilterUI = ANIMFILTER.ui()"'
        )
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #10
0
def animDraw():
    try:
        import cgm.core.tools.animDrawTool as ANIMDRAW
        reload(ANIMDRAW)
        mel.eval(
            'python "import cgm.core.tools.animDrawTool as ANIMDRAW;cgmAnimDrawUI = ANIMDRAW.ui()"'
        )
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #11
0
def cgmProject():
    try:
        import cgm.core.tools.Project as PROJECT
        reload(PROJECT)
        reload(PROJECT.PU)
        #x = PROJECT.ui()
        mel.eval(
            'python "import cgm;uiProject = cgm.core.tools.Project.ui();"')

    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #12
0
def angleBetween(p1, p2, p3):
    try:
        p1 = VALID.euclidVector3Arg(p1)
        p2 = VALID.euclidVector3Arg(p2)
        p3 = VALID.euclidVector3Arg(p3)

        v1 = (p2 - p1).normalized()
        v2 = (p3 - p2).normalized()

        return math.degrees(v1.angle(v2))
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #13
0
def animDraw():
    try:
        import cgm.core.tools.liveRecord as liveRecord
        reload(liveRecord)
        import cgm.core.tools.animDrawTool as ADT
        reload(ADT)
        import cgm.core.tools.animDraw as animDraw
        reload(animDraw)
        mel.eval(
            'python "import cgm.core.tools.animDrawTool as ANIMDRAW;cgmAnimDrawUI = ANIMDRAW.ui()"'
        )
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #14
0
def animDraw():
    try:
        import cgm.core.tools.liveRecord as liveRecord
        reload(liveRecord)
        import cgm.core.tools.animDrawTool as ADT
        reload(ADT)
        import cgm.core.tools.animDraw as animDraw
        reload(animDraw)
        mel.eval(
            'python "import cgm.core.tools.animDrawTool as ADT;animDrawInstance = ADT.ui();"'
        )

    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #15
0
def stripInvalidChars(arg=None,
                      invalidChars="""`~!@#$%^&*()-+=[]\\{}|;':"/?><., """,
                      noNumberStart=True,
                      functionSwap=True,
                      replaceChar='',
                      cleanDoubles=True,
                      stripTailing=True):
    """
    Modified from Hamish MacKenzie's zoo one

    :parameters:
    arg(str) - String to clean
    invalidChars(str) - Sequence of characters to remove
    	noNumberStart(bool) - remove numbers at start
    	functionSwap(bool) - whether to replace functions with string from dict
    	replaceChar(str) - Character to use to replace with
    	cleanDoubles(bool) - remove doubles
    	stripTrailing(bool) - remove trailing '_'

    returns l_pos
    """
    _str_funcName = 'stripInvalidChars'
    try:
        str_Clean = cgmValid.stringArg(arg, False, _str_funcName)

        for char in invalidChars:
            if functionSwap and char in d_functionStringSwaps.keys():
                str_Clean = str_Clean.replace(char,
                                              d_functionStringSwaps.get(char))
            else:
                str_Clean = str_Clean.replace(char, replaceChar)

        if noNumberStart:
            for n in range(10):
                while str_Clean.startswith(str(n)):
                    log.debug("Cleaning : %s" % str(n))
                    str_Clean = str_Clean[1:]
        if cleanDoubles and replaceChar:
            doubleChar = replaceChar + replaceChar
            while doubleChar in str_Clean:
                str_Clean = str_Clean.replace(doubleChar, replaceChar)

        if stripTailing:
            while str_Clean.endswith('_'):
                str_Clean = str_Clean[:-1]
        return str_Clean
    except Exception, err:
        cgmGeneral.cgmException(Exception, err)
Example #16
0
def get_axisSize(arg):
    try:
        _str_func = 'get_axisSize'
        bbSize = get_bb_size(arg)

        d_res = {'x': [], 'y': [], 'z': []}

        _startPoint = POS.get(arg, 'bb')
        _res = []
        for i, k in enumerate('xyz'):
            log.debug("|{0}| >> On t: {1} | {2}".format(_str_func, arg, k))

            pos_pos = get_pos_by_axis_dist(arg, k + '+', bbSize[i] * 1.5)
            pos_neg = get_pos_by_axis_dist(arg, k + '-', bbSize[i] * 1.5)

            pos1 = get_closest_point(pos_pos, arg)
            pos2 = get_closest_point(pos_neg, arg)

            dist = get_distance_between_points(pos1[0], pos2[0])
            _res.append(dist)

        return (_res)
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #17
0
def wing_temp(d_wiring=d_wiring_r, mode='slidingPosition'):
    """
    
    """
    try:
        _str_func = 'wing_temp'
        log.debug(cgmGEN.logString_start(_str_func))

        ml_roots = []
        ml_parts = []
        ml_rigNulls = []
        ml_blendDrivers = []

        #Dat get...
        for part in d_wiring['modules']:
            mPart = cgmMeta.asMeta(part)
            mRigNull = mPart.rigNull
            ml_parts.append(mPart)
            ml_rigNulls.append(mRigNull)
            ml_roots.append(mRigNull.rigRoot)
            ml_joints = mRigNull.msgList_get('blendJoints')
            if not ml_joints:
                for plug in 'fkAttachJoints', 'fkJoints':
                    ml_test = mRigNull.msgList_get(plug)
                    if ml_test:
                        ml_joints = ml_test
                        break
            ml_blendDrivers.append(ml_joints[0])

        pprint.pprint(vars())

        #Generate driver locs...
        for d, s in d_wiring['driven'].iteritems():
            mPart = ml_parts[d]
            mRoot = ml_roots[d]
            mRigNull = ml_rigNulls[d]
            mAttach = mRigNull.getMessageAsMeta('attachDriver')

            log.info(cgmGEN.logString_sub(_str_func, "{0} | {1}".format(d, s)))

            #...loc -----------------------------------------------------------------------
            log.info(cgmGEN.logString_msg(_str_func, 'loc...'))
            mLoc = mRoot.getMessageAsMeta('featherDriver')
            if mLoc:
                mLoc.delete()

            mLoc = ml_roots[d].doLoc()
            mLoc.rename("{0}_featherLoc".format(mPart.p_nameBase))
            mLoc.p_parent = mRoot.masterGroup.p_parent
            mLoc.v = False
            mLoc.doStore('cgmAlias', 'feather')

            mRoot.connectChildNode(mLoc.mNode, 'featherDriver', 'mPart')

            #...drivers ------------------------------------------------------------
            ml_drivers = [ml_blendDrivers[v] for v in s]
            l_drivers = [mObj.mNode for mObj in ml_drivers]
            _vList = DIST.get_normalizedWeightsByDistance(
                mLoc.mNode, l_drivers)

            _orient = mc.orientConstraint(l_drivers,
                                          mLoc.mNode,
                                          maintainOffset=0)
            l_constraints = [_orient]
            if mode == 'slidingPosition':
                _point = mc.pointConstraint(l_drivers,
                                            mLoc.mNode,
                                            maintainOffset=0)
                l_constraints.append(_point)
            else:
                _point = mc.pointConstraint(mAttach.mNode,
                                            mLoc.mNode,
                                            maintainOffset=1)

            for c in l_constraints:
                CONSTRAINT.set_weightsByDistance(c[0], _vList)

            ATTR.set(_orient[0], 'interpType', 2)
            mLoc.dagLock()

            mDynGroup = mRoot.dynParentGroup
            mDynGroup.addDynParent(mLoc)
            mDynGroup.rebuild()

            _len = len(ATTR.get_enumList(mRoot.mNode, 'space'))
            mRoot.space = _len - 1

        return True
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #18
0
def orientChain(joints=None,
                axisAim='z+',
                axisUp='y+',
                worldUpAxis=[0, 1, 0],
                relativeOrient=True,
                progressBar=None,
                axisBackup='x+',
                baseName=None,
                asMeta=True):
    """
    Given a series of positions, or objects, or a curve and a mesh - loft retopology it

    :parameters:


    :returns
        created(list)
    """
    try:
        _str_func = 'orientChain'
        if baseName: raise NotImplementedError, "Remove these calls"

        def orientJoint(mJnt):
            try:
                if mJnt not in ml_cull:
                    log.debug("|{0}| >> Aready done: {1}".format(
                        _str_func, mJnt.mNode))
                    return

                log.debug("|{0}| >> Orienting: {1}".format(
                    _str_func, mJnt.mNode))
                mParent = _d_parents[mJnt]
                if mParent and mParent in ml_cull:
                    return
                    log.debug("|{0}| >> Orienting parent: {1}".format(
                        _str_func, mParent.mNode))
                    orientJoint(mParent)

                if mJnt in ml_world:
                    log.debug("|{0}| >> World joint: {1}".format(
                        _str_func, mJnt.mNode))
                    try:
                        axisWorldOrient = SHARED._d_axisToJointOrient[str_aim][
                            str_up]
                    except Exception, err:
                        log.error("{0}>> World axis query. {1} | {2}".format(
                            _str_func, str_aim, str_up))
                        raise Exception, err

                    log.debug("|{0}| >> World joint: {1} | {2}".format(
                        _str_func, mJnt.mNode, axisWorldOrient))
                    mJnt.rotate = 0, 0, 0
                    mJnt.jointOrient = axisWorldOrient[0], axisWorldOrient[
                        1], axisWorldOrient[2]

                elif mJnt not in ml_ends:
                    log.debug("|{0}| >> Reg joint: {1}".format(
                        _str_func, mJnt.mNode))
                    mDup = mJnt.doDuplicate(parentOnly=True)
                    mc.makeIdentity(mDup.mNode, apply=1, jo=1)  #Freeze
                    b_rotFix = False

                    if relativeOrient and mParent:
                        p_child = _d_children[mJnt][0].p_position
                        p_me = mJnt.p_position
                        p_parent = mParent.p_position

                        _axisWorldUp = MATH.get_obj_vector(
                            mParent.mNode, axisUp)
                        _vecToChild = MATH.get_vector_of_two_points(
                            p_child, p_me)
                        _vecToParent = MATH.get_vector_of_two_points(
                            p_me, p_parent)
                        _vecFromParent = MATH.get_vector_of_two_points(
                            p_parent, p_me)

                        _angleVec = MATH.angleBetweenVectors(
                            _axisWorldUp, _vecToChild)
                        #_angle = MATH.angleBetweenVectors(_vecFromParent,_vecToChild)
                        _angle = MATH.angleBetween(p_child, p_me, p_parent)
                        #except:_angle = 0
                        _cross = MATH.dotproduct(_vecToChild, _vecToParent)

                        #pprint.pprint(vars())

                        log.debug(
                            cgmGEN.logString_msg(
                                _str_func,
                                "{0} | vec: {1} | angle: {2} | cross: {3}".
                                format(mJnt.mNode, _angleVec, _angle, _cross)))

                        if _angle > 70:
                            log.warning(
                                cgmGEN.logString_msg(
                                    _str_func,
                                    "{0} | dangerous angles vec: {1} | angle: {2} "
                                    .format(mJnt.mNode, _angleVec, _angle)))
                            #log.info(cgmGEN.logString_msg(_str_func,"dangerous cross: {0} ".format(_cross)))

                            #_axisWorldUp = MATH.get_obj_vector(mParent.mNode, axisBackup)

                            if _cross < 0:
                                _axisWorldUp = [-1 * v for v in _vecToParent]
                            else:
                                pass
                                #_axisWorldUp = _vecToParent
                                #_axisWorldUp = _lastVecUp
                            #v = MATH.transform_direction(

                            b_rotFix = True
                            """
                            if _angleVec < 1.0:
                                _axisWorldUp = MATH.averageVectors(_axisWorldUp,_vecToChild)
                                _axisWorldUp = MATH.averageVectors(_axisWorldUp,worldUpAxis)#.average in the world value
                                log.warning(cgmGEN.logString_msg(_str_func,"To child | postfix: {0} ".format(_axisWorldUp)))
                                
                            else:
                                _vecToParent = MATH.get_vector_of_two_points(p_me, p_parent)                        
                                _axisWorldUp = MATH.averageVectors(_axisWorldUp,_vecToParent)
                                _axisWorldUp = MATH.averageVectors(_axisWorldUp,worldUpAxis)#.average in the world value
                                log.warning(cgmGEN.logString_msg(_str_func,"To parent | postfix: {0} ".format(_axisWorldUp)))"""
                    else:
                        _axisWorldUp = worldUpAxis

                    mDup.rotateOrder = 0
                    SNAP.aim(mDup.mNode, _d_children[mJnt][0].mNode,
                             mAxis_aim.p_vector, mAxis_up.p_vector, 'vector',
                             _axisWorldUp)

                    if b_rotFix:
                        pass
                        """
                        a = 'r{0}'.format(axisAim[0])
                        v = ATTR.get(mDup.mNode,a)                
                        log.warning(cgmGEN.logString_msg(_str_func,"{0} | rotFix | a: {1} | v: {2}".format(mJnt.mNode,a,v)))
            
                        ATTR.set(mDup.mNode,a,90)"""

                    mJnt.rotate = 0, 0, 0
                    mJnt.jointOrient = mDup.p_orient
                    mDup.delete()

                if mJnt in ml_cull: ml_cull.remove(mJnt)
                return
            except Exception, err:
                cgmGEN.cgmException(Exception, err)
Example #19
0
def reload_cgmCore(*a):
    try:
        import cgm.core
        cgm.core._reload()
    except Exception, err:
        cgmGEN.cgmException(Exception, err)
Example #20
0
    def bake(self, startTime=None, endTime=None):
        _str_func = 'PostBake.bake'

        self._cancelBake = False

        self.startTime = int(mc.playbackOptions(
            q=True, min=True)) if startTime is None else startTime
        self.endTime = int(mc.playbackOptions(
            q=True, max=True)) if endTime is None else endTime

        previousStart = mc.playbackOptions(q=True, min=True)
        previousEnd = mc.playbackOptions(q=True, max=True)
        previousCurrent = mc.currentTime(q=True)

        log.info('Baking from {0} to {1}'.format(self.startTime, self.endTime))

        mc.currentTime(self.startTime)

        self.preBake()

        self.setAim(aimFwd=self.aimFwd, aimUp=self.aimUp)

        fps = mel.eval('currentTimeUnitToFPS')

        fixedDeltaTime = 1.0 / fps

        self.velocity = MATH.Vector3.zero()

        ak = mc.autoKeyframe(q=True, state=True)
        mc.autoKeyframe(state=False)
        mc.refresh(su=not self.showBake)

        _len = self.endTime - self.startTime
        _progressBar = cgmUI.doStartMayaProgressBar(_len, "Processing...")

        completed = True

        if self._cancelBake:
            mc.refresh(su=False)
            mc.autoKeyframe(state=ak)
            return

        for i in range(self.startTime, self.endTime + 1):
            mc.currentTime(i)

            try:
                self.update(fixedDeltaTime)
            except Exception, err:
                mc.refresh(su=False)
                mc.autoKeyframe(state=ak)
                log.warning('Error on update | {0}'.format(err))
                cgmGEN.cgmException(Exception, err)
                return

            mc.setKeyframe(self.obj.mNode, at=self.keyableAttrs)
            self.velocity = MATH.Vector3.Lerp(
                self.velocity,
                VALID.euclidVector3Arg(self.obj.p_position) -
                self.previousPosition,
                min(fixedDeltaTime * self.velocityDamp, 1.0))
            self.previousPosition = VALID.euclidVector3Arg(self.obj.p_position)

            if _progressBar:
                if mc.progressBar(_progressBar, query=True, isCancelled=True):
                    log.warning('Bake cancelled!')
                    completed = False
                    break

                mc.progressBar(_progressBar,
                               edit=True,
                               status=("{0} On frame {1}".format(_str_func,
                                                                 i)),
                               step=1,
                               maxValue=_len)
Example #21
0
            #if closestInRange:
            #hit = d_castReturn.get('near') or False
            #else:
            #hit = d_castReturn.get('far') or False
            #if not hit:log.info("{0} -- {1}".format(rotateValue,d_castReturn))
                l_hits.append(hit)
                d_processedHitFromValue[rotateValue] = hit
                l_pos.append(hit)
                if markHits:
                    LOC.create(position=hit,
                               name="cast_rot{0}_loc".format(rotateValue))

                d_rawHitFromValue[rotateValue] = hit

            except Exception, err:
                cgmGEN.cgmException(Exception, err)

        mc.delete(mi_loc.getParents()[-1])  #delete top group
        log.debug("pos list: %s" % l_pos)
        #guiFactory.doCloseProgressWindow()

    except Exception, error:
        pprint.pprint(vars())
        raise ValueError, "Cast fail | {0}".format(error)
    try:
        if not l_pos:
            log.warning("Cast return: %s" % d_castReturn)
            raise StandardError, "createMeshSliceCurve>> Not hits found. Nothing to do"
        if len(l_pos) >= 3:
            if closedCurve:
                l_pos.extend(l_pos[:curveDegree])
Example #22
0
def createMRSRig(folderPath):
    cgm.core._  #reload()

    fileList = mc.getFileList(folder=folderPath)

    if not folderPath.endswith('\\'):
        folderPath = folderPath + '\\'

    if not 'MRSRigs' in mc.getFileList(folder=folderPath):
        mc.sysFile(folderPath + 'MRSRigs', md=1)
        newFolderPath = folderPath + 'MRSRigs\\'

    for _file in fileList:
        try:
            if (_file.endswith('.ma')):

                mc.file(folderPath + _file, open=1, f=1)

                log.info("Working on... " + _file)

                ml_masters = r9Meta.getMetaNodes(
                    mTypes='cgmRigBlock',
                    nTypes=['transform', 'network'],
                    mAttrs='blockType=master')

                for mBlock in ml_masters:

                    log.info(mBlock)

                    RIGBLOCKS.contextual_rigBlock_method_call(mBlock,
                                                              'below',
                                                              'atUtils',
                                                              'changeState',
                                                              'rig',
                                                              forceNew=False)
                    mBlock.moduleTarget  #<< link to puppet
                    '''
                    This is the start of the puppet calls

                    '''

                    #If more than one Rig exists Do:
                    #if len(ml_masters):raise ValueError,"Too many masters: {0}".format(ml_masters)

                    #rig call if you prefer as a for loop: build rig, check rig
                    ml_context = BLOCKGEN.get_rigBlock_heirarchy_context(
                        mBlock, 'below', True, False)
                    pprint.pprint(ml_context)

                    log.info('Begin Rig Build')

                    ml_context = BLOCKGEN.get_rigBlock_heirarchy_context(
                        mBlock, 'below', True, False)
                    l_fails = []

                    for mSubBlock in ml_context:
                        _state = mSubBlock.getState(False)
                        if _state != 4:
                            l_fails.append(mSubBlock)
                    if l_fails:
                        log.info('The following failed...')
                        pprint.pprint(l_fails)
                        raise ValueError, "Modules failed to rig: {0}".format(
                            l_fails)

                    log.info("Begin Rig Prep cleanup...")
                    '''

                    Begin Rig Prep process

                    '''

                    mPuppet = mBlock.moduleTarget  #...when mBlock is your masterBlock

                    log.info('mirror_verify...')
                    mPuppet.atUtils('mirror_verify')
                    log.info('collect worldSpace...')
                    mPuppet.atUtils('collect_worldSpaceObjects')
                    log.info('qss...')
                    mPuppet.atUtils('qss_verify',
                                    puppetSet=1,
                                    bakeSet=1,
                                    deleteSet=1,
                                    exportSet=1)
                    log.info('proxyMesh...')
                    mPuppet.atUtils('proxyMesh_verify')
                    log.info('ihi...')
                    mPuppet.atUtils('rigNodes_setAttr', 'ihi', 0)
                    log.info('rig connect...')
                    mPuppet.atUtils('rig_connectAll')

                #Save the scene in the new folder.

                log.info("Saving out the new scene...")

                newFile = mc.file(rename=newFolderPath +
                                  _file.split('_template')[0] + "_rig.ma")
                mc.file(save=1, type='mayaAscii')

                log.info("Saved new scene " + newFile)

            else:
                log.info("There was an error creating new file...")
        except Exception, err:
            log.error("File failed: {0}".format(_file))
            cgmGEN.cgmException(Exception, err)