コード例 #1
0
ファイル: joint_utils.py プロジェクト: sgodanas/cgm_tools
def orientChain(joints = None, axisAim = 'z+', axisUp = 'y+',
                worldUpAxis = [0,1,0], relativeOrient = True,
                progressBar = None,
                baseName = None, asMeta = True):
                
    """
    Given a series of positions, or objects, or a curve and a mesh - loft retopology it

    :parameters:


    :returns
        created(list)
    """    
    _str_func = 'orientChain'
    if baseName:raise NotImplementedError,"Remove these calls"
    
    def orientJoint(mJnt):
        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
            
            if relativeOrient and mParent:
                _axisWorldUp = MATH.get_obj_vector(mParent.mNode, axisUp)            
            else:
                _axisWorldUp = worldUpAxis
    
            SNAP.aim(mDup.mNode,_d_children[mJnt][0].mNode,
                     mAxis_aim.p_vector,mAxis_up.p_vector,
                     'vector',_axisWorldUp)
            
            mJnt.rotate = 0,0,0
            mJnt.jointOrient = mDup.rotate
            mDup.delete()
コード例 #2
0
ファイル: snap_calls.py プロジェクト: sgodanas/cgm_tools
def snap_action(objects=None,
                snapMode='point',
                selectionMode='eachToLast',
                **kws):
    """
    """
    try:
        _str_func = 'snap_action'
        subKWS = {}
        if objects is None:
            objects = mc.ls(sl=True)

        if snapMode == 'aim':
            aim_axis = SHARED._l_axis_by_string[var_objDefaultAimAxis.value]
            up_axis = SHARED._l_axis_by_string[var_objDefaultUpAxis.value]

            subKWS = {
                'aimAxis': aim_axis,
                'upAxis': up_axis,
                'mode': var_aimMode.value
            }

            if selectionMode == 'firstToRest':
                MMCONTEXT.func_process(SNAP.aim_atMidPoint, objects,
                                       selectionMode, 'Snap aim', **subKWS)
            else:
                MMCONTEXT.func_process(SNAP.aim, objects, selectionMode,
                                       'Snap aim', **subKWS)

            if selectionMode == 'eachToNext':
                SNAP.aim(objects[-1], objects[-2],
                         VALID.simpleAxis(aim_axis).inverse.p_string, up_axis,
                         var_aimMode.value)

        elif snapMode == 'ground':
            MMCONTEXT.func_process(SNAP.to_ground, objects, 'each', 'Snap')

        elif snapMode in [
                'axisBox', 'boundingBox', 'boundingBoxShapes',
                'boundingBoxEach', 'castCenter', 'castFar', 'castNear',
                'castAllCenter', 'castAllFar', 'castAllNear'
        ]:
            log.debug("|{0}| | special mode: {1}".format(_str_func, snapMode))
            subKWS['mode'] = kws.get('mode', 'z+')
            subKWS['arg'] = snapMode

            if len(objects) == 1:
                specialSnap(objects[0], **subKWS)
            elif snapMode in ['boundingBox'] and selectionMode != 'each':
                log.debug("|{0}| | bb each mode".format(_str_func, snapMode))
                specialSnap(objects[0], objects, **subKWS)
            else:
                MMCONTEXT.func_process(specialSnap, objects, selectionMode,
                                       'Snap Special', **subKWS)

        else:
            subKWS = {
                'position': False,
                'rotation': False,
                'rotateAxis': False,
                'rotateOrder': False,
                'scalePivot': False,
                'pivot': 'rp',
                'space': 'w',
                'mode': 'xform'
            }

            if snapMode in ['point', 'closestPoint']:
                subKWS['position'] = True
            elif snapMode == 'orient':
                subKWS['rotation'] = True
            elif snapMode == 'parent':
                subKWS['position'] = True
                subKWS['rotation'] = True
            elif snapMode == 'aim':
                subKWS['rotation'] = True
            else:
                raise ValueError, "Unknown mode!"

            _pivotMode = var_snapPivotMode.value

            if snapMode == 'closestPoint':
                subKWS['pivot'] = 'closestPoint'
            else:
                if not _pivotMode: pass  #0 handled by default
                elif _pivotMode == 1:
                    subKWS['pivot'] = 'sp'
                elif _pivotMode == 2:
                    subKWS['pivot'] = 'boundingBox'
                else:
                    raise ValueError, "Uknown pivotMode: {0}".format(
                        _pivotMode)

            MMCONTEXT.func_process(SNAP.go, objects, selectionMode, 'Snap',
                                   **subKWS)

        mc.select(objects)
        return
    except Exception, err:
        cgmGEN.cgmExceptCB(Exception, err, msg=vars())
コード例 #3
0
ファイル: shapeCaster.py プロジェクト: liudger/cgmTools
def createWrapControlShape(
        targetObjects,
        targetGeo=None,
        latheAxis='z',
        aimAxis='y+',
        objectUp='y+',
        points=8,
        curveDegree=1,
        insetMult=None,  #Inset multiplier
        minRotate=None,
        maxRotate=None,
        posOffset=[],
        rootOffset=[],  #offset root before cast
        rootRotate=None,
        joinMode=False,
        extendMode=None,
        closedCurve=True,
        l_specifiedRotates=None,
        maxDistance=1000,
        closestInRange=True,
        vectorOffset=None,
        midMeshCast=False,
        subSize=None,  #For ball on loli for example
        rotateBank=None,
        joinHits=None,  #keys to processed hits to see what to join
        axisToCheck=['x', 'y'],
        **kws):  #'segment,radial,disc'
    """
    This function lathes an axis of an object, shoot rays out the aim axis at the provided mesh and returning hits. 
    it then uses this information to build a curve shape.

    :parameters:
        mesh(string) | Surface to cast at
    mi_obj(string/mObj) | our casting object
    latheAxis(str) | axis of the objec to lathe TODO: add validation
    aimAxis(str) | axis to shoot out of
    points(int) | how many points you want in the curve
    curveDegree(int) | specified degree
    minRotate(float) | let's you specify a valid range to shoot
    maxRotate(float) | let's you specify a valid range to shoot
    posOffset(vector) | transformational offset for the hit from a normalized locator at the hit. Oriented to the surface
    markHits(bool) | whether to keep the hit markers
    returnDict(bool) | whether you want all the infomation from the process.
    rotateBank (float) | let's you add a bank to the rotation object
    l_specifiedRotates(list of values) | specify where to shoot relative to an object. Ignores some other settings
    maxDistance(float) | max distance to cast rays
    closestInRange(bool) | True by default. If True, takes first hit. Else take the furthest away hit in range.

    :returns:
        Dict ------------------------------------------------------------------
    'source'(double3) |  point from which we cast
    'hit'(double3) | world space points | active during single return
    'hits'(list) | world space points | active during multi return
    'uv'(double2) | uv on surface of hit | only works for mesh surfaces

    :raises:
    Exception | if reached

    """
    _str_func = "createWrapControlShape"
    log.debug(">> %s >> " % (_str_func) + "=" * 75)
    _joinModes = []
    _extendMode = []

    if type(targetObjects) not in [list, tuple]:
        targetObjects = [targetObjects]
    targetGeo = VALID.objStringList(targetGeo, calledFrom=_str_func)

    assert type(points) is int, "Points must be int: %s" % points
    assert type(curveDegree) is int, "Points must be int: %s" % points
    assert curveDegree > 0, "Curve degree must be greater than 1: %s" % curveDegree
    if posOffset is not None and len(posOffset) and len(posOffset) != 3:
        raise StandardError, "posOffset must be len(3): %s | len: %s" % (
            posOffset, len(posOffset))
    if rootOffset is not None and len(rootOffset) and len(rootOffset) != 3:
        raise StandardError, "rootOffset must be len(3): %s | len: %s" % (
            rootOffset, len(rootOffset))
    if rootRotate is not None and len(rootRotate) and len(rootRotate) != 3:
        raise StandardError, "rootRotate must be len(3): %s | len: %s" % (
            rootRotate, len(rootRotate))

    if extendMode in ['loliwrap', 'cylinder', 'disc'] and insetMult is None:
        insetMult = 1
    for axis in ['x', 'y', 'z']:
        if axis in latheAxis.lower(): latheAxis = axis

    log.debug("targetObjects: %s" % targetObjects)

    if len(aimAxis) == 2: single_aimAxis = aimAxis[0]
    else: single_aimAxis = aimAxis
    mAxis_aim = VALID.simpleAxis(aimAxis)
    log.debug("Single aim: %s" % single_aimAxis)
    log.debug("createWrapControlShape>> midMeshCast: %s" % midMeshCast)
    log.debug("|{0}| >> extendMode: {1}".format(_str_func, extendMode))
    #>> Info
    l_groupsBuffer = []
    il_curvesToCombine = []
    l_sliceReturns = []
    #Need to do more to get a better size

    #>> Build curves
    #=================================================================
    #> Root curve #
    log.debug("RootRotate: %s" % rootRotate)
    mi_rootLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc()
    if rootOffset:
        log.debug("rootOffset: %s" % rootOffset)
        mc.move(rootOffset[0],
                rootOffset[1],
                rootOffset[2], [mi_rootLoc.mNode],
                r=True,
                rpr=True,
                os=True,
                wd=True)
    if rootRotate is not None and len(rootRotate):
        log.debug("rootRotate: %s" % rootRotate)
        mc.rotate(rootRotate[0],
                  rootRotate[1],
                  rootRotate[2], [mi_rootLoc.mNode],
                  os=True,
                  r=True)

    #>> Root
    mi_rootLoc.doGroup()  #Group to zero
    if extendMode == 'segment':
        log.debug("segment mode. Target len: %s" % len(targetObjects[1:]))
        if len(targetObjects) < 2:
            log.warning(
                "Segment build mode only works with two objects or more")
        else:
            if insetMult is not None:
                rootDistanceToMove = distance.returnDistanceBetweenObjects(
                    targetObjects[0], targetObjects[1])
                log.debug("rootDistanceToMove: %s" % rootDistanceToMove)
                mi_rootLoc.__setattr__('t%s' % latheAxis,
                                       rootDistanceToMove * insetMult)
                #mi_rootLoc.tz = (rootDistanceToMove*insetMult)#Offset it

            #Notes -- may need to play with up object for aim snapping
            #mi_upLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc()
            #mi_upLoc.doGroup()#To zero
            objectUpVector = dictionary.returnStringToVectors(objectUp)
            log.debug("objectUpVector: %s" % objectUpVector)
            #mi_uploc

            for i, obj in enumerate(targetObjects[1:]):
                log.debug("i: %s" % i)
                #> End Curve
                mi_endLoc = cgmMeta.cgmNode(obj).doLoc()
                aimVector = dictionary.returnStringToVectors(latheAxis + '-')
                log.debug("segment aimback: %s" % aimVector)
                #Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,aim=True,aimVector=aimVector,upVector=objectUpVector)
                #Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,orient=True)
                SNAP.go(mi_endLoc.mNode,
                        mi_rootLoc.mNode,
                        position=False,
                        rotation=True)

                mi_endLoc.doGroup()

                if i == len(targetObjects[1:]) - 1:
                    if insetMult is not None:
                        log.debug("segment insetMult: %s" % insetMult)
                        distanceToMove = distance.returnDistanceBetweenObjects(
                            targetObjects[-1], targetObjects[0])
                        log.debug("distanceToMove: %s" % distanceToMove)
                        #mi_endLoc.tz = -(distanceToMove*insetMult)#Offset it
                        mi_endLoc.__setattr__('t%s' % latheAxis,
                                              -(distanceToMove * insetMult))
                log.debug("segment lathe: %s" % latheAxis)
                log.debug("segment aim: %s" % aimAxis)
                log.debug("segment rotateBank: %s" % rotateBank)
                d_endCastInfo = createMeshSliceCurve(
                    targetGeo,
                    mi_endLoc,
                    midMeshCast=midMeshCast,
                    curveDegree=curveDegree,
                    latheAxis=latheAxis,
                    aimAxis=aimAxis,
                    posOffset=posOffset,
                    points=points,
                    returnDict=True,
                    closedCurve=closedCurve,
                    maxDistance=maxDistance,
                    closestInRange=closestInRange,
                    rotateBank=rotateBank,
                    l_specifiedRotates=l_specifiedRotates,
                    axisToCheck=axisToCheck)
                l_sliceReturns.append(d_endCastInfo)
                mi_end = cgmMeta.cgmObject(d_endCastInfo['curve'])
                il_curvesToCombine.append(mi_end)
                mc.delete(mi_endLoc.parent)  #delete the loc

    elif extendMode == 'radial':
        log.debug("|{0}| >> radial...".format(_str_func))
        d_handleInner = createMeshSliceCurve(
            targetGeo,
            mi_rootLoc,
            midMeshCast=midMeshCast,
            curveDegree=curveDegree,
            latheAxis=latheAxis,
            aimAxis=aimAxis,
            posOffset=0,
            points=points,
            returnDict=True,
            closedCurve=closedCurve,
            maxDistance=maxDistance,
            closestInRange=closestInRange,
            rotateBank=rotateBank,
            l_specifiedRotates=l_specifiedRotates,
            axisToCheck=axisToCheck)
        mi_buffer = cgmMeta.cgmObject(d_handleInner['curve'])  #instance curve
        l_sliceReturns.append(d_handleInner)
        il_curvesToCombine.append(mi_buffer)

    elif extendMode == 'disc':
        log.debug("|{0}| >> disc...".format(_str_func))
        d_size = returnBaseControlSize(mi_rootLoc, targetGeo,
                                       axis=[aimAxis])  #Get size
        #discOffset = d_size[ d_size.keys()[0]]*insetMult
        size = False
        l_absSize = [abs(i) for i in posOffset]
        if l_absSize: size = max(l_absSize)
        if not size:
            d_size = returnBaseControlSize(mi_rootLoc,
                                           targetGeo,
                                           axis=[aimAxis])  #Get size
            log.debug("d_size: %s" % d_size)
            size = d_size[d_size.keys()[0]] * insetMult

        discOffset = size
        log.debug("d_size: %s" % d_size)
        log.debug("discOffset is: %s" % discOffset)

        mi_rootLoc.__setattr__('t%s' % latheAxis, discOffset)
        if posOffset:
            tmp_posOffset = [
                posOffset[0] * .5, posOffset[1] * .5, posOffset[2] * .5
            ]
        d_handleInnerUp = createMeshSliceCurve(
            targetGeo,
            mi_rootLoc,
            curveDegree=curveDegree,
            midMeshCast=midMeshCast,
            latheAxis=latheAxis,
            aimAxis=aimAxis,
            posOffset=tmp_posOffset,
            points=points,
            returnDict=True,
            closedCurve=closedCurve,
            maxDistance=maxDistance,
            closestInRange=closestInRange,
            rotateBank=rotateBank,
            l_specifiedRotates=l_specifiedRotates,
            axisToCheck=axisToCheck)
        mi_buffer = cgmMeta.cgmObject(
            d_handleInnerUp['curve'])  #instance curve
        l_sliceReturns.append(d_handleInnerUp)
        il_curvesToCombine.append(mi_buffer)

        mi_rootLoc.__setattr__('t%s' % latheAxis, -discOffset)
        d_handleInnerDown = createMeshSliceCurve(
            targetGeo,
            mi_rootLoc,
            curveDegree=curveDegree,
            midMeshCast=midMeshCast,
            latheAxis=latheAxis,
            aimAxis=aimAxis,
            posOffset=tmp_posOffset,
            points=points,
            returnDict=True,
            closedCurve=closedCurve,
            maxDistance=maxDistance,
            closestInRange=closestInRange,
            rotateBank=rotateBank,
            l_specifiedRotates=l_specifiedRotates,
            axisToCheck=axisToCheck)
        mi_buffer = cgmMeta.cgmObject(
            d_handleInnerDown['curve'])  #instance curve
        l_sliceReturns.append(d_handleInnerDown)
        il_curvesToCombine.append(mi_buffer)

        mi_rootLoc.tz = 0

    elif extendMode == 'cylinder':
        log.debug("|{0}| >> cylinder...".format(_str_func))
        d_size = returnBaseControlSize(mi_rootLoc, targetGeo,
                                       axis=[aimAxis])  #Get size
        discOffset = d_size[d_size.keys()[0]] * insetMult
        log.debug("d_size: %s" % d_size)
        log.debug("discOffset is: %s" % discOffset)

        mi_rootLoc.__setattr__('t%s' % latheAxis, discOffset)
        d_handleInnerUp = createMeshSliceCurve(
            targetGeo,
            mi_rootLoc,
            curveDegree=curveDegree,
            midMeshCast=midMeshCast,
            latheAxis=latheAxis,
            aimAxis=aimAxis,
            posOffset=posOffset,
            points=points,
            returnDict=True,
            closedCurve=closedCurve,
            maxDistance=maxDistance,
            closestInRange=closestInRange,
            rotateBank=rotateBank,
            l_specifiedRotates=l_specifiedRotates,
            axisToCheck=axisToCheck)
        mi_buffer = cgmMeta.cgmObject(
            d_handleInnerUp['curve'])  #instance curve
        l_sliceReturns.append(d_handleInnerUp)
        il_curvesToCombine.append(mi_buffer)

        mi_rootLoc.__setattr__('t%s' % latheAxis, 0)

    elif extendMode == 'loliwrap':
        log.debug("|{0}| >> lolipop...".format(_str_func))
        #l_absSize = [abs(i) for i in posOffset]
        size = False
        #if l_absSize:
        #log.debug("l_absSize: %s"%l_absSize)
        #size = max(l_absSize)*1.25
        if subSize is not None:
            size = subSize
        if not size:
            d_size = returnBaseControlSize(mi_rootLoc,
                                           targetGeo,
                                           axis=[aimAxis])  #Get size
            log.info("d_size: %s" % d_size)
            l_size = d_size[single_aimAxis]
            size = l_size / 3
        log.info("loli size: %s" % size)
        i_ball = cgmMeta.cgmObject(
            curves.createControlCurve('sphere', size=size))

    elif extendMode == 'endCap':
        log.debug("|{0}| >> endCap...".format(_str_func))
        returnBuffer1 = createMeshSliceCurve(
            targetGeo,
            mi_rootLoc.mNode,
            aimAxis='{0}+'.format(latheAxis),
            latheAxis=objectUp[0],
            curveDegree=curveDegree,
            maxDistance=maxDistance,
            closestInRange=closestInRange,
            closedCurve=False,
            l_specifiedRotates=[-90, -60, -30, 0, 30, 60, 90],
            posOffset=posOffset)
        mi_rootLoc.rotate = [0, 0, 0]
        mi_rootLoc.__setattr__('r%s' % latheAxis, 90)
        returnBuffer2 = createMeshSliceCurve(
            targetGeo,
            mi_rootLoc.mNode,
            aimAxis='{0}+'.format(latheAxis),
            latheAxis=objectUp[0],
            curveDegree=curveDegree,
            maxDistance=maxDistance,
            closedCurve=False,
            closestInRange=closestInRange,
            l_specifiedRotates=[-90, -60, -30, 0, 30, 60, 90],
            posOffset=posOffset)
        l_sliceReturns.extend([returnBuffer1, returnBuffer2])
        il_curvesToCombine.append(cgmMeta.cgmObject(returnBuffer1))
        il_curvesToCombine.append(cgmMeta.cgmObject(returnBuffer2))
        mi_rootLoc.rotate = [0, 0, 0]

    #Now cast our root since we needed to move it with segment mode before casting
    if extendMode == 'cylinder':
        log.debug("|{0}| >> cylinder move...".format(_str_func))
        mi_rootLoc.__setattr__('t%s' % latheAxis, -discOffset)

    log.debug("|{0}| >> Rootcast...".format(_str_func))

    d_rootCastInfo = createMeshSliceCurve(
        targetGeo,
        mi_rootLoc,
        curveDegree=curveDegree,
        minRotate=minRotate,
        maxRotate=maxRotate,
        latheAxis=latheAxis,
        midMeshCast=midMeshCast,
        aimAxis=aimAxis,
        posOffset=posOffset,
        points=points,
        vectorOffset=vectorOffset,
        returnDict=True,
        closedCurve=closedCurve,
        maxDistance=maxDistance,
        closestInRange=closestInRange,
        rotateBank=rotateBank,
        l_specifiedRotates=l_specifiedRotates,
        axisToCheck=axisToCheck)
    #d_rootCastInfo = createMeshSliceCurve(targetGeo,mi_rootLoc,**kws)
    log.debug("|{0}| >> Rootcast done".format(_str_func) + cgmGEN._str_subLine)

    if extendMode == 'disc':
        l_sliceReturns.insert(1, d_rootCastInfo)
    else:
        l_sliceReturns.insert(0, d_rootCastInfo)

    #Special loli stuff
    if extendMode == 'loliwrap':
        SNAP.go(i_ball.mNode, mi_rootLoc.mNode, True,
                True)  #Snap to main object

        #log.debug("hitReturns: %s"%d_rootCastInfo['hitReturns'])
        #cgmGEN.walk_dat(d_rootCastInfo['hitReturns'],'hitReturns')

        mi_crv = cgmMeta.cgmObject(d_rootCastInfo['curve'])
        """
        d_return = RayCast.findMeshIntersectionFromObjectAxis(targetGeo,mi_rootLoc.mNode,mAxis_aim.p_string) or {}
        if not d_return.get('hit'):
            log.info(d_return)
            raise ValueError,"No hit on loli check"
        pos = d_return.get('hit')
        dist = distance.returnDistanceBetweenPoints(i_ball.getPosition(),pos) * 2"""

        if vectorOffset is not None:
            dist = vectorOffset + subSize * 4
        else:
            dist = max(posOffset) + subSize * 4

        if '-' in aimAxis:
            distM = -dist
        else:
            distM = dist
        log.debug("distM: %s" % distM)

        #Move the ball
        pBuffer = i_ball.doGroup()
        i_ball.__setattr__('t%s' % single_aimAxis, distM)
        i_ball.parent = False
        mc.delete(pBuffer)

        uPos = distance.returnClosestUPosition(i_ball.mNode, mi_crv.mNode)

        SNAP.aim(i_ball.mNode, mi_rootLoc.mNode, aimAxis='z-')
        #if posOffset:
        #mc.move(posOffset[0]*3,posOffset[1]*3,posOffset[2]*3, [i_ball.mNode], r = True, rpr = True, os = True, wd = True)
        #Make the curve between the two
        mi_traceCrv = cgmMeta.cgmObject(
            mc.curve(degree=1, ep=[uPos, i_ball.getPosition()]))

        #Combine
        il_curvesToCombine.extend([i_ball, mi_traceCrv])

    mi_root = cgmMeta.cgmObject(d_rootCastInfo['curve'])  #instance curve
    il_curvesToCombine.append(mi_root)

    mc.delete(mi_rootLoc.parent)  #delete the loc

    l_curvesToCombine = [mi_obj.mNode for mi_obj in il_curvesToCombine
                         ]  #Build our combine list before adding connectors
    log.debug("|{0}| >> processed: {1}".format(
        _str_func, d_rootCastInfo['processedHits']))

    if joinMode and extendMode not in ['loliwrap', 'endCap'
                                       ] and len(l_sliceReturns) > 1:
        if joinHits:
            keys = d_rootCastInfo['processedHits'].keys()
            keys.sort()
            #goodDegrees = []
            #for i,key in enumerate(keys):
            #if i in joinHits:
            #goodDegrees.append(key)
            goodDegrees = [key for i, key in enumerate(keys) if i in joinHits]
            log.debug("joinHits: %s" % joinHits)
            log.debug("goodDegrees: %s" % goodDegrees)
        else:
            goodDegrees = [
                key for key in d_rootCastInfo['processedHits'].keys()
            ]
        #> Side Curves
        for degree in goodDegrees:
            l_pos = []
            for d in l_sliceReturns:
                l_pos.append(d['processedHits'].get(degree) or False)
            while False in l_pos:
                l_pos.remove(False)
            log.debug("l_pos: %s" % l_pos)
            if len(l_pos) >= 2:
                try:
                    l_curvesToCombine.append(
                        mc.curve(d=curveDegree, ep=l_pos,
                                 os=True))  #Make the curve
                except:
                    log.debug(
                        "createWrapControlShape>>> skipping curve fail: %s" %
                        (degree))

    #>>Combine the curves
    newCurve = curves.combineCurves(l_curvesToCombine)
    mi_crv = cgmMeta.cgmObject(rigging.groupMeObject(targetObjects[0], False))
    curves.parentShapeInPlace(mi_crv.mNode, newCurve)  #Parent shape
    mc.delete(newCurve)

    #>>Copy tags and name
    mi_crv.doCopyNameTagsFromObject(targetObjects[0],
                                    ignore=['cgmType', 'cgmTypeModifier'])
    mi_crv.addAttr('cgmType',
                   attrType='string',
                   value='controlCurve',
                   lock=True)
    mi_crv.doName()

    #Store for return
    return {'curve': mi_crv.mNode, 'instance': mi_crv}
コード例 #4
0
ファイル: joint_utils.py プロジェクト: liudger/cgmTools
        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()