Example #1
0
def doParentConstraintObjectGroup(targets, obj, mode=0):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list)
    object(string
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objGroup = rigging.groupMeObject(obj, True, True)
    constraint = mc.parentConstraint(targets, objGroup, maintainOffset=True)
    if mode == 1:
        weights = returnNormalizedWeightsByDistance(obj, targets)
        targetWeights = mc.parentConstraint(constraint,
                                            q=True,
                                            weightAliasList=True)
        for cnt, value in enumerate(weights):
            mc.setAttr(('%s%s%s' % (constraint[0], '.', targetWeights[cnt])),
                       value)
    return objGroup
Example #2
0
def doPointConstraintObjectGroup(targets, object, mode=0):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list)
    object(string
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objGroup = rigging.groupMeObject(object, True, True)
    constraint = mc.pointConstraint(targets, objGroup, maintainOffset=True)
    if mode == 1:
        distances = []
        for target in targets:
            distances.append(
                distance.returnDistanceBetweenObjects(target, objGroup))
        normalizedDistances = cgmMath.normList(distances)
        targetWeights = mc.pointConstraint(constraint,
                                           q=True,
                                           weightAliasList=True)

        cnt = 1
        for value in normalizedDistances:
            mc.setAttr(('%s%s%s' % (constraint[0], '.', targetWeights[cnt])),
                       value)
            cnt -= 1
    return objGroup
Example #3
0
def doPointConstraintObjectGroup(targets,object,mode=0): 
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list)
    object(string
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """    
    objGroup = rigging.groupMeObject(object,True,True)
    constraint = mc.pointConstraint (targets,objGroup, maintainOffset=True)
    if mode == 1:
        distances = []
        for target in targets:
            distances.append(distance.returnDistanceBetweenObjects(target,objGroup))
        normalizedDistances = cgmMath.normList(distances)
        targetWeights = mc.pointConstraint(constraint,q=True, weightAliasList=True)
        
        cnt=1
        for value in normalizedDistances:
            mc.setAttr(('%s%s%s' % (constraint[0],'.',targetWeights[cnt])),value )
            cnt-=1
    return objGroup
    def finalize(self):
        """
        Press action. Clears buffers.
        """
        #Clean our lists...
        self.l_created = lists.returnListNoDuplicates(self.l_created)
        self.l_return = lists.returnListNoDuplicates(self.l_return)

        if self._createMode in ['curve','jointChain','group','follicle'] and self.l_return:
            if self._createMode == 'group':
                bufferList = []
                for i,o in enumerate(self.l_created):
                    buffer = rigging.groupMeObject(o,False)
                    bufferList.append(buffer)                    
                    try:mc.delete(o)
                    except:pass
                self.l_created = bufferList

            elif self._createMode =='follicle':
                if self.mode == 'midPoint':
                    log.warning("Mid point mode doesn't work with follicles")
                    return
                bufferList = []
                for o in self.l_created:
                    mesh = attributes.doGetAttr(o,'cgmHitTarget')
                    if mc.objExists(mesh):
                        uv = distance.returnClosestUVToPos(mesh,distance.returnWorldSpacePosition(o))
                        log.info("uv: {0}".format(uv))
                        follicle = nodes.createFollicleOnMesh(mesh)
                        log.info("follicle: {0}".format(follicle))                        
                        attributes.doSetAttr(follicle[0],'parameterU',uv[0])
                        attributes.doSetAttr(follicle[0],'parameterV',uv[1])
                        try:mc.delete(o)
                        except:pass                        
            else:
                for o in self.l_created:
                    try:mc.delete(o)
                    except:pass
                if self._createMode == 'curve' and len(self.l_return)>1:
                    if len(self.l_return) > 1:
                        self.l_created = [curves.curveFromPosList(self.l_return)]
                    else:
                        log.warning("Need at least 2 points for a curve")                        
                elif self._createMode == 'jointChain':
                    self.l_created = []
                    mc.select(cl=True)
                    for pos in self.l_return:                             
                        self.l_created.append( mc.joint (p = (pos[0], pos[1], pos[2]),radius = 1) ) 
        log.debug( self.l_created)

        if self.d_tagAndName:
            for o in self.l_created:
                try:
                    i_o = cgmMeta.cgmNode(o)
                    for tag in self.d_tagAndName.keys():
                        i_o.doStore(tag,self.d_tagAndName[tag])
                    i_o.doName()
                except StandardError,error:
                    log.error(">>> clickMesh >> Failed to tag and name: %s | error: %s"%(i_o.p_nameShort,error))            	            		
Example #5
0
    def doGroup(self,maintain=False):
        """
        Grouping function for a maya instanced object.

        Keyword arguments:
        maintain(bool) -- whether to parent the maya object in place or not (default False)

        """
        assert mc.ls(self.nameLong,type='transform'),"'%s' has no transform"%self.nameLong	

        group = rigging.groupMeObject(self.nameLong,True,maintain) 
        groupLong = mc.ls(group,long=True)
        self.update(groupLong[0]+'|'+self.nameBase)  
        return groupLong[0]
    def finalize(self):
        """
        Press action. Clears buffers.
        """
        #Clean our lists...
        self.createdList = lists.returnListNoDuplicates(self.createdList)
        self.returnList = lists.returnListNoDuplicates(self.returnList)
        
        if self.createMode in ['curve','jointChain','group','follicle'] and self.returnList:
            if self.createMode == 'group':
                bufferList = []
                for i,o in enumerate(self.createdList):
                    buffer = rigging.groupMeObject(o,False)
                    bufferList.append(buffer)                    
                    try:mc.delete(o)
                    except:pass
                self.createdList = bufferList
                
            elif self.createMode =='follicle':
                if self.mode == 'midPoint':
                    guiFactory.warning("Mid point mode doesn't work with follicles")
                    return
                bufferList = []
                for o in self.createdList:
                    mesh = attributes.doGetAttr(o,'cgmHitTarget')
                    if mc.objExists(mesh):
                        uv = distance.returnClosestUVToPos(mesh,distance.returnWorldSpacePosition(o))
                        follicle = nodes.createFollicleOnMesh(mesh)
                        attributes.doSetAttr(follicle[0],'parameterU',uv[0])
                        attributes.doSetAttr(follicle[0],'parameterV',uv[1])
                        try:mc.delete(o)
                        except:pass                        
            else:
                for o in self.createdList:
                    try:mc.delete(o)
                    except:pass
                if self.createMode == 'curve' and len(self.returnList)>1:
                    if len(self.returnList) > 1:
                        self.createdList = [curves.curveFromPosList(self.returnList)]
                    else:
                        guiFactory.warning("Need at least 2 points for a curve")                        
                elif self.createMode == 'jointChain':
                    self.createdList = []
                    mc.select(cl=True)
                    for pos in self.returnList:                             
                        self.createdList.append( mc.joint (p = (pos[0], pos[1], pos[2]),radius = 1) )
                                

        self.reset()
    def finalize(self):
        """
        Press action. Clears buffers.
        """
        #Clean our lists...
        self.createdList = lists.returnListNoDuplicates(self.createdList)
        self.returnList = lists.returnListNoDuplicates(self.returnList)
        
        if self.createMode in ['curve','jointChain','group','follicle'] and self.returnList:
            if self.createMode == 'group':
                bufferList = []
                for i,o in enumerate(self.createdList):
                    buffer = rigging.groupMeObject(o,False)
                    bufferList.append(buffer)                    
                    try:mc.delete(o)
                    except:pass
                self.createdList = bufferList
                
            elif self.createMode =='follicle':
                if self.mode == 'midPoint':
                    guiFactory.warning("Mid point mode doesn't work with follicles")
                    return
                bufferList = []
                for o in self.createdList:
                    mesh = attributes.doGetAttr(o,'cgmHitTarget')
                    if mc.objExists(mesh):
                        uv = distance.returnClosestUVToPos(mesh,distance.returnWorldSpacePosition(o))
                        follicle = nodes.createFollicleOnMesh(mesh)
                        attributes.doSetAttr(follicle[0],'parameterU',uv[0])
                        attributes.doSetAttr(follicle[0],'parameterV',uv[1])
                        try:mc.delete(o)
                        except:pass                        
            else:
                for o in self.createdList:
                    try:mc.delete(o)
                    except:pass
                if self.createMode == 'curve' and len(self.returnList)>1:
                    if len(self.returnList) > 1:
                        self.createdList = [mc.curve (d=3, p = self.returnList , ws=True)]
                    else:
                        guiFactory.warning("Need at least 2 points for a curve")                        
                elif self.createMode == 'jointChain':
                    self.createdList = []
                    mc.select(cl=True)
                    for pos in self.returnList:        
                        self.createdList.append( mc.joint (p = (pos[0], pos[1], pos[2])) )
                                

        self.reset()
Example #8
0
def returnLocalAimDirection(rootObj,aimObj):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a local aim direction

    ARGUMENTS:
    rootObj(string)
    aimObj(string)

    RETURNS:
    direction(list) - [0,0,0]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    directionalLocArray = []
    locGroups = []
    directions = ['+x','-x','+y','-y','+z','-z']
    returnDirections = [[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]]
    distanceBuffer = returnDistanceBetweenObjects(rootObj,aimObj)
    rotationOrderDictionary = {'xyz':0,'yzx':1 ,'zxy':2 ,'xzy':3 ,'yxz':4,'zyx':5,'none':6}

    #distanceValues = distanceBuffer /2
    cnt = 0
    for direction in directions:
	locBuffer = mc.spaceLocator()[0]
	objTrans = mc.xform (rootObj, q=True, ws=True, sp=True)
	objRot = mc.xform (rootObj, q=True, ws=True, ro=True)
	objRoo = mc.xform (rootObj, q=True, roo=True )
	
	mc.move (objTrans[0],objTrans[1],objTrans[2], locBuffer)
	mc.setAttr ((locBuffer+'.rotateOrder'), rotationOrderDictionary[objRoo])
	mc.rotate (objRot[0], objRot[1], objRot[2], locBuffer, ws=True)	
	
        locGroups.append(rigging.groupMeObject(locBuffer))
        directionBuffer = list(direction)
        if directionBuffer[0] == '-':
            mc.setAttr((locBuffer+'.t'+directionBuffer[1]), -1)
        else:
            mc.setAttr((locBuffer+'.t'+directionBuffer[1]), 1)
        directionalLocArray.append(locBuffer)
        cnt+=1
    closestLoc = returnClosestObject(aimObj, directionalLocArray)
    matchIndex = directionalLocArray.index(closestLoc)

    for grp in locGroups:
        mc.delete(grp)
	
    return returnDirections[matchIndex]
Example #9
0
        def _copyTransform(self):		    
            copyTransform = self.d_kws['copyTransform']
            if copyTransform is not None:
                if issubclass(type(copyTransform),cgmMeta.cgmNode):
                    i_target = copyTransform
                elif mc.objExists(copyTransform):
                    i_target = cgmMeta.cgmObject(copyTransform)
                else:
                    raise StandardError,"Failed to find suitable copyTransform object: '%s"%copyTransform

                #Need to move this to default cgmNode stuff
                mBuffer = self.mi_control
                i_newTransform = cgmMeta.cgmObject( rigging.groupMeObject(i_target.mNode,False) )
                for a in mc.listAttr(self.mi_control.mNode, userDefined = True):
                    attributes.doCopyAttr(self.mi_control.mNode,a,i_newTransform.mNode)
                curves.parentShapeInPlace(i_newTransform.mNode,self.mi_control.mNode)#Parent shape
                i_newTransform.parent = self.mi_control.parent#Copy parent
                self.mi_control = cgmMeta.asMeta(i_newTransform,'cgmControl', setClass=True)
                mc.delete(mBuffer.mNode)
Example #10
0
def attachObjectToMesh(obj, mesh, aim=False):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Rotation not working!
    DESCRIPTION:
    Script to rename a joint chain list
    
    ARGUMENTS:
    jointList(list) - list of joints in order
    startJointName(string) - what you want the root named
    interiorJointRootName(string) - what you want the iterative name to be
    
    RETURNS:
    newJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ Make a transform group """
    surfaceFollowGroup = mc.group(w=True, empty=True)
    originalPosGroup = rigging.groupMeObject(obj, False)

    surfaceFollowGroup = mc.rename(surfaceFollowGroup,
                                   (obj + '_surfaceFollowGroup'))
    attributes.storeInfo(surfaceFollowGroup, 'object', obj)
    """ make the closest point node """
    closestPointNode = mc.createNode('closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh, shapes=True)
    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((originalPosGroup + '.translate'),
                             (closestPointNode + '.inPosition'))
    attributes.doConnectAttr((controlSurface[0] + '.worldMesh'),
                             (closestPointNode + '.inMesh'))
    attributes.doConnectAttr((controlSurface[0] + '.worldMatrix'),
                             (closestPointNode + '.inputMatrix'))
    """ Contect the locator to the info node"""
    attributes.doConnectAttr((closestPointNode + '.position'),
                             (surfaceFollowGroup + '.translate'))

    mc.normalConstraint(mesh,
                        surfaceFollowGroup,
                        worldUpType='object',
                        worldUpObject=originalPosGroup)
    mc.parentConstraint(mesh, originalPosGroup, maintainOffset=True)
    return [surfaceFollowGroup]
        def _copyTransform(self):		    
            copyTransform = self.d_kws['copyTransform']
            if copyTransform is not None:
                if issubclass(type(copyTransform),cgmMeta.cgmNode):
                    i_target = copyTransform
                elif mc.objExists(copyTransform):
                    i_target = cgmMeta.cgmObject(copyTransform)
                else:
                    raise StandardError,"Failed to find suitable copyTransform object: '%s"%copyTransform

                #Need to move this to default cgmNode stuff
                mBuffer = self.mi_control
                i_newTransform = cgmMeta.cgmObject( rigging.groupMeObject(i_target.mNode,False) )
                for a in mc.listAttr(self.mi_control.mNode, userDefined = True):
                    attributes.doCopyAttr(self.mi_control.mNode,a,i_newTransform.mNode)
                curves.parentShapeInPlace(i_newTransform.mNode,self.mi_control.mNode)#Parent shape
                i_newTransform.parent = self.mi_control.parent#Copy parent
                self.mi_control = cgmMeta.asMeta(i_newTransform,'cgmControl', setClass=True)
                mc.delete(mBuffer.mNode)
Example #12
0
def returnLocalAimDirection(rootObj, aimObj):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a local aim direction

    ARGUMENTS:
    rootObj(string)
    aimObj(string)

    RETURNS:
    direction(list) - [0,0,0]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    directionalLocArray = []
    locGroups = []
    directions = ['+x', '-x', '+y', '-y', '+z', '-z']
    returnDirections = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0],
                        [0, 0, 1], [0, 0, -1]]
    distanceBuffer = distance.returnDistanceBetweenObjects(rootObj, aimObj)

    #distanceValues = distanceBuffer /2
    cnt = 0
    for direction in directions:
        locBuffer = locators.locMeObject(rootObj)
        locBuffer = mc.rename(locBuffer, (locBuffer + '_' + str(cnt)))
        locGroups.append(rigging.groupMeObject(locBuffer))
        directionBuffer = list(direction)
        if directionBuffer[0] == '-':
            mc.setAttr((locBuffer + '.t' + directionBuffer[1]), -1)
        else:
            mc.setAttr((locBuffer + '.t' + directionBuffer[1]), 1)
        directionalLocArray.append(locBuffer)
        cnt += 1
    closestLoc = distance.returnClosestObject(aimObj, directionalLocArray)
    matchIndex = directionalLocArray.index(closestLoc)

    for grp in locGroups:
        mc.delete(grp)

    return returnDirections[matchIndex]
Example #13
0
def plasticConstraintsAndScaleFromObjectToTransform():
    selection = mc.ls(sl=True, flatten=True)
    for obj in selection:
        #Make a transform
        group = rigging.groupMeObject(obj,maintainParent = True)

        #Get scale connections
        objScaleConnections = []
        for s in 'sx','sy','sz':
            buffer =  attributes.returnDriverAttribute(obj+'.'+s)
            attributes.doBreakConnection(obj+'.'+s)
            attributes.doConnectAttr(buffer,(group+'.'+s))

        # Get constraint info from obj
        objConstraints = constraints.returnObjectConstraints(obj)

        for const in objConstraints:
            constraintTargets = constraints.returnConstraintTargets(const)
            mc.delete(const)

            mc.parentConstraint(constraintTargets,group, maintainOffset = True)
Example #14
0
def plasticConstraintsAndScaleFromObjectToTransform():
    selection = mc.ls(sl=True, flatten=True)
    for obj in selection:
        #Make a transform
        group = rigging.groupMeObject(obj,maintainParent = True)

        #Get scale connections
        objScaleConnections = []
        for s in 'sx','sy','sz':
            buffer =  attributes.returnDriverAttribute(obj+'.'+s)
            attributes.doBreakConnection(obj+'.'+s)
            attributes.doConnectAttr(buffer,(group+'.'+s))

        # Get constraint info from obj
        objConstraints = constraints.returnObjectConstraints(obj)

        for const in objConstraints:
            constraintTargets = constraints.returnConstraintTargets(const)
            mc.delete(const)

            mc.parentConstraint(constraintTargets,group, maintainOffset = True)
Example #15
0
def attachObjectToMesh (obj, mesh, aim=False):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Rotation not working!
    DESCRIPTION:
    Script to rename a joint chain list
    
    ARGUMENTS:
    jointList(list) - list of joints in order
    startJointName(string) - what you want the root named
    interiorJointRootName(string) - what you want the iterative name to be
    
    RETURNS:
    newJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ Make a transform group """
    surfaceFollowGroup =  mc.group (w=True, empty=True)
    originalPosGroup = rigging.groupMeObject(obj,False)
    
    surfaceFollowGroup = mc.rename(surfaceFollowGroup,(obj+'_surfaceFollowGroup'))
    attributes.storeInfo(surfaceFollowGroup,'object',obj)  
    
    
    """ make the closest point node """
    closestPointNode = mc.createNode ('closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh,shapes=True)
    
    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((originalPosGroup+'.translate'),(closestPointNode+'.inPosition'))
    attributes.doConnectAttr((controlSurface[0]+'.worldMesh'),(closestPointNode+'.inMesh'))
    attributes.doConnectAttr((controlSurface[0]+'.worldMatrix'),(closestPointNode+'.inputMatrix'))

    """ Contect the locator to the info node"""
    attributes.doConnectAttr ((closestPointNode+'.position'),(surfaceFollowGroup+'.translate'))
    
    
    mc.normalConstraint(mesh,surfaceFollowGroup,worldUpType='object',worldUpObject=originalPosGroup)
    mc.parentConstraint(mesh,originalPosGroup, maintainOffset = True)
    return [surfaceFollowGroup]
Example #16
0
def driveAttachedPriCtl(bnd, priCtl):
    # find dmNd
    all_mms = priCtl.matrix.outputs(type='multMatrix')
    bndName = '_'.join(bnd.name().split('_')[:3])
    mm = [m for m in all_mms if bndName in m.name()][0]
    dmNd = mm.matrixSum.outputs(type='decomposeMatrix')[0]
    
    channels = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
    
    if bnd.hasAttr('attached_pri_ctl'):
        attachedCtl = bnd.attr('attached_pri_ctl').get()
        if attachedCtl != priCtl:
            print 'Bnd: ' + bnd
            print 'Current Pri Ctl: ' + priCtl
            print 'Attached Pri Ctl: ' + attachedCtl
            attachedCtg = attachedCtl.getParent()
            # add zero grp to take in connections
            zeroGrp = pm.PyNode(cgmrigging.groupMeObject(attachedCtg.nodeName(), True, True))
            for eachChannel in channels:
                mdl = pm.createNode('multDoubleLinear', n=bnd.replace('_bnd', '_%s_%s_mdl' % (eachChannel, priCtl)))
                if eachChannel in ['sx', 'sy', 'sz']:
                    adl = pm.createNode('addDoubleLinear', n=bnd.replace('_bnd', '_%s_%s_adl' % (eachChannel, priCtl)))
                    dmNd.attr('o' + eachChannel) >> adl.input1
                    adl.input2.set(-1)
                    adl.output >> mdl.input1
                else:
                    dmNd.attr('o' + eachChannel) >> mdl.input1
                bnd.attr(priCtl.stripNamespace().nodeName() + '_weight_' + eachChannel) >> mdl.input2
                if eachChannel in ['sx', 'sy', 'sz']:
                    adl = pm.createNode('addDoubleLinear', n=bnd.replace('_bnd', '_%s_%s_adl' % (eachChannel, priCtl)))
                    mdl.output >> adl.input1
                    adl.input2.set(1)
                    adl.output >> zeroGrp.attr(eachChannel)
                else:
                    mdl.output >> zeroGrp.attr(eachChannel)
    
    return eachChannel
Example #17
0
def doParentConstraintObjectGroup(targets,obj,mode=0): 
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list)
    object(string
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """    
    objGroup = rigging.groupMeObject(obj,True,True)
    constraint = mc.parentConstraint (targets,objGroup, maintainOffset=True)
    if mode == 1:
        weights = returnNormalizedWeightsByDistance(obj,targets)
        targetWeights = mc.parentConstraint(constraint,q=True, weightAliasList=True)
        for cnt,value in enumerate(weights):
            mc.setAttr(('%s%s%s' % (constraint[0],'.',targetWeights[cnt])),value )
    return objGroup
Example #18
0
def attachAimedObjectToSurface(obj, surface, aimObject, parent=True):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Script to rename a joint chain list
    
    ARGUMENTS:
    jointList(list) - list of joints in order
    startJointName(string) - what you want the root named
    interiorJointRootName(string) - what you want the iterative name to be
    
    RETURNS:
    newJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ Make a transform group """
    surfaceLoc = locators.locMeClosestUVOnSurface(obj, surface)
    surfaceFollowGroup = rigging.groupMeObject(surfaceLoc, False)
    transformGroup = rigging.groupMeObject(obj, False)

    surfaceFollowGroup = mc.rename(surfaceFollowGroup,
                                   (obj + '_surfaceFollowGroup'))
    attributes.storeInfo(surfaceFollowGroup, 'object', obj)

    transformGroup = mc.rename(transformGroup,
                               (obj + '_surfaceFollowTransformGroup'))
    attributes.storeInfo(transformGroup, 'object', obj)

    controlSurface = mc.listRelatives(surface, shapes=True)
    """ make the node """
    closestPointNode = mc.createNode('closestPointOnSurface',
                                     name=(obj + '_closestPointInfoNode'))
    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((surfaceLoc + '.translate'),
                             (closestPointNode + '.inPosition'))
    attributes.doConnectAttr((controlSurface[0] + '.worldSpace'),
                             (closestPointNode + '.inputSurface'))

    pointOnSurfaceNode = mc.createNode('pointOnSurfaceInfo',
                                       name=(obj + '_posInfoNode'))
    """ Connect the info node to the surface """
    attributes.doConnectAttr((controlSurface[0] + '.worldSpace'),
                             (pointOnSurfaceNode + '.inputSurface'))
    """ Contect the pos group to the info node"""
    attributes.doConnectAttr((pointOnSurfaceNode + '.position'),
                             (surfaceFollowGroup + '.translate'))
    attributes.doConnectAttr((closestPointNode + '.parameterU'),
                             (pointOnSurfaceNode + '.parameterU'))
    attributes.doConnectAttr((closestPointNode + '.parameterV'),
                             (pointOnSurfaceNode + '.parameterV'))
    """ if we wanna aim """
    if aimObject != False:
        """ make some locs """
        upLoc = locators.locMeObject(surface)
        aimLoc = locators.locMeObject(aimObject)
        attributes.storeInfo(upLoc, 'cgmName', obj)
        attributes.storeInfo(upLoc, 'cgmTypeModifier', 'up')
        upLoc = NameFactory.doNameObject(upLoc)

        attributes.storeInfo(aimLoc, 'cgmName', aimObject)
        attributes.storeInfo(aimLoc, 'cgmTypeModifier', 'aim')
        aimLoc = NameFactory.doNameObject(aimLoc)

        attributes.storeInfo(surfaceFollowGroup, 'locatorUp', upLoc)
        attributes.storeInfo(surfaceFollowGroup, 'aimLoc', aimLoc)
        #mc.parent(upLoc,aimObject)

        boundingBoxSize = distance.returnBoundingBoxSize(surface)
        distance = max(boundingBoxSize) * 2

        mc.xform(upLoc, t=[0, distance, 0], ws=True, r=True)

        attributes.doConnectAttr((aimLoc + '.translate'),
                                 (closestPointNode + '.inPosition'))
        """ constrain the aim loc to the aim object """
        pointConstraintBuffer = mc.pointConstraint(aimObject,
                                                   aimLoc,
                                                   maintainOffset=True,
                                                   weight=1)
        """ aim it """
        aimConstraintBuffer = mc.aimConstraint(aimLoc,
                                               surfaceFollowGroup,
                                               maintainOffset=True,
                                               weight=1,
                                               aimVector=[0, 0, 1],
                                               upVector=[0, 1, 0],
                                               worldUpObject=upLoc,
                                               worldUpType='object')
        """ aim the controller back at the obj"""
        aimConstraintBuffer = mc.aimConstraint(obj,
                                               aimLoc,
                                               maintainOffset=True,
                                               weight=1,
                                               aimVector=[0, 0, -1],
                                               upVector=[0, 1, 0],
                                               worldUpObject=upLoc,
                                               worldUpType='object')

        mc.parent(upLoc, aimObject)
    else:
        mc.delete(closestPointNode)

    transformGroup = rigging.doParentReturnName(transformGroup,
                                                surfaceFollowGroup)
    """finally parent it"""
    if parent == True:
        mc.parent(obj, transformGroup)

    if parent == 'constrain':
        mc.parentConstraint(transformGroup, obj, maintainOffset=True)

    mc.delete(surfaceLoc)
    return [transformGroup, surfaceFollowGroup]
Example #19
0
def rigSpine(moduleNull):
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>>Get our info
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    partName = NameFactory.returnUniqueGeneratedName(moduleNull,
                                                     ignore='cgmType')
    """ template null """
    templateNull = modules.returnTemplateNull(moduleNull)
    templateNullData = attributes.returnUserAttrsToDict(templateNull)
    jointOrientation = modules.returnSettingsData('jointOrientation')
    templateRoot = modules.returnInfoNullObjects(moduleNull,
                                                 'templatePosObjects',
                                                 types='templateRoot')
    """ AutonameStuff """
    divider = NameFactory.returnCGMDivider()
    """ control helper objects """
    controlTemplateObjects = modules.returnInfoNullObjects(
        moduleNull, 'templateControlObjects', types='all')
    controlTemplateObjects = distance.returnDistanceSortedList(
        templateRoot, controlTemplateObjects)

    print 'controlTemplateObjects...'
    print controlTemplateObjects
    """size list of template control objects """
    controlTemplateObjectsSizes = []
    for obj in controlTemplateObjects:
        controlTemplateObjectsSizes.append(
            distance.returnAbsoluteSizeCurve(obj))
    print 'sizes...'
    print controlTemplateObjectsSizes
    """ Skin Joints """
    skinJoints = modules.returnInfoNullObjects(moduleNull,
                                               'skinJoints',
                                               types='all')
    skinJoints = distance.returnDistanceSortedList(templateRoot, skinJoints)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Make Controls
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ control options """
    fk = templateNullData.get('fk')
    ik = templateNullData.get('ik')
    stretch = templateNullData.get('stretch')
    bend = templateNullData.get('bend')
    """controls to make """
    controlsToMake = []
    controlsToMake.append('cog')

    if fk == True:
        controlsToMake.append('segmentControls')
        controlsToMake.append('hips')

    if ik == True:
        controlsToMake.append('vectorHandles')
        controlsToMake.append('spineIKHandle')

    controlsDict = modules.limbControlMaker(moduleNull, controlsToMake)

    print controlsDict
    #>>> Organize em
    segmentControls = controlsDict.get('segmentControls')
    spineIKHandle = controlsDict.get('spineIKHandle')
    cog = controlsDict.get('cog')
    hips = controlsDict.get('hips')
    vectorHandles = controlsDict.get('vectorHandles')

    for handle in vectorHandles[-1:]:
        mc.delete(handle)
        vectorHandles.remove(handle)

    #>>> Parent em
    rigging.parentListToHeirarchy(segmentControls)
    mc.parent(spineIKHandle, segmentControls[-1])
    mc.parent(segmentControls[0], cog)
    mc.parent(hips, cog)

    for obj in segmentControls:
        rigging.zeroTransformMeObject(obj)
        mc.makeIdentity(obj, apply=True, translate=True)

    for obj in vectorHandles:
        mc.makeIdentity(obj, apply=True, translate=True)
    """ hips anchor locator """
    locBuffer = locators.locMeObject(hips)
    attributes.storeInfo(locBuffer, 'cgmName', hips)
    attributes.storeInfo(locBuffer, 'cgmTypeModifier', 'anchor')
    hipsAnchor = NameFactory.doNameObject(locBuffer)

    mc.setAttr((hipsAnchor + '.rotateOrder'), 5)

    pointConstraintBuffer = mc.pointConstraint(hips,
                                               hipsAnchor,
                                               maintainOffset=False,
                                               weight=1)
    orientConstraintBuffer = mc.orientConstraint(hips,
                                                 hipsAnchor,
                                                 maintainOffset=False,
                                                 skip=['x', 'y'],
                                                 weight=1)
    """ hips anchor group constraint """
    groupBuffer = rigging.groupMeObject(hipsAnchor)
    attributes.storeInfo(groupBuffer, 'cgmName', hipsAnchor)
    attributes.storeInfo(groupBuffer, 'cgmTypeModifier', 'orient')
    hipsAnchorOrGroup = NameFactory.doNameObject(groupBuffer)
    orientConstraintBuffer = mc.orientConstraint(segmentControls[0],
                                                 hipsAnchorOrGroup,
                                                 maintainOffset=False,
                                                 weight=1)
    """ end anchor locator """
    locBuffer = locators.locMeObject(segmentControls[-1])
    attributes.storeInfo(locBuffer, 'cgmName', segmentControls[-1])
    attributes.storeInfo(locBuffer, 'cgmTypeModifier', 'anchor')
    endAnchor = NameFactory.doNameObject(locBuffer)

    mc.setAttr((endAnchor + '.rotateOrder'), 5)

    mc.parent(endAnchor, spineIKHandle)

    #>>> set up follow chains
    constraintChain = []
    constraintChain.append(hipsAnchor)
    constraintChain = constraintChain + vectorHandles
    constraintChain.append(endAnchor)

    constraintChainReturn = constraints.doSegmentAimPointConstraint(
        constraintChain)
    print constraintChainReturn
    vectorHandlesZeroGroups = []
    for obj in vectorHandles:
        vectorHandlesZeroGroups.append(rigging.zeroTransformMeObject(obj))
    """ parent the last group to our IK handle """
    #mc.parent(vectorHandlesZeroGroups[-1],spineIKHandle)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Joint Chains
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ surface chain """
    dupJointsBuffer = mc.duplicate(skinJoints[:-1], po=True, rc=True)
    surfaceJoints = []
    for joint in dupJointsBuffer:
        attributes.storeInfo(joint, 'cgmType', 'surfaceJoint')
        surfaceJoints.append(NameFactory.doNameObject(joint))
    """ firm start """
    startJointsBuffer = mc.duplicate(skinJoints[0], po=True, rc=True)
    startJoints = []
    for joint in startJointsBuffer:
        attributes.storeInfo(joint, 'cgmType', 'deformationJoint')
        startJoints.append(NameFactory.doNameObject(joint))
    """ firm end """
    endJointsBuffer = mc.duplicate(skinJoints[-2:], po=True, rc=True)
    endJoints = []
    for joint in endJointsBuffer:
        attributes.storeInfo(joint, 'cgmType', 'deformationJoint')
        endJoints.append(NameFactory.doNameObject(joint))
    mc.parent(endJoints[0], world=True)

    #>>> Influence chain
    """
    get the root joints from our main chain searching by "cgmName" tags...maybe not the best way
    Maybe should change to search to closest joints
    """
    influenceJointsBuffer = []
    for obj in surfaceJoints:
        if (search.returnTagInfo(obj, 'cgmName')) != False:
            influenceJointsBuffer.append(obj)
    """ make our influence joints """
    influenceJoints = []
    for joint in influenceJointsBuffer:
        buffer = mc.duplicate(joint, po=True)
        closestObject = distance.returnClosestObject(buffer[0], surfaceJoints)
        attributes.storeInfo(buffer[0], 'cgmName', closestObject)
        attributes.storeInfo(buffer[0], 'cgmType', 'influenceJoint')
        rigging.doParentToWorld(buffer[0])
        influenceJoints.append(NameFactory.doNameObject(buffer[0]))

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Put our deformation joints in the rig
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    ############### need better way of doing this for iterative
    mc.parent(endJoints[0], spineIKHandle)
    mc.parent(startJoints[0], hips)
    mc.parent(influenceJoints[0], hipsAnchor)
    mc.parent(influenceJoints[1], vectorHandles[0])
    mc.parent(influenceJoints[2], spineIKHandle)
    #mc.parent(influenceJoints[3],spineIKHandle)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Control Surface
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ create """
    orientationBuffer = list(jointOrientation)
    outChannel = orientationBuffer[2]
    upChannel = (orientationBuffer[1] + 'up')
    print upChannel

    surfaceBuffer = joints.loftSurfaceFromJointList(surfaceJoints, outChannel)
    controlSurface = surfaceBuffer[0]
    attributes.copyUserAttrs(moduleNull,
                             controlSurface,
                             attrsToCopy=['cgmName'])
    attributes.storeInfo(controlSurface, 'cgmType', 'controlSurface', True)
    controlSurface = NameFactory.doNameObject(controlSurface)
    """ connect joints to surface"""
    surfaceConnectReturn = joints.attachJointChainToSurface(
        surfaceJoints, controlSurface, jointOrientation, upChannel, 'animCrv')
    print surfaceConnectReturn
    """ surface influence joints skinning"""
    surfaceSkinCluster = mc.skinCluster(influenceJoints,
                                        controlSurface,
                                        tsb=True,
                                        n=(controlSurface + '_skinCluster'),
                                        maximumInfluences=3,
                                        normalizeWeights=1,
                                        dropoffRate=1)
    #surfaceSkinCluster = mc.skinCluster (influenceJoints,controlSurface,tsb=True, n=(controlSurface+'_skinCluster'),maximumInfluences = 3, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
    controlSurfaceSkinCluster = surfaceSkinCluster[0]
    """ smooth skin weights """
    skinning.simpleControlSurfaceSmoothWeights(controlSurface)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Connect skin joints to surface joints
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    deformationJoints = []
    deformationJoints.append(startJoints[0])
    deformationJoints = deformationJoints + surfaceJoints[1:-2]
    deformationJoints = deformationJoints + endJoints
    for joint in skinJoints:
        attachJoint = distance.returnClosestObject(joint, deformationJoints)
        pntConstBuffer = mc.pointConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
        orConstBuffer = mc.orientConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
        #mc.connectAttr((attachJoint+'.t'),(joint+'.t'))
        #mc.connectAttr((attachJoint+'.r'),(joint+'.r'))
        mc.connectAttr((attachJoint + '.s'), (joint + '.s'))
        pntConstBuffer = mc.pointConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
        orConstBuffer = mc.orientConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
Example #20
0
    def createSizeTemplateControl(self):
        """ 
        >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   
        DESCRIPTION:
        Generates a sizeTemplateObject. It's been deleted, it recreates it. Guess the size based off of there
        being a mesh there. If there is no mesh, it sets sets an intial size of a 
        [155,170,29] unit character.
        
        ARGUMENTS:
        self.PuppetNull.nameShort(string)
        
        RETURNS:
        returnList(list) = [startCrv(string),EndCrv(list)]
        >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        """
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Get info
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        startColors = modules.returnSettingsData('colorStart')
        endColors = modules.returnSettingsData('colorEnd')

        font = mc.getAttr((self.msgSettingsInfo.get() + '.font'))
        """ checks for there being anything in our geo group """
        if not self.geo:
            return guiFactory.warning(
                'Need some geo defined to make this tool worthwhile')
            boundingBoxSize = modules.returnSettingsDataAsFloat(
                'meshlessSizeTemplate')
        else:
            boundingBoxSize = distance.returnBoundingBoxSize(
                self.msgGeoGroup.get())
            boundingBox = mc.exactWorldBoundingBox(self.msgGeoGroup.get())
        """determine orienation """
        maxSize = max(boundingBoxSize)
        matchIndex = boundingBoxSize.index(maxSize)
        """Find the pivot of the bounding box """
        pivotPosition = distance.returnCenterPivotPosition(
            self.msgGeoGroup.get())

        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Get our positions
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        if self.optionPuppetMode.get() == 0:
            #If bio...
            if matchIndex == 1 or matchIndex == 0:
                #Vertical
                posBuffers = [[0, .5, 0], [0, .75, 0]]
                width = (boundingBoxSize[0] / 2)
                height = (boundingBoxSize[1])
                depth = boundingBoxSize[2]

                for cnt, pos in enumerate(posBuffers):
                    posBuffer = posBuffers[cnt]
                    posBuffer[0] = 0
                    posBuffer[1] = (posBuffer[1] * height)
                    posBuffer[2] = 0

            elif matchIndex == 2:
                #Horizontal
                posBuffers = [[0, 0, -.33], [0, 0, .66]]
                width = boundingBoxSize[1]
                height = boundingBoxSize[2] / 2
                depth = (boundingBoxSize[0])

                for cnt, pos in enumerate(posBuffers):
                    posBuffer = posBuffers[cnt]
                    posBuffer[0] = 0
                    posBuffer[1] = boundingBoxSize[1] * .75
                    posBuffer[2] = (posBuffer[2] * height)

        else:
            #Otherwise
            if matchIndex == 1 or matchIndex == 0:
                #Vertical
                width = (boundingBoxSize[0] / 2)
                height = (boundingBoxSize[1])
                depth = boundingBoxSize[2]
                posBuffers = [[0, boundingBox[1], 0], [0, boundingBox[4], 0]]

            elif matchIndex == 2:
                #Horizontal
                width = boundingBoxSize[0]
                height = boundingBoxSize[2] / 2
                depth = (boundingBoxSize[1])
                startHeight = max([boundingBox[4], boundingBox[1]]) - depth / 2
                print startHeight
                posBuffers = [[0, startHeight, boundingBox[2]],
                              [0, startHeight, boundingBox[5]]]
        # Simple reverse of start pos buffers if the object is pointing negative
        if self.optionAimAxis < 2:
            posBuffers.reverse()

        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Making the controls
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        """ make our control object """
        startCurves = []
        startCurve = curves.createControlCurve('circle', depth * .8)
        mc.xform(startCurve, t=posBuffers[0], ws=True)
        attributes.doSetAttr(startCurve, 'rotateOrder', 5)
        curves.setCurveColorByName(startCurve, startColors[1])
        startCurves.append(startCurve)

        startText = curves.createTextCurve('start',
                                           size=depth * .75,
                                           font=font)
        mc.xform(startText, t=posBuffers[0], ws=True)
        curves.setCurveColorByName(startText, startColors[0])
        startCurves.append(startText)

        endCurves = []
        endCurve = curves.createControlCurve('circle', depth * .8)
        mc.xform(endCurve, t=posBuffers[1], ws=True)
        curves.setCurveColorByName(endCurve, endColors[1])
        attributes.doSetAttr(endCurve, 'rotateOrder', 5)
        endCurves.append(endCurve)

        endText = curves.createTextCurve('end', size=depth * .6, font=font)
        mc.xform(endText, t=posBuffers[1], ws=True)
        curves.setCurveColorByName(endText, endColors[0])
        endCurves.append(endText)
        """ aiming """
        position.aimSnap(startCurve, endCurve, [0, 0, 1], [0, 1, 0])
        position.aimSnap(startText, endCurve, [0, 0, 1], [0, 1, 0])

        position.aimSnap(endCurve, startCurve, [0, 0, -1], [0, 1, 0])
        position.aimSnap(endText, startCurve, [0, 0, -1], [0, 1, 0])

        sizeCurveControlStart = curves.combineCurves(startCurves)
        sizeCurveControlEnd = curves.combineCurves(endCurves)
        """ store our info to name our objects"""
        attributes.storeInfo(sizeCurveControlStart, 'cgmName',
                             (self.PuppetNull.nameShort + '.cgmName'))
        attributes.storeInfo(sizeCurveControlStart, 'cgmDirection', 'start')
        attributes.storeInfo(sizeCurveControlStart, 'cgmType',
                             'templateSizeObject')
        sizeCurveControlStart = NameFactory.doNameObject(sizeCurveControlStart)
        mc.makeIdentity(sizeCurveControlStart,
                        apply=True,
                        t=True,
                        s=True,
                        r=True)

        attributes.storeInfo(sizeCurveControlEnd, 'cgmName',
                             (self.PuppetNull.nameShort + '.cgmName'))
        attributes.storeInfo(sizeCurveControlEnd, 'cgmDirection', 'end')
        attributes.storeInfo(sizeCurveControlEnd, 'cgmType',
                             'templateSizeObject')
        sizeCurveControlEnd = NameFactory.doNameObject(sizeCurveControlEnd)

        endGroup = rigging.groupMeObject(sizeCurveControlEnd)
        mc.makeIdentity(sizeCurveControlEnd,
                        apply=True,
                        t=True,
                        s=True,
                        r=True)

        mc.parentConstraint(sizeCurveControlStart,
                            endGroup,
                            maintainOffset=True)
        """ make control group """
        controlGroup = rigging.groupMeObject(sizeCurveControlStart)
        attributes.storeInfo(controlGroup, 'cgmName',
                             (self.PuppetNull.nameShort + '.cgmName'))
        attributes.storeInfo(controlGroup, 'cgmType',
                             'templateSizeObjectGroup')
        controlGroup = NameFactory.doNameObject(controlGroup)

        endGroup = rigging.doParentReturnName(endGroup, controlGroup)
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Getting data ready
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        attributes.storeInfo(controlGroup, 'controlStart',
                             sizeCurveControlStart)
        attributes.storeInfo(controlGroup, 'controlEnd', sizeCurveControlEnd)
        attributes.storeInfo(self.PuppetNull.nameShort, 'templateSizeObject',
                             controlGroup)

        self.templateSizeObjects['root'] = controlGroup
        self.templateSizeObjects['start'] = sizeCurveControlStart
        self.templateSizeObjects['end'] = sizeCurveControlEnd

        returnList = []
        returnList.append(sizeCurveControlStart)
        returnList.append(sizeCurveControlEnd)
        return returnList
Example #21
0
def surfRigger(objectNull,anchor,worldScale,mirror,mode,jointsPerChain,deformChains,ctrlChains):
    """ Get variables"""
    nullBase = names.stripSuffixObj (objectNull)
    templateNull = (nullBase + '_templateNull')
    moverNull = (nullBase + '_mover')
    templateNullMessageData = []
    templateNullMessageData = attributes.returnMessageAttrs (templateNull)
    templateObjects = []
    coreNamesList = []
    spineJointNumber = int(mc.getAttr (objectNull+'.rollJoints'))
    #spineChainList = search.returnChildrenJoints (spineChain)
    spineChainList = []
    spineChainList.append (anchor)
    jointChains = []
    for set in templateNullMessageData:
        templateObjects.append (set[1])
        coreNamesList.append (set[0])
    #>>>>>>>>>>>>>>>>>>>>>Store skin joint data
    """ check for master skin info group """
    if mc.objExists ('master_skinJntList_grp'):
        masterSkinJointList = ('master_skinJntList_grp')
    else:
        masterSkinJointList = mc.group (n= ('master_skinJntList_grp'), w=True, empty=True)
        mc.parent(masterSkinJointList,'rigStuff_grp')
    """ check for segment skin info group """
    if mc.objExists (nullBase+'_skinJntList_grp'):
        skinJointListGrp = (nullBase+'_skinJntList_grp')
    else:
        skinJointListGrp = mc.group (n= (nullBase+'_skinJntList_grp'), w=True, empty=True)
    attributes.storeObjNameToMessage (skinJointListGrp,masterSkinJointList)
    mc.parent (skinJointListGrp,masterSkinJointList)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ Rebuild curve - with actual curve in it!"""
    mc.rebuildCurve ((templateObjects[3]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=jointsPerChain, d=1, tol=5)
    mc.rebuildCurve ((templateObjects[7]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=jointsPerChain, d=1, tol=5)
    mc.rebuildCurve ((templateObjects[11]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=jointsPerChain, d=1, tol=5)
    """ Reverse the curve """
    mc.reverseCurve ((templateObjects[3]),ch=False,rpo=True)
    mc.reverseCurve ((templateObjects[7]),ch=False,rpo=True)
    mc.reverseCurve ((templateObjects[11]),ch=False,rpo=True)
    """ loft our surface to figure out joint positions, then delete it"""
    controlSurface = mc.loft ([templateObjects[3],templateObjects[7],templateObjects[11]],name=(nullBase+'_surf'),ss=(ctrlChains-mode),ch=1,u=1,c=0,ar=1,d=3,rn=0,po=0,rsn=True)
    mc.select (cl=True)
    jointChains = joints.createJointChainsFromLoftSurface (nullBase,controlSurface[0],2,False)
    frontChain = jointChains[0]
    backChain = jointChains[-1]
    """ Chain - orienting, sizing """
    for chain in jointChains:
        joints.orientJointChain (chain, 'xyz', 'zup')
        joints.setGoodJointRadius(chain,.5)
    #IF we have mode 0, gotta make a main ctrl
    if mode == 0:
        midChain = []
        if (len(jointChains)) > 3:
            midChain = jointChains[int(len(jointChains)/2)]
        else:
            midChain = jointChains[1]
            jointChains.remove(midChain)
        if ctrlChains > 2:
            masterCtrlBuffer = mc.duplicate (midChain[0],parentOnly=True)
        else:
            masterCtrlBuffer = midChain[0]
            mc.delete (midChain[1])
        masterCtrl = mc.rename (masterCtrlBuffer,(nullBase+'_master_anim'))
        position.movePointSnap(masterCtrl,moverNull)
        """ temp parenting the master control for mirroring purposes """
        spineHookJoint = distance.returnClosestObject (masterCtrl, spineChainList)
        mc.parent (masterCtrl,spineHookJoint)
    mc.delete (controlSurface[0])
    #>>>>>>>>>>>>Parent time
    """ Get closest joint """
    if mode == 0:
        for chain in jointChains:
            mc.parent (chain[0],masterCtrl)
    else:
        for chain in jointChains:
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            mc.parent (chain[0],tailHookJoint)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>> Ctrl Joints to Ctrls
    cnt = 0
    for chain in jointChains:
        ctrlSize = (distance.returnAverageDistanceBetweenObjects (chain)/2)
        for jnt in chain[0:-1]:
            rigging.makeObjCtrl (jnt,ctrlSize)
        """ adds our Anim tag """
        chainBuffer = []
        chainBuffer = names.addSuffixList ('anim', chain)
        jointChains[cnt]= chainBuffer
        cnt +=1
    #>>>>>>>>>>>>>>>>>>>Mirroring while getting chain info
    """ If mirroring ...."""
    if mirror == True:
        # if we have a main control
        leftSkinChains = []
        rightSkinChains = []
        masterCtrls = []
        if mode == 0:
            leftChain = []
            rightChain = []
            finHeirarchy = []
            finHeirarchy.append (masterCtrl)
            children = search.returnChildrenJoints (masterCtrl)
            finHeirarchy += children
            leftChain = names.addPrefixList ('left',finHeirarchy)
            masterCtrl = leftChain [0]
            rightChainBuffer = mc.mirrorJoint (masterCtrl,mirrorYZ=True,mirrorBehavior=True, searchReplace =['left','right'])
            rightChainJointBuffer = mc.ls (rightChainBuffer,type='joint')
            rightChain = rightChainJointBuffer
            leftSkinChains.append(leftChain)
            rightSkinChains.append(rightChain)
            masterCtrls.append(leftChain[0])
            masterCtrls.append(rightChain[0])
        else:
            for chain in jointChains:
                leftChain =[]
                leftChain = names.addPrefixList ('left',chain)
                rightChainBuffer = (mc.mirrorJoint (leftChain[0],mirrorYZ=True,mirrorBehavior=True, searchReplace =['left','right']))
                rightChainJointBuffer = mc.ls (rightChainBuffer,type='joint')
                rightChain = rightChainJointBuffer
                rightSkinChains.append (rightChainJointBuffer)
                leftSkinChains.append (leftChain)
        """ complile our chains to lists of skin joints """
        leftSkinJointList=[]
        rightSkinJointList=[]
        for chain in leftSkinChains:
            for jnt in chain:
                leftSkinJointList.append (jnt)
        for chain in rightSkinChains:
            for jnt in chain:
                rightSkinJointList.append (jnt)
        """if we're not mirroring, let's return our skin joints for the deformation surface"""
    else:
        skinJointList = []
        skinChains = []
        for chain in jointChains:
            skinChains.append (chain)
            for jnt in chain:
                skinJointList.append (jnt)
                
    #>>>>>>>>>>>>>>>>>>>>>>>>>>Time to make the deformation surface stuff
    """ Rebuild curve - with actual curve in it!"""
    #mc.rebuildCurve ((templateObjects[3]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=(3), d=1, tol=5)
    #mc.rebuildCurve ((templateObjects[7]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=(3), d=1, tol=5)
    """ loft our surface to figure out joint positions, then delete it"""
    deformSurface = mc.loft ([templateObjects[3],templateObjects[7],templateObjects[11]],name=(nullBase+'_surf'),ss=(deformChains-1),ch=0,u=1,c=0,ar=1,d=3,rn=0,po=0,rsn=True)
    if mirror == True:
        deformSurfaceNameBuffer = deformSurface[0]
        """we have a surface to mirror..."""
        surfaceMirrorBuffer = mc.duplicate (deformSurface[0])
        mc.setAttr ((surfaceMirrorBuffer[0]+'.sx'),-1)
        leftBuffer = mc.rename (deformSurface[0],('left_'+deformSurfaceNameBuffer))
        rightBuffer = mc.rename (surfaceMirrorBuffer[0],('right_'+deformSurfaceNameBuffer))
        deformSurface[0]=leftBuffer
        deformSurface.append(rightBuffer)
        leftDeformJointChains = joints.createJointChainsFromLoftSurface (('left_'+nullBase),deformSurface[0],2,False)
        rightDeformJointChains = joints.createJointChainsFromLoftSurface (('right_'+nullBase),deformSurface[1],2,False)
        """ Connecting to surface """
        for chain in leftDeformJointChains:
            attachSurfaceReturn = joints.attachJointChainToSurface (chain,deformSurface[0],'xyz','zup')
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            """ break the connection so we can parent it"""
            """first return the original thing to follow"""
            parentBuffer = attributes.returnDriverObject ((chain[0]+'.translate'))
            attributes.doBreakConnection (chain[0]+'.translate')
            #mc.parent (chain[0],tailHookJoint)
            """ reconstrain it to the driver"""
            constraintBuffer = mc.pointConstraint (parentBuffer,chain[0], maintainOffset = True)
            mc.rename (constraintBuffer[0],(chain[0]+'_pointConst'))
            """ store the skin joint data """
            for jnt in chain:
                attributes.storeObjNameToMessage (jnt,skinJointListGrp)

        for chain in rightDeformJointChains:
            attachSurfaceMirrorReturn = joints.attachJointChainToSurface (chain,deformSurface[1],'xyz','zup')
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            """ break the connection s we can parent it"""
            """first return the original thing to follow"""
            parentBuffer = attributes.returnDriverObject ((chain[0]+'.translate'))
            attributes.doBreakConnection (chain[0]+'.translate')
            #mc.parent (chain[0],tailHookJoint)
            """ reconstrain it to the driver"""
            constraintBuffer = mc.pointConstraint (parentBuffer,chain[0], maintainOffset = True)
            mc.rename (constraintBuffer[0],(chain[0]+'_pointConst'))
            """ store the skin joint data """
            for jnt in chain:
                attributes.storeObjNameToMessage (jnt,skinJointListGrp)

        """ parent the scale stuff to rig stuff grp"""
        mc.select (cl=True)
        for item in attachSurfaceReturn[0]:
            mc.parent(item,'rigStuff_grp')
        for item in attachSurfaceMirrorReturn[0]:
            mc.parent(item,'rigStuff_grp')
        """ hook up world scale """
        mc.connectAttr (worldScale,attachSurfaceReturn[1])
        mc.connectAttr (worldScale,attachSurfaceMirrorReturn[1])
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Skin in the control joints
        """ Time to set skin our surface to our control joints """
        mc.skinCluster (leftSkinJointList,deformSurface[0],tsb=True, n=(deformSurface[0]+'_skinCluster'),maximumInfluences = 8, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
        mc.skinCluster (rightSkinJointList,deformSurface[1],tsb=True, n=(deformSurface[1]+'_skinCluster'),maximumInfluences = 8, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
    #>>>>>If we,re not mirrored, let's make our deform setup
    else:
        deformJointChains = []
        deformJointChains = joints.createJointChainsFromLoftSurface (nullBase,deformSurface[0],2,False)
        """ Connecting to surface """
        for chain in deformJointChains:
            attachSurfaceReturn = joints.attachJointChainToSurface (chain,deformSurface[0],'xyz','zup')
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            """ break the connection so we can parent it"""
            """first return the original thing to follow"""
            parentBuffer = attributes.returnDriverObject ((chain[0]+'.translate'))
            attributes.doBreakConnection (chain[0]+'.translate')
            #mc.parent (chain[0],tailHookJoint)
            """ reconstrain it to the driver"""
            constraintBuffer = mc.pointConstraint (parentBuffer,chain[0], maintainOffset = True)
            mc.rename (constraintBuffer[0],(chain[0]+'_pointConst'))
            """ store the skin joint data """
            for jnt in chain:
                attributes.storeObjNameToMessage (jnt,skinJointListGrp)
        """ hook up world scale  """
        partScaleBuffer = attachSurfaceReturn[1]
        mc.connectAttr (worldScale, partScaleBuffer)
        """ parent the scale stuff to rig stuff grp"""
        mc.select (cl=True)
        for item in attachSurfaceReturn[0]:
            mc.parent(item,'rigStuff_grp')
        """ Time to set skin our surface to our control joints """
        mc.skinCluster (skinJointList,deformSurface[0],tsb=True, n=(deformSurface[0]+'_skinCluster'),maximumInfluences = 8, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
        
        
    """ Setting up the joint starts"""
    if mode == 0:
        if mirror == True:
            for ctrl in masterCtrls:
                rigging.makeObjCtrl (ctrl,(ctrlSize*4))
                masterCtrlGrp = rigging.groupMeObject (ctrl,True)
                """ Get closest joint and connect the Cntrl """
                spineHookJoint = distance.returnClosestObject (masterCtrlGrp, spineChainList)
                mc.parent(masterCtrlGrp,spineHookJoint)
        else:
            rigging.makeObjCtrl (masterCtrl,(ctrlSize*4))
            masterCtrlGrp = rigging.groupMeObject (masterCtrl,True)
            """ Get closest joint and connect the Cntrl """
            spineHookJoint = distance.returnClosestObject (masterCtrlGrp, spineChainList)
            mc.parent(masterCtrlGrp,spineHookJoint)
    #else we need to connect the individual chains to the spine
    else:
        if mirror == True:
            for chain in leftSkinChains:
                chainCtrlGrp = rigging.groupMeObject (chain[0],True)
                spineHookJoint = distance.returnClosestObject (chainCtrlGrp, spineChainList)
                mc.parent(chainCtrlGrp,spineHookJoint)
            for chain in rightSkinChains:
                chainCtrlGrp = rigging.groupMeObject (chain[0],True)
                spineHookJoint = distance.returnClosestObject (chainCtrlGrp, spineChainList)
                mc.parent(chainCtrlGrp,spineHookJoint)
        else:
            for chain in skinChains:
                chainCtrlGrp = rigging.groupMeObject (chain[0],True)
                spineHookJoint = distance.returnClosestObject (chainCtrlGrp, spineChainList)
                mc.parent(chainCtrlGrp,spineHookJoint)
Example #22
0
def rigSpine (crvName,tailCntrlJoints,waveControlObject,splitJoints):
    """ Rebuild curve - with actual curve in it!"""
    """ first have to make our reg spine""" 
    mc.rebuildCurve (crvName, ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=(splitJoints), d=1, tol=5)
    """ Make joint chains"""
    spineJoints = joints.createJointsFromCurve (crvName,'spine')
    """ set joint radius """
    joints.setGoodJointRadius (spineJoints,1)
    """ Orienting the joint chain """
    joints.orientJointChain (spineJoints, 'xyz', 'zup')
    
    """ Renaming the joint chain """
    spineJointsBuffer = names.renameJointChainList (spineJoints, 'tailStart', 'tail')
    spineJoints = spineJointsBuffer
    """ removing initial bind from the spine curve """
    mc.delete ('bindPose1')
    mc.delete ('skinCluster1')
    """ Makes our control surface """
    controlSurface = makeJointControlSurfaceFish(spineJoints[0],tailCntrlJoints,'y','tail')
    """ parenting the tail joints """
    rigging.parentListToHeirarchy (tailCntrlJoints)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>auto swim stuff
    """ Creating our deformation surface """
    deformMeshBuffer = mc.duplicate (controlSurface)
    deformMesh = mc.rename (deformMeshBuffer[0],(controlSurface[0]+'_defmesh'))
    """ Creates  our wave deformer """
    deformerBuffer = mc.nonLinear (deformMesh, type = 'wave', name = 'swimWave')
    waveDeformer = mc.rename (deformerBuffer[0], 'waveDeformer')
    waveDeformerHandle = mc.rename (deformerBuffer[1], 'waveDeformerHandle')
    """ move the handle """
    position.movePointSnap (waveDeformerHandle,spineJoints[0])
    mc.setAttr ((waveDeformerHandle+'.rx'),90)
    mc.setAttr ((waveDeformerHandle+'.ry'),90)
    """ set some variables """
    mc.setAttr ((waveDeformer+'.dropoff'),1)
    mc.setAttr ((waveDeformer+'.dropoffPosition'),1)
    mc.setAttr ((waveDeformer+'.maxRadius'),2)
    """ make our blendshape node and reorder things"""
    blendshapeNode = mc.blendShape (deformMesh, controlSurface[0], name = 'swim_bsNode' )
    mc.reorderDeformers ("tweak2", blendshapeNode[0],controlSurface[0])
    """ add some attrs to our wave control object """
    attributes.addSectionBreakAttrToObj (waveControlObject, 'swim')
    attributes.addFloatAttributeToObject (waveControlObject, 'auto', min = 0, max = 1, dv =0)
    attributes.addFloatAttributeToObject (waveControlObject, 'speed', -100, 100, 0)
    attributes.addFloatAttributeToObject (waveControlObject, 'wavelength', 0, 10, 5)
    attributes.addFloatAttributeToObject (waveControlObject, 'amplitude', 0, 10, 0)
    attributes.addFloatAttributeToObject (waveControlObject, 'dropoff', 0, 1, 1)
    attributes.addFloatAttributeToObject (waveControlObject, 'dropoffPosition', 0, 1, 0)
    attributes.addFloatAttributeToObject (waveControlObject, 'minRadius', 0, 10, 0)
    attributes.addFloatAttributeToObject (waveControlObject, 'maxRadius', 0, 10, 10)
    """ connect a few attrs """
    mc.connectAttr ((waveControlObject+'.auto'),(blendshapeNode[0]+'.'+deformMesh))
    mc.connectAttr ((waveControlObject+'.wavelength'),(waveDeformer+'.wavelength'))
    mc.connectAttr ((waveControlObject+'.amplitude'),(waveDeformer+'.amplitude'))
    mc.connectAttr ((waveControlObject+'.dropoff'),(waveDeformer+'.dropoff'))
    mc.connectAttr ((waveControlObject+'.dropoffPosition'),(waveDeformer+'.dropoffPosition'))
    mc.connectAttr ((waveControlObject+'.minRadius'),(waveDeformer+'.minRadius'))
    mc.connectAttr ((waveControlObject+'.maxRadius'),(waveDeformer+'.maxRadius'))
    """ set some good base values """
    mc.setAttr ((waveControlObject+'.speed'),1)
    mc.setAttr ((waveControlObject+'.wavelength'),4)
    mc.setAttr ((waveControlObject+'.amplitude'),.3)
    mc.setAttr ((waveControlObject+'.dropoff'),1)
    mc.setAttr ((waveControlObject+'.dropoffPosition'),1)
    mc.setAttr ((waveControlObject+'.maxRadius'),2)
    """ sets up swim speed """
    nodes.offsetCycleSpeedControlNodeSetup (waveDeformer,(waveControlObject+'.speed'),90,-10)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>> Head control and joint
    headJointBuffer = mc.duplicate ('head_anim')
    headJoint = mc.rename (headJointBuffer, 'head_jnt')
    headCtrlGrp = rigging.groupMeObject ('head_anim',True)
    #mc.parent (headJoint, spineJoints[0])
    mc.parent (headJoint, 'move_anim')
    contsBuffer = mc.parentConstraint (spineJoints[0], headCtrlGrp, maintainOffset = True)
    mc.rename (contsBuffer,(headCtrlGrp+'_prntConst'))
    contsBuffer = mc.parentConstraint ('head_anim', headJoint, maintainOffset = True)
    mc.rename (contsBuffer,(headJoint+'_prntConst'))
    mc.parent (headCtrlGrp,'move_anim')
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Clean stuff
    """ deform group """
    deformGrp = mc.group (n= 'swimDeform_grp', w=True, empty=True)
    mc.parent (waveDeformerHandle,deformGrp)
    mc.parent (deformMesh,deformGrp)
    mc.setAttr ((deformGrp+'.v'), 0)
    mc.setAttr ((controlSurface[0]+'.v'),0)
    """ delete placement stuff """
    mc.delete ('curvePlacementStuff')
    mc.parent (tailCntrlJoints[0],waveControlObject)
    mc.parent (deformGrp, 'rigStuff_grp')

    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>> Ctrl Joints to Ctrls
    ctrlSize = (distance.returnAverageDistanceBetweenObjects (tailCntrlJoints))
    curves.parentShape ('head_anim', 'sampleCtrlZ')
    for ctrl in tailCntrlJoints:
        rigging.makeObjCtrl (ctrl,ctrlSize)
 
    #>>>>>>>>>>>>>>>>>>>>>Store skin joint data
    """ check for master skin info group """
    name = 'spine'
    if mc.objExists ('master_skinJntList_grp'):
        masterSkinJointList = ('master_skinJntList_grp')
    else:
        masterSkinJointList = mc.group (n= ('master_skinJntList_grp'), w=True, empty=True)
        mc.parent(masterSkinJointList,'rigStuff_grp')
    """ check for segment skin info group """
    if mc.objExists (name+'_skinJntList_grp'):
        skinJointList = (name+'_skinJntList_grp')
    else:
        skinJointList = mc.group (n= (name+'_skinJntList_grp'), w=True, empty=True)
    mc.parent (skinJointList,masterSkinJointList)
    attributes.storeObjNameToMessage (skinJointList,masterSkinJointList)
    """ store the skin joint data """
    for jnt in spineJoints:
        attributes.storeObjNameToMessage (jnt,skinJointList)
    attributes.storeObjNameToMessage (headJoint,skinJointList)
Example #23
0
def connectBndToPivot(bnd, pivot, drivePrimary=False):
    '''
    basically the same at face.connectBndToPriCtl
    but can don't drive primary controls
    '''

    # bnd's "local" matrix within pivot
    bnd_wMat = bnd.getMatrix(ws=True)
    pivot_wMat = pivot.getMatrix(ws=True)
    bnd_lMat = bnd_wMat * pivot_wMat.inverse()
    lMatNd = pm.createNode('fourByFourMatrix',
                           n=bnd.replace('_bnd',
                                         '_lMat_in_' + pivot.nodeName()))
    # populate "local" matrix
    for i in range(4):
        for j in range(4):
            lMatNd.attr('in%d%d' % (i, j)).set(bnd_lMat[i][j])
    # bnd's "local-inverse" matrix
    lInvMatNd = pm.createNode('inverseMatrix',
                              n=bnd.replace('_bnd',
                                            '_lInvMat_in_' + pivot.nodeName()))
    lMatNd.output >> lInvMatNd.inputMatrix
    # for bnd to pivot around pivot,
    # the matrix is lMat * pivotMat * lInvMat
    mmNd = pm.createNode('multMatrix', n=bnd.replace('_bnd', '_calc_mm'))
    lMatNd.output >> mmNd.i[0]
    pivot.matrix >> mmNd.i[1]
    lInvMatNd.outputMatrix >> mmNd.i[2]
    # decompose matrix before passing into bw
    dmNd = pm.createNode('decomposeMatrix', n=bnd.replace('_bnd', '_calc_dm'))
    mmNd.o >> dmNd.inputMatrix
    # get bw nodes to connect to
    channels = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
    bwNodes = {}
    for eachChannel in channels:
        bwNodes[eachChannel] = bnd.attr(eachChannel + '_bwMsg').get()
    # get index to connect to
    existingInputs = bwNodes['tx'].i.inputs()
    nextIndex = len(existingInputs)
    # actual connections
    dmNd.otx >> bwNodes['tx'].i[nextIndex]
    dmNd.oty >> bwNodes['ty'].i[nextIndex]
    dmNd.otz >> bwNodes['tz'].i[nextIndex]
    dmNd.orx >> bwNodes['rx'].i[nextIndex]
    dmNd.ory >> bwNodes['ry'].i[nextIndex]
    dmNd.orz >> bwNodes['rz'].i[nextIndex]
    dmNd.osx >> bwNodes['sx'].i[nextIndex]
    dmNd.osy >> bwNodes['sy'].i[nextIndex]
    dmNd.osz >> bwNodes['sz'].i[nextIndex]
    # channel box separator
    bnd.addAttr(pivot.nodeName() + '_weights', at='double', k=True, dv=0)
    bnd.setAttr(pivot.nodeName() + '_weights', lock=True)
    # connect weight to be blended to 0
    for eachChannel in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']:
        bnd.addAttr(pivot.nodeName() + '_weight_' + eachChannel,
                    at='double',
                    k=True,
                    min=-1,
                    max=2,
                    dv=1)
        bnd.attr(pivot.nodeName() + '_weight_' +
                 eachChannel) >> bwNodes[eachChannel].weight[nextIndex]
    # scales need a minus 1, to be normalized to 0 for blending
    for eachChannel in ['sx', 'sy', 'sz']:
        adl = pm.createNode('addDoubleLinear',
                            n=bnd.replace('_bnd', '_%s_adl' % eachChannel))
        adl.input2.set(-1)
        dmNd.attr('o%s' % eachChannel) >> adl.input1
        adl.output >> bwNodes[eachChannel].i[nextIndex]
        bnd.addAttr(pivot.nodeName() + '_weight_' + eachChannel,
                    at='double',
                    k=True,
                    min=-1,
                    max=2,
                    dv=1)
        bnd.attr(pivot.nodeName() + '_weight_' +
                 eachChannel) >> bwNodes[eachChannel].weight[nextIndex]

    if drivePrimary:
        # if this bnd already has it's own attached priCtl
        # we need to drive that too
        if bnd.hasAttr('attached_pri_ctl'):
            attachedCtl = bnd.attr('attached_pri_ctl').get()

            if attachedCtl != pivot:
                print 'Bnd: ' + bnd
                print 'Current Pri Ctl: ' + pivot
                print 'Attached Pri Ctl: ' + attachedCtl
                attachedCtg = attachedCtl.getParent()
                # add zero grp to take in connections
                zeroGrp = pm.PyNode(
                    cgmrigging.groupMeObject(attachedCtg.nodeName(), True,
                                             True))
                for eachChannel in channels:
                    mdl = pm.createNode(
                        'multDoubleLinear',
                        n=bnd.replace('_bnd',
                                      '_%s_%s_mdl' % (eachChannel, pivot)))
                    if eachChannel in ['sx', 'sy', 'sz']:
                        adl = pm.createNode(
                            'addDoubleLinear',
                            n=bnd.replace('_bnd',
                                          '_%s_%s_adl' % (eachChannel, pivot)))
                        dmNd.attr('o' + eachChannel) >> adl.input1
                        adl.input2.set(-1)
                        adl.output >> mdl.input1
                    else:
                        dmNd.attr('o' + eachChannel) >> mdl.input1

                    bnd.attr(pivot.nodeName() + '_weight_' +
                             eachChannel) >> mdl.input2

                    if eachChannel in ['sx', 'sy', 'sz']:
                        adl = pm.createNode(
                            'addDoubleLinear',
                            n=bnd.replace('_bnd',
                                          '_%s_%s_adl' % (eachChannel, pivot)))
                        mdl.output >> adl.input1
                        adl.input2.set(1)
                        adl.output >> zeroGrp.attr(eachChannel)
                    else:
                        mdl.output >> zeroGrp.attr(eachChannel)
Example #24
0
def orientSegment(limbJoints, posTemplateObjects, orientation):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Basic limb skeletonizer
    
    ARGUMENTS:
    limbJoints(list)
    templeateObjects(list)
    orientation(string) - ['xyz','yzx','zxy','xzy','yxz','zyx']
    
    RETURNS:
    limbJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ orientation vectors"""
    orientationVectors = search.returnAimUpOutVectorsFromOrientation(
        orientation)
    wantedAimVector = orientationVectors[0]
    wantedUpVector = orientationVectors[1]
    """put objects in order of closeness to root"""
    limbJoints = distance.returnDistanceSortedList(limbJoints[0], limbJoints)

    #>>> Segment our joint list by names
    jointSegmentsList = []
    cullList = []
    """ gonna be culling items from the list so need to rebuild it, just doing a list1 = list2 
    somehow keeps the relationship....odd """
    for obj in limbJoints:
        cullList.append(obj)

    while len(cullList) > 0:
        matchTerm = search.returnTagInfo(cullList[0], 'cgmName')
        objSet = search.returnMatchedTagsFromObjectList(
            cullList, 'cgmName', matchTerm)
        jointSegmentsList.append(objSet)
        for obj in objSet:
            cullList.remove(obj)

    #>>> get our orientation helpers
    helperObjects = []
    for obj in posTemplateObjects:
        templateObj = attributes.returnMessageObject(obj, 'cgmName')
        helperObjects.append(
            attributes.returnMessageObject(templateObj, 'orientHelper'))

    #>>> un parenting the chain
    for joint in limbJoints[1:]:
        mc.parent(joint, world=True)

    #>>>per segment stuff
    cnt = 0
    for segment in jointSegmentsList:
        if len(segment) > 1:
            """ creat our up object from from the helper object """
            helperObjectCurvesShapes = mc.listRelatives(helperObjects[cnt],
                                                        shapes=True)
            upLoc = locators.locMeCvFromCvIndex(helperObjectCurvesShapes[0],
                                                30)
            print upLoc
            """ make a pair list"""
            pairList = lists.parseListToPairs(segment)
            for pair in pairList:
                """ set up constraints """
                constraintBuffer = mc.aimConstraint(pair[1],
                                                    pair[0],
                                                    maintainOffset=False,
                                                    weight=1,
                                                    aimVector=wantedAimVector,
                                                    upVector=wantedUpVector,
                                                    worldUpVector=[0, 1, 0],
                                                    worldUpObject=upLoc,
                                                    worldUpType='object')
                mc.delete(constraintBuffer[0])
            for obj in segment[-1:]:
                constraintBuffer = mc.orientConstraint(segment[-2],
                                                       obj,
                                                       maintainOffset=False,
                                                       weight=1)
                mc.delete(constraintBuffer[0])
            """ increment and delete the up loc """
            cnt += 1
            mc.delete(upLoc)
        else:
            helperObjectCurvesShapes = mc.listRelatives(helperObjects[cnt],
                                                        shapes=True)
            upLoc = locators.locMeCvFromCvIndex(helperObjectCurvesShapes[0],
                                                30)
            """ make an aim object """
            aimLoc = locators.locMeObject(helperObjects[cnt])
            aimLocGroup = rigging.groupMeObject(aimLoc)
            mc.move(10, 0, 0, aimLoc, localSpace=True)
            constraintBuffer = mc.aimConstraint(aimLoc,
                                                segment[0],
                                                maintainOffset=False,
                                                weight=1,
                                                aimVector=wantedAimVector,
                                                upVector=wantedUpVector,
                                                worldUpVector=[0, 1, 0],
                                                worldUpObject=upLoc,
                                                worldUpType='object')
            mc.delete(constraintBuffer[0])
            mc.delete(aimLocGroup)
            mc.delete(upLoc)
            cnt += 1
    #>>>reconnect the joints
    pairList = lists.parseListToPairs(limbJoints)
    for pair in pairList:
        mc.parent(pair[1], pair[0])
    """ Freeze the rotations """
    mc.makeIdentity(limbJoints[0], apply=True, r=True)
    return limbJoints
Example #25
0
	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}  
 
def createMeshSliceCurve(mesh, mi_obj,latheAxis = 'z',aimAxis = 'y+',
                         points = 12, curveDegree = 3, minRotate = None, maxRotate = None, rotateRange = None,
                         posOffset = 0, markHits = False,rotateBank = None, closedCurve = True, maxDistance = 1000,
                         initialRotate = 0, offsetMode = 'vector', midMeshCast = False,
Example #26
0
def attachAimedObjectToSurface (obj, surface, aimObject, parent = True):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Script to rename a joint chain list
    
    ARGUMENTS:
    jointList(list) - list of joints in order
    startJointName(string) - what you want the root named
    interiorJointRootName(string) - what you want the iterative name to be
    
    RETURNS:
    newJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    
    """ Make a transform group """
    surfaceLoc = locators.locMeClosestUVOnSurface(obj,surface)
    surfaceFollowGroup = rigging.groupMeObject(surfaceLoc,False)
    transformGroup = rigging.groupMeObject(obj,False)
    
    surfaceFollowGroup = mc.rename(surfaceFollowGroup,(obj+'_surfaceFollowGroup'))
    attributes.storeInfo(surfaceFollowGroup,'object',obj)  
    
    transformGroup = mc.rename(transformGroup,(obj+'_surfaceFollowTransformGroup'))
    attributes.storeInfo(transformGroup,'object',obj) 
    
    
    controlSurface = mc.listRelatives(surface,shapes=True)
    
    """ make the node """
    closestPointNode = mc.createNode ('closestPointOnSurface',name= (obj+'_closestPointInfoNode'))
    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((surfaceLoc+'.translate'),(closestPointNode+'.inPosition'))
    attributes.doConnectAttr((controlSurface[0]+'.worldSpace'),(closestPointNode+'.inputSurface'))
    
    pointOnSurfaceNode = mc.createNode ('pointOnSurfaceInfo',name= (obj+'_posInfoNode'))
    """ Connect the info node to the surface """                  
    attributes.doConnectAttr  ((controlSurface[0]+'.worldSpace'),(pointOnSurfaceNode+'.inputSurface'))
    """ Contect the pos group to the info node"""
    attributes.doConnectAttr ((pointOnSurfaceNode+'.position'),(surfaceFollowGroup+'.translate'))
    attributes.doConnectAttr ((closestPointNode+'.parameterU'),(pointOnSurfaceNode+'.parameterU'))
    attributes.doConnectAttr  ((closestPointNode+'.parameterV'),(pointOnSurfaceNode+'.parameterV'))

    """ if we wanna aim """
    if aimObject != False: 
        """ make some locs """
        upLoc = locators.locMeObject(surface)
        aimLoc = locators.locMeObject(aimObject)
        attributes.storeInfo(upLoc,'cgmName',obj)
        attributes.storeInfo(upLoc,'cgmTypeModifier','up')
        upLoc = NameFactoryOld.doNameObject(upLoc)
        
        attributes.storeInfo(aimLoc,'cgmName',aimObject)
        attributes.storeInfo(aimLoc,'cgmTypeModifier','aim')
        aimLoc = NameFactoryOld.doNameObject(aimLoc)

        attributes.storeInfo(surfaceFollowGroup,'locatorUp',upLoc)
        attributes.storeInfo(surfaceFollowGroup,'aimLoc',aimLoc)
        #mc.parent(upLoc,aimObject)
        
        boundingBoxSize = distance.returnBoundingBoxSize(surface)
        distance = max(boundingBoxSize)*2
        
        mc.xform(upLoc,t = [0,distance,0],ws=True,r=True)
        
        attributes.doConnectAttr((aimLoc+'.translate'),(closestPointNode+'.inPosition'))

        """ constrain the aim loc to the aim object """
        pointConstraintBuffer = mc.pointConstraint(aimObject,aimLoc,maintainOffset = True, weight = 1)
        
        """ aim it """
        aimConstraintBuffer = mc.aimConstraint(aimLoc,surfaceFollowGroup,maintainOffset = True, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpObject = upLoc, worldUpType = 'object' )

        """ aim the controller back at the obj"""
        aimConstraintBuffer = mc.aimConstraint(obj,aimLoc,maintainOffset = True, weight = 1, aimVector = [0,0,-1], upVector = [0,1,0], worldUpObject = upLoc, worldUpType = 'object' )
        
        mc.parent(upLoc,aimObject)
    else:
        mc.delete(closestPointNode)
    
    transformGroup = rigging.doParentReturnName(transformGroup,surfaceFollowGroup)
    """finally parent it"""    
    if parent == True:
        mc.parent(obj,transformGroup)
        
    if parent == 'constrain':
        mc.parentConstraint(transformGroup,obj,maintainOffset = True)
    
    mc.delete(surfaceLoc)
    return [transformGroup,surfaceFollowGroup]
Example #27
0
    def doTemplate(self,PuppetInstance):       
        """
        
        """
        def makeLimbTemplate (self):
            #>>>Curve degree finder
            if self.optionCurveDegree.get() == 0:
                doCurveDegree = 1
            else:
                if len(corePositionList) <= 3:
                    doCurveDegree = 1
                else:
                    doCurveDegree = len(corePositionList) - 1
                    
            #Make some storage vehicles
            self.templatePosObjectsBuffer = BufferFactory(self.infoNulls['templatePosObjects'].get())
            self.templatePosObjectsBuffer.purge()
            
            LocatorCatcher = ObjectFactory('')
            LocatorBuffer = BufferFactory(LocatorCatcher.nameLong)
            LocatorBuffer.purge()
            
            returnList = []
            self.templHandleList = []
            
            moduleColors = modules.returnModuleColors(self.ModuleNull.nameShort)
            
            #>>>Scale stuff
            moduleParent = self.msgModuleParent.get()
            
            if not moduleParent:
                length = (distance.returnDistanceBetweenPoints (corePositionList[0],corePositionList[-1]))
                size = length / self.optionHandles.get()
            else:
                #>>>>>>>>>>>>>>>>>>>>> NOT TOUCHED YET
                parentTemplatePosObjectsInfoNull = modules.returnInfoTypeNull(moduleParent,'templatePosObjects')
                parentTemplatePosObjectsInfoData = attributes.returnUserAttrsToDict (parentTemplatePosObjectsInfoNull)
                parentTemplateObjects = []
                for key in parentTemplatePosObjectsInfoData.keys():
                    if (mc.attributeQuery (key,node=parentTemplatePosObjectsInfoNull,msg=True)) == True:
                        if search.returnTagInfo((parentTemplatePosObjectsInfoData[key]),'cgmType') != 'templateCurve':
                            parentTemplateObjects.append (parentTemplatePosObjectsInfoData[key])
                createBuffer = curves.createControlCurve('sphere',1)
                pos = corePositionList[0]
                mc.move (pos[0], pos[1], pos[2], createBuffer, a=True)
                closestParentObject = distance.returnClosestObject(createBuffer,parentTemplateObjects)
                boundingBoxSize = distance.returnBoundingBoxSize (closestParentObject)
                maxSize = max(boundingBoxSize)
                size = maxSize *.25
                mc.delete(createBuffer)
                if partType == 'clavicle':
                    size = size * .5
                elif partType == 'head':
                    size = size * .75
                if (search.returnTagInfo(moduleParent,'cgmModuleType')) == 'clavicle':
                    size = size * 2
        
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            # Making the template objects
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            self.TemplateObject = {}
            
            #>>> Template objects
            for cnt,pos in enumerate(corePositionList):
                #Size multiplier based on PuppetMode, make it take into account module mode eventually
                if PuppetInstance.optionPuppetMode.get() == 0:
                    if cnt == 0:
                        sizeMultiplier = 1
                    elif cnt == len(corePositionList) -1:
                        sizeMultiplier = .8
                    else:
                        sizeMultiplier = .5
                else:
                    sizeMultiplier = 1
                    
                #make a sphere and move it
                createBuffer = curves.createControlCurve('sphere',(size * sizeMultiplier))
                self.TemplateObject[cnt] = ObjectFactory(createBuffer) # Instance the control to our module
                obj = self.TemplateObject[cnt]
                curves.setCurveColorByName(obj.nameLong,moduleColors[0])
                obj.store('cgmName',coreNames[cnt])
                
                obj.getNameTagsFromObject(self.ModuleNull.nameLong,['cgmName','cgmType'])

                obj.store('cgmType','templateObject')
                obj.doName()
                mc.move (pos[0], pos[1], pos[2], [obj.nameLong], a=True)
                            
                #adds it to the list
                self.templHandleList.append (obj.nameLong) 
                self.templatePosObjectsBuffer.store(obj.nameLong)
            
             
            #Aim the objects           
            position.aimObjects(self.templHandleList,
                                dictionary.axisDirectionsByString[ self.optionAimAxis.get() ],
                                dictionary.axisDirectionsByString[ self.optionUpAxis.get() ],
                                dictionary.axisDirectionsByString[ PuppetInstance.optionUpAxis.get() ])            
            
            #>>> Template curve
            crvName = mc.curve (d=doCurveDegree, p = corePositionList , os=True, n=('%s_%s' %(partName,(typesDictionary.get('templateCurve')))))            
            self.afTemplateCurve = AttrFactory(self.infoNulls['templatePosObjects'].get(),
                                               'curve','message', value=crvName)# connect it back to our template objects info null
            
            curve = ObjectFactory(crvName) # instance it
            curve.getNameTagsFromObject(self.ModuleNull.nameLong,['cgmType']) #get name tags from the module

            attributes.storeInfo(crvName,'cgmType','templateCurve') # store type
            curves.setCurveColorByName(crvName,moduleColors[1]) # set curve color
            
            # Make locators to connect the cv's to
            for cnt,obj in enumerate(self.templHandleList):
                pointLoc = locators.locMeObject(obj) # make the loc
                loc = ObjectFactory(pointLoc) #instance it
                mc.setAttr ((loc.nameShort+'.visibility'),0) # turn off visibility
                mc.parentConstraint ([obj],[loc.nameShort],mo=False) # parent constrain
                mc.connectAttr ( (loc.nameShort+'.translate'),
                                 ('%s.controlPoints[%i]' % (crvName, cnt)), f=True ) # connect the cv to the loc
                self.TemplateObject[cnt].store('loc',loc.nameLong)
                LocatorBuffer.store(loc.nameLong)
                
            #>>> Direction and size Stuff
            """
            # Directional data derived from joints 
            generalDirection = logic.returnHorizontalOrVertical(self.templHandleList)
            if generalDirection == 'vertical' and 'leg' not in self.afModuleType.get():
                worldUpVector = [0,0,-1]
            elif generalDirection == 'vertical' and 'leg' in self.afModuleType.get():
                worldUpVector = [0,0,1]
            else:
                worldUpVector = [0,1,0]
            """            
            
            # Create root control
            templateNull = self.msgTemplateNull.get()
            handleList = copy.copy(self.templatePosObjectsBuffer.bufferList)
            
            rootSize = (distance.returnBoundingBoxSizeToAverage(self.templHandleList[0])*1.5)
            rootCtrl = ObjectFactory(curves.createControlCurve('cube',rootSize))
            rootCtrl.getNameTagsFromObject(self.ModuleNull.nameLong)
            self.msgTemplateRoot = AttrFactory(self.infoNulls['templatePosObjects'].get(), 'root', 'message', value = rootCtrl.nameLong)
            curves.setCurveColorByName(rootCtrl.nameLong,moduleColors[0])
            
            # move the root
            if self.afModuleType.get() == 'clavicle':
                position.movePointSnap(rootCtrl.nameLong,self.templHandleList[0])
            else:
                position.movePointSnap(rootCtrl.nameLong,self.templHandleList[0])
            # aim the root
            position.aimSnap(rootCtrl.nameShort,self.templHandleList[-1],  
                            dictionary.axisDirectionsByString[ self.optionAimAxis.get() ],
                            dictionary.axisDirectionsByString[ self.optionUpAxis.get() ],
                            dictionary.axisDirectionsByString[ PuppetInstance.optionUpAxis.get() ]) 
            
            rootCtrl.store('cgmType','templateRoot')
            rootCtrl.doName()
            
            #>>> Parent the main objcts
            rootGroup = rootCtrl.doGroup()
            rootGroup = rigging.doParentReturnName(rootGroup,templateNull)
            curve.doParent(templateNull)
            
            for obj in LocatorBuffer.bufferList:
                rigging.doParentReturnName(obj,templateNull)
            mc.delete(LocatorCatcher.nameShort) # delete the locator buffer obj
            
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Orientation helpers
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            # Make our Orientation Helpers 
            """
            orientHelpersReturn = template.addOrientationHelpers(self)
            masterOrient = orientHelpersReturn[0]
            orientObjects = orientHelpersReturn[1]
            return
            
        
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Control helpers
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            print orientObjects
            print self.ModuleNull.nameShort
            print (templateNull+'.visControlHelpers')
            controlHelpersReturn = addControlHelpers(orientObjects,self.ModuleNull.nameShort,(templateNull+'.visControlHelpers'))"""
    
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Input the saved values if there are any
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            # Orientation Helpers 
            """rotBuffer = coreRotationList[-1]
            #actualName = mc.spaceLocator (n= wantedName)
            rotCheck = sum(rotBuffer)
            if rotCheck != 0:
                mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],masterOrient,os=True)
            
            cnt = 0
            for obj in orientObjects:
                rotBuffer = coreRotationList[cnt]
                rotCheck = sum(rotBuffer)
                if rotCheck != 0:
                    mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],obj,os=True)
                cnt +=1 
                    
            # Control Helpers 
            controlHelpers = controlHelpersReturn[0]
            cnt = 0
            for obj in controlHelpers:
                posBuffer = controlPositionList[cnt]
                posCheck = sum(posBuffer)
                if posCheck != 0:
                    mc.xform(obj,t=[posBuffer[0],posBuffer[1],posBuffer[2]],ws=True)
                
                rotBuffer = controlRotationList[cnt]
                rotCheck = sum(rotBuffer)
                if rotCheck != 0:
                    mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],obj,ws=True)
                
                scaleBuffer = controlScaleList[cnt]
                scaleCheck = sum(scaleBuffer)
                if scaleCheck != 0:
                    mc.scale(scaleBuffer[0],scaleBuffer[1],scaleBuffer[2],obj,absolute=True)
                cnt +=1 """
            
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Final stuff
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            """
            returnList.append(templObjNameList)
            returnList.append(self.templHandleList)
            returnList.append(rootCtrl)"""
            return True	



        # Start objects stuff 
        partName = NameFactory.returnRawGeneratedName(self.ModuleNull.nameShort,ignore=['cgmType','cgmTypeModifier'])
        templateStarterDataInfoNull = self.infoNulls['templateStarterData'].value
        initialObjectsPosData = mc.listAttr(templateStarterDataInfoNull,userDefined=True)
        corePositionList = []
        coreRotationList = []
        corePositionDict = {}
        coreRotationDict = {}        
        for a in initialObjectsPosData:
            buffer = attributes.doGetAttr(templateStarterDataInfoNull,a)                            
            if 'cgm' not in a and type(buffer) is list:
                if 'pos' in a:
                    split = a.split('pos_')
                    corePositionDict[int(split[1])] =  buffer[0]
                    corePositionList.append(buffer[0])
                elif 'rot' in a:
                    split = a.split('rot_')
                    coreRotationDict[int(split[1])] =  buffer[0] 
                    coreRotationList.append(buffer[0])
   
        print corePositionList
        print coreRotationList
        
        # template control objects stuff #
        templateControlObjectsDataNull = self.infoNulls['templateControlObjects'].value
        templateControlObjectsData = mc.listAttr(templateControlObjectsDataNull,userDefined=True)
        controlPositionList = []
        controlRotationList = []
        controlScaleList = []
        controlPositionDict = {}
        controlRotationDict = {}
        controlScaleDict = {}
        
        for a in templateControlObjectsData:
            buffer = attributes.doGetAttr(templateControlObjectsDataNull,a)                            
            if 'cgm' not in a and type(buffer) is list:
                if 'pos' in a:
                    split = a.split('pos_')
                    controlPositionDict[int(split[1])] =  buffer[0] 
                    controlPositionList.append(buffer[0])                    
                elif 'rot' in a:
                    split = a.split('rot_')
                    controlRotationDict[int(split[1])] =  buffer[0] 
                    controlRotationList.append(buffer[0])
                elif 'scale' in a:
                    split = a.split('scale_')
                    controlScaleDict[int(split[1])] =  buffer[0]   
                    controlScaleList.append(buffer[0])
                    
                  
        print controlPositionList
        print controlRotationList
        print controlScaleList
        
        # Names Info #
        coreNamesInfoNull = self.infoNulls['coreNames'].value
        coreNamesBuffer = mc.listAttr(coreNamesInfoNull,userDefined=True)
        coreNames = {}
        for a in coreNamesBuffer:
            if 'cgm' not in a and 'name_' in a:
                split = a.split('name_')
                coreNames[int(split[1])] =  attributes.doGetAttr(coreNamesInfoNull,a) 
                
        print coreNames            
        print ('%s data aquired...'%self.ModuleNull.nameShort)
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> make template objects
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
        #makes template objects#
        assert len(corePositionList) == self.optionHandles.get(),"There isn't enough data to template. Needs to be sized"
        
        templateObjects = makeLimbTemplate(self)
        guiFactory.report( 'Template Limb made....')
        
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> Parent objects
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
        for cnt,obj in enumerate(self.templHandleList): 
            self.TemplateObject[cnt].doParent(self.msgTemplateNull.get())
    
        guiFactory.report('Template objects parented')
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> Transform groups and Handles...handling
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        self.templatePosObjectsBuffer.updateData()
        root = self.msgTemplateRoot.get()
        handles = copy.copy( self.templatePosObjectsBuffer.bufferList )
        stiffIndex = self.optionStiffIndex.get()
        
        """ Don't remember why I did this stiff index thing....
        #>>> Break up the handles into the sets we need 
        if stiffIndex == 0:
            splitHandles = False
            handlesToSplit = handles
            handlesRemaining = [handles[0],handles[-1]]
        elif stiffIndex < 0:
            splitHandles = True
            handlesToSplit = handles[:stiffIndex]
            handlesRemaining = handles[stiffIndex:]
            handlesRemaining.append(handles[0])
        elif stiffIndex > 0:
            splitHandles = True
            handlesToSplit = handles[stiffIndex:]
            handlesRemaining = handles[:stiffIndex]
            handlesRemaining.append(handles[-1]) 
        if len(handlesToSplit)>2:"""
        
        # makes our mid transform groups#
        if len(handles)>2:
            constraintGroups = constraints.doLimbSegmentListParentConstraint(handles)
            print 'Constraint groups created...'
            for group in constraintGroups:
                mc.parent(group,root)
            
        # zero out the first and last#
        for handle in [handles[0],handles[-1]]:
            groupBuffer = (rigging.groupMeObject(handle,maintainParent=True))
            mc.parent(groupBuffer,root)
           
        #>>> Break up the handles into the sets we need 
        if stiffIndex < 0:
            for handle in handles[(stiffIndex+-1):-1]:
                groupBuffer = (rigging.groupMeObject(handle,maintainParent=True))
                mc.parent(groupBuffer,handles[-1])
        elif stiffIndex > 0:
            for handle in handles[1:(stiffIndex+1)]:
                groupBuffer = (rigging.groupMeObject(handle,maintainParent=True))
                mc.parent(groupBuffer,handles[0])
                
        print 'Constraint groups parented...'
        
        #>>> Lock off handles
        self.templatePosObjectsBuffer.updateData()
        for obj in self.templatePosObjectsBuffer.bufferList:
            attributes.doSetLockHideKeyableAttr(obj,True,False,False,['sx','sy','sz','v'])
            
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Parenting constraining parts
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        """ COME BACK AFTER DONE WITH SEGMENT
        if self.moduleParent:
            if self.afModuleType.get() == 'clavicle':
                self.moduleParent = attributes.returnMessageObject(self.moduleParent,'self.moduleParent')
            parentTemplatePosObjectsInfoNull = modules.returnInfoTypeNull(self.moduleParent,'templatePosObjects')
            parentTemplatePosObjectsInfoData = attributes.returnUserAttrsToDict (parentTemplatePosObjectsInfoNull)
            parentTemplateObjects = []
            for key in parentTemplatePosObjectsInfoData.keys():
                if (mc.attributeQuery (key,node=parentTemplatePosObjectsInfoNull,msg=True)) == True:
                    if search.returnTagInfo((parentTemplatePosObjectsInfoData[key]),'cgmType') != 'templateCurve':
                        parentTemplateObjects.append (parentTemplatePosObjectsInfoData[key])
            closestParentObject = distance.returnClosestObject(rootName,parentTemplateObjects)
            if (search.returnTagInfo(self.ModuleNull.nameShort,'cgmModuleType')) != 'foot':
                constraintGroup = rigging.groupMeObject(rootName,maintainParent=True)
                constraintGroup = NameFactory.doNameObject(constraintGroup)
                mc.pointConstraint(closestParentObject,constraintGroup, maintainOffset=True)
                mc.scaleConstraint(closestParentObject,constraintGroup, maintainOffset=True)
            else:
                constraintGroup = rigging.groupMeObject(closestParentObject,maintainParent=True)
                constraintGroup = NameFactory.doNameObject(constraintGroup)
                mc.parentConstraint(rootName,constraintGroup, maintainOffset=True)
                
        # grab the last clavicle piece if the arm has one and connect it to the arm  #
        if self.moduleParent:
            if (search.returnTagInfo(self.ModuleNull.nameShort,'cgmModuleType')) == 'arm':
                if (search.returnTagInfo(self.moduleParent,'cgmModuleType')) == 'clavicle':
                    print '>>>>>>>>>>>>>>>>>>>>> YOU FOUND ME'
                    parentTemplatePosObjectsInfoNull = modules.returnInfoTypeNull(self.moduleParent,'templatePosObjects')
                    parentTemplatePosObjectsInfoData = attributes.returnUserAttrsToDict (parentTemplatePosObjectsInfoNull)
                    parentTemplateObjects = []
                    for key in parentTemplatePosObjectsInfoData.keys():
                        if (mc.attributeQuery (key,node=parentTemplatePosObjectsInfoNull,msg=True)) == True:
                            if search.returnTagInfo((parentTemplatePosObjectsInfoData[key]),'cgmType') != 'templateCurve':
                                parentTemplateObjects.append (parentTemplatePosObjectsInfoData[key])
                    closestParentObject = distance.returnClosestObject(rootName,parentTemplateObjects)
                    endConstraintGroup = rigging.groupMeObject(closestParentObject,maintainParent=True)
                    endConstraintGroup = NameFactory.doNameObject(endConstraintGroup)
                    mc.pointConstraint(handles[0],endConstraintGroup, maintainOffset=True)
                    mc.scaleConstraint(handles[0],endConstraintGroup, maintainOffset=True)
        """    
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> Final stuff
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
        
        #>>> Set our new module rig process state
        self.afTemplateState.set(1)
        print ('%s done!'%self.ModuleNull.nameShort)
        
        #>>> Tag our objects for easy deletion
        children = mc.listRelatives (self.msgTemplateNull.get(), allDescendents = True,type='transform')
        for obj in children:
            attributes.storeInfo(obj,'cgmOwnedBy',self.msgTemplateNull.get())
            
        #>>> Visibility Connection
        """
Example #28
0
def doPointAimConstraintObjectGroup(targets, object, mode=0):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    ACKNOWLEDGEMENT:
    Idea for this stype of constraint setup is from http://td-matt.blogspot.com/2011/01/spine-control-rig.html
    
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list) - should be in format of from to back with the last one being the aim object
    object(string)
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    returnList = []
    """ figure out which is the aim direction  """
    aimVector = logic.returnLocalAimDirection(object, targets[-1])
    upVector = logic.returnLocalUp(aimVector)
    """ create locators """
    locs = []
    toMake = ['point', 'aim', 'up']
    for type in toMake:
        locBuffer = locators.locMeObject(object)
        attributes.storeInfo(locBuffer, 'cgmName', object)
        attributes.storeInfo(locBuffer, 'cgmTypeModifier', type)
        locs.append(NameFactory.doNameObject(locBuffer))

    pointLoc = locs[0]
    aimLoc = locs[1]
    upLoc = locs[2]
    """ move the locators """
    mc.xform(aimLoc, t=aimVector, r=True, os=True)
    mc.xform(upLoc, t=upVector, r=True, os=True)
    """group constraint"""
    objGroup = rigging.groupMeObject(object, True, True)
    attributes.storeInfo(objGroup, 'cgmName', object)
    attributes.storeInfo(objGroup, 'cgmTypeModifier', 'follow')
    objGroup = NameFactory.doNameObject(objGroup)

    pointConstraintBuffer = mc.pointConstraint(pointLoc,
                                               objGroup,
                                               maintainOffset=False)
    aimConstraintBuffer = mc.aimConstraint(aimLoc,
                                           objGroup,
                                           maintainOffset=False,
                                           weight=1,
                                           aimVector=aimVector,
                                           upVector=upVector,
                                           worldUpObject=upLoc,
                                           worldUpType='object')
    """loc constraints"""
    locConstraints = []
    for loc in locs:
        parentConstraintBuffer = mc.parentConstraint(targets,
                                                     loc,
                                                     maintainOffset=True)
        locConstraints.append(parentConstraintBuffer[0])

    if mode == 1:
        distances = []
        for target in targets:
            distances.append(
                distance.returnDistanceBetweenObjects(target, objGroup))
        normalizedDistances = cgmMath.normList(distances)
        for constraint in locConstraints:
            targetWeights = mc.parentConstraint(constraint,
                                                q=True,
                                                weightAliasList=True)
            cnt = 1
            for value in normalizedDistances:
                mc.setAttr(('%s%s%s' % (constraint, '.', targetWeights[cnt])),
                           value)
                cnt -= 1

    returnList.append(objGroup)
    returnList.append(locs)
    return returnList
Example #29
0
def doConstraintObjectGroup(targets,
                            obj=False,
                            constraintTypes=[],
                            group=False,
                            mode=0):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list)
    object(string)
    constraintTypes(list)
    group(string) -- whether to pass a group through
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    log.debug(">>> doConstraintObjectGroup")
    log.info("targets: %s" % str(targets))
    log.debug("obj: %s" % str(obj))
    log.info("constraintTypes: %s" % str(constraintTypes))
    log.debug("group: %s" % str(group))
    log.debug("mode: %s" % str(mode))
    if targets and not type(targets) == list:
        targets = [targets]  #thanks Mark, for this syntax
    if constraintTypes and not type(constraintTypes) == list:
        constraintTypes = [constraintTypes]

    normalizedDistances = False
    if not obj and not group:
        log.warning("Must have a obj or a group")
        return False
    if group and mc.objExists(group):
        objGroup = group
    elif obj:
        objGroup = rigging.groupMeObject(obj, True, True)
    else:
        log.warning("Not enough info")
        return False

    for c in constraintTypes:
        constraint = False
        if mode == 1:
            distances = []
            for target in targets:
                distances.append(
                    distance.returnDistanceBetweenObjects(target, objGroup))
            normalizedDistances = cgmMath.normList(distances)
        if c == 'point':
            constraint = mc.pointConstraint(targets,
                                            objGroup,
                                            maintainOffset=True)
            targetWeights = mc.pointConstraint(constraint,
                                               q=True,
                                               weightAliasList=True)
        if c == 'parent':
            constraint = mc.parentConstraint(targets,
                                             objGroup,
                                             maintainOffset=True)
            targetWeights = mc.parentConstraint(constraint,
                                                q=True,
                                                weightAliasList=True)
        if c == 'orient':
            constraint = mc.orientConstraint(targets,
                                             objGroup,
                                             maintainOffset=True)
            targetWeights = mc.orientConstraint(constraint,
                                                q=True,
                                                weightAliasList=True)
        if c == 'scale':
            constraint = mc.scaleConstraint(targets,
                                            objGroup,
                                            maintainOffset=True)
            targetWeights = mc.scaleConstraint(constraint,
                                               q=True,
                                               weightAliasList=True)
        if constraint:
            try:
                mc.setAttr("%s.interpType" % constraint[0], 0)  #Set to no flip
            except:
                pass
            if normalizedDistances:
                for cnt, value in enumerate(normalizedDistances):
                    mc.setAttr(
                        ('%s%s%s' % (constraint[0], '.', targetWeights[cnt])),
                        value)
    return objGroup
Example #30
0
def returnAbsoluteSizeCurve(curve):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass an curve into it and it returns absolute distance scale

    ARGUMENTS:
    curve(string) - curve

    RETURNS:
    distances(list) - [xLength,yLength,zLength]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    def duplicateShape(shape):
        parentObj = mc.listRelatives(shape, p=True, fullPath=True)
        shapes = mc.listRelatives(parentObj, shapes=True, fullPath=True)
        matchObjName = mc.ls(shape, long=True)
        matchIndex = shapes.index(matchObjName[0])

        dupBuffer = mc.duplicate(parentObj)
        children = mc.listRelatives(dupBuffer[0], children = True, fullPath =True)
        if len(children) > 0:
            for c in children:
                if search.returnObjectType(c) != 'shape':
                    mc.delete(c)

        dupShapes = mc.listRelatives(dupBuffer[0], shapes=True, fullPath=True)
        for shape in dupShapes:
            if dupShapes.index(shape) != matchIndex:
                mc.delete(shape)
                return dupBuffer[0]


    boundingBoxSize = returnBoundingBoxSize(curve)
    if mayaVersion <=2010:
        return boundingBoxSize
    else:
        distanceToMove = max(boundingBoxSize)
        positions = []
        isShape = False
        if search.returnObjectType(curve) == 'shape':
            dupCurve = duplicateShape(curve)
            curve = dupCurve
            isShape = True

        loc = rigging.locMeObjectStandAlone(curve)
        locGroup = rigging.groupMeObject(loc,False)
        loc = rigging.doParentReturnName(loc,locGroup)
        directions = ['x','y','z']
        for direction in directions:
            positionsBuffer = []
            mc.setAttr((loc+'.t'+direction),distanceToMove)
            positionsBuffer.append(returnClosestUPosition(loc,curve))
            mc.setAttr((loc+'.t'+direction),-distanceToMove)
            positionsBuffer.append(returnClosestUPosition(loc,curve))
            mc.setAttr((loc+'.t'+direction),0)
            positions.append(positionsBuffer)

        distances = []
        for set in positions:
            distances.append(returnDistanceBetweenPoints(set[0],set[1]))

        if isShape == True:
            mc.delete(dupCurve)

        mc.delete(locGroup)
        return distances
Example #31
0
def returnAbsoluteSizeCurve(curve):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass an curve into it and it returns absolute distance scale

    ARGUMENTS:
    curve(string) - curve

    RETURNS:
    distances(list) - [xLength,yLength,zLength]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    def duplicateShape(shape):
        parentObj = mc.listRelatives(shape, p=True, fullPath=True)
        shapes = mc.listRelatives(parentObj, shapes=True, fullPath=True)
        matchObjName = mc.ls(shape, long=True)
        matchIndex = shapes.index(matchObjName[0])

        dupBuffer = mc.duplicate(parentObj)
        children = mc.listRelatives(dupBuffer[0], children = True, fullPath =True)
        if len(children) > 0:
            for c in children:
                if search.returnObjectType(c) != 'shape':
                    mc.delete(c)

        dupShapes = mc.listRelatives(dupBuffer[0], shapes=True, fullPath=True)
        for shape in dupShapes:
            if dupShapes.index(shape) != matchIndex:
                mc.delete(shape)
                return dupBuffer[0]


    boundingBoxSize = returnBoundingBoxSize(curve)
    if mayaVersion <=2010:
        return boundingBoxSize
    else:
        distanceToMove = max(boundingBoxSize)
        positions = []
        isShape = False
        if search.returnObjectType(curve) == 'shape':
            dupCurve = duplicateShape(curve)
            curve = dupCurve
            isShape = True

        loc = rigging.locMeObjectStandAlone(curve)
        locGroup = rigging.groupMeObject(loc,False)
        loc = rigging.doParentReturnName(loc,locGroup)
        directions = ['x','y','z']
        for direction in directions:
            positionsBuffer = []
            mc.setAttr((loc+'.t'+direction),distanceToMove)
            positionsBuffer.append(returnClosestUPosition(loc,curve))
            mc.setAttr((loc+'.t'+direction),-distanceToMove)
            positionsBuffer.append(returnClosestUPosition(loc,curve))
            mc.setAttr((loc+'.t'+direction),0)
            positions.append(positionsBuffer)

        distances = []
        for set in positions:
            distances.append(returnDistanceBetweenPoints(set[0],set[1]))

        if isShape == True:
            mc.delete(dupCurve)

        mc.delete(locGroup)
        return distances
Example #32
0
 def doCreateStartingPositionLoc(self, modeType='child', workingObject=None, aimingObject=None, cvIndex = None ):
     """ 
     >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
     DESCRIPTION:
     Adds a locator setup to duplicate to get our initial position locators. All should be zeroed out.
     The top node of the return group has the loctor and move group connected is message nodes if needed.
     
     ARGUMENTS:
     modeType(string)
         child - basic child locator to the workingObject
         innerChild - aims locator from the working to the aiming curves
         cvBack - works off working curves cvIndex. Places it and aiming
                     it back on z. Mainly used for tails
         radialOut - Works off working curve cv for position and radial 
                     orientation. It's transform group is oriented to 
                     the aiming curves equivalent cv. Good for arms
         radialDown - same as radial out but locator orientation is y down zup for legs.
                     transform orientation is the same as radial out
         footBase - looking for it's module Parent's last loc to start from
         parentDuplicate - looking for it's module Parent's last loc to start from
         
     workingObject(string) - usually the sizing objects start curve (can be a locator for parentchild loc)
     aimingObject(string) - usually the sizing objects end curve
     cvIndex(int) - cv to work off of
     
     RETURNS:
     returnList(list) = [rootHelper(string),helperObjects(list),helperObjectGroups(list)]
     >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
     """
     
     if modeType == 'child':
         """ make initial loc and orient it """
         returnLoc = []
         curveShapes = mc.listRelatives(workingObject, shapes = True)
         startLoc = locators.locMeObject(workingObject)
         aimLoc = locators.locMeObject(workingObject)
         upLoc = locators.locMeCvFromCvIndex(curveShapes[0],0)
         
         startLoc = mc.rename(startLoc,(self.ModuleNull.nameBase+'child_startLoc'))
         StartLoc = ObjectFactory(startLoc)
         
         sizeObjectLength = distance.returnDistanceBetweenObjects(workingObject,aimingObject)
         mc.xform(aimLoc,t=[0,0,sizeObjectLength],r=True,os=True)
         aimConstraintBuffer = mc.aimConstraint(aimLoc,startLoc,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpObject = upLoc, worldUpType = 'object' )
         mc.delete(aimConstraintBuffer[0])
         mc.delete(upLoc)
         mc.delete(aimLoc)
         
         zeroGroup = StartLoc.doGroup()
         returnLoc.append(StartLoc.nameLong)
         
         attributes.storeInfo(zeroGroup,'locator',startLoc)
         returnLoc.append(zeroGroup)
         
         return returnLoc
         
     elif modeType == 'innerChild':       
         """ make initial lock and orient it """
         returnLoc = []
         curveShapes = mc.listRelatives(workingObject, shapes = True)
         startLoc = locators.locMeObject(workingObject)
         aimLoc = locators.locMeObject(aimingObject)
         upLoc = locators.locMeCvFromCvIndex(curveShapes[0],0)
         startLoc = mc.rename(startLoc, (self.ModuleNull.nameBase+'_innerChild_startLoc'))
         StartLoc = ObjectFactory(startLoc)
         
         aimConstraintBuffer = mc.aimConstraint(aimLoc,startLoc,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpObject = upLoc, worldUpType = 'object' )
         mc.delete(aimConstraintBuffer[0])
         mc.delete(upLoc)
         mc.delete(aimLoc)
         
         zeroGroup = StartLoc.doGroup()  
         returnLoc.append(StartLoc.nameLong)
         
         #zeroGroup = rigging.zeroTransformMeObject(startLoc)
         #attributes.storeInfo(zeroGroup,'locator',startLoc)
         returnLoc.append(zeroGroup)
         
         return returnLoc
         
     elif  modeType == 'cvBack':
         returnLoc = []
         curveShapes = mc.listRelatives(workingObject, shapes = True)
         startLoc = locators.locMeCvFromCvIndex(curveShapes[0],cvIndex)
         upLoc = locators.locMeObject(workingObject)
         
         initialAimLoc = locators.locMeObject(aimingObject)
         aimConstraintBuffer = mc.aimConstraint(initialAimLoc,startLoc,maintainOffset = False, weight = 1, aimVector = [0,0,-1], upVector = [0,-1,0],  worldUpObject = upLoc, worldUpType = 'object', skip = ['x','z'])
         mc.delete(aimConstraintBuffer[0])
         mc.delete(initialAimLoc)
 
         aimLoc = locators.locMeCvFromCvIndex(curveShapes[0],cvIndex)
         startLoc = mc.rename(startLoc, (self.ModuleNull.nameBase+'_radialBackl_startLoc'))
         StartLoc = ObjectFactory(startLoc)
         
         sizeObjectLength = distance.returnDistanceBetweenObjects(workingObject,aimingObject)
         mc.xform(aimLoc,t=[0,0,-sizeObjectLength],r=True,ws=True)
         aimConstraintBuffer = mc.aimConstraint(aimLoc,startLoc,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpType = 'vector' )
         mc.delete(aimConstraintBuffer[0])
         mc.delete(aimLoc)
         mc.delete(upLoc)
         returnLoc.append(startLoc)
         zeroGroup = StartLoc.doGroup()  
         returnLoc.append(StartLoc.nameLong)
         
         return returnLoc
         
     elif  modeType == 'radialOut':
         sizeObjectLength = distance.returnDistanceBetweenObjects(workingObject,aimingObject)
         
         returnLoc = []
         
         workingObjectShapes = mc.listRelatives(workingObject, shapes = True)
         aimingObjectShapes = mc.listRelatives(aimingObject, shapes = True)
         
         """initial loc creation and orientation"""
         startLoc = locators.locMeCvFromCvIndex(workingObjectShapes[0],cvIndex)
         startLocAim = locators.locMeObject(workingObject)
         startLocUp = locators.locMeCvFromCvIndex(workingObjectShapes[0],cvIndex)
         startLoc = mc.rename(startLoc, (self.ModuleNull.nameBase+'_radialOut_startLoc'))
         StartLoc = ObjectFactory(startLoc)
         
         
         """ move the up loc up """
         mc.xform(startLocUp,t=[0,sizeObjectLength,0],r=True,ws=True)
 
         """ aim it """
         aimConstraintBuffer = mc.aimConstraint(startLocAim,startLoc,maintainOffset = False, weight = 1, aimVector = [0,0,-1], upVector = [0,1,0], worldUpType = 'vector' )
         mc.delete(aimConstraintBuffer[0])
         mc.delete(startLocUp)
         
         """ setup the transform group"""
         transformGroup = rigging.groupMeObject(startLoc,False)
         transformGroup = mc.rename(transformGroup,('%s%s' %(startLoc,'_moveGroup')))
         groupUp = startLocAim
         groupAim = locators.locMeCvFromCvIndex(aimingObjectShapes[0],cvIndex)
         
         """aim it"""
         aimConstraintBuffer = mc.aimConstraint(groupAim,transformGroup,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,-1,0],  worldUpObject = groupUp, worldUpType = 'object')
         mc.delete(aimConstraintBuffer[0])
         mc.delete(groupUp)
         mc.delete(groupAim)
         
         startLoc = rigging.doParentReturnName(startLoc,transformGroup)
         rigging.zeroTransformMeObject(startLoc)
         returnLoc.append(startLoc)
         returnLoc.append(transformGroup)
         zeroGroup = rigging.groupMeObject(transformGroup)
         attributes.storeInfo(zeroGroup,'move',transformGroup)
         returnLoc.append(zeroGroup)
         
         return returnLoc
         
     elif  modeType == 'radialDown':
         sizeObjectLength = distance.returnDistanceBetweenObjects(workingObject,aimingObject)
         returnLoc = []
         
         workingObjectShapes = mc.listRelatives(workingObject, shapes = True)
         aimingObjectShapes = mc.listRelatives(aimingObject, shapes = True)
         
         """initial loc creation and orientation"""
         startLoc = locators.locMeCvFromCvIndex(workingObjectShapes[0],cvIndex)
         startLocAim = locators.locMeCvFromCvIndex(workingObjectShapes[0],cvIndex)
         startLoc = mc.rename(startLoc, (self.ModuleNull.nameBase+'_radialDown_startLoc'))
         StartLoc = ObjectFactory(startLoc)
         
         """ move the up loc up """
         mc.xform(startLocAim,t=[0,-sizeObjectLength,0],r=True, ws=True)
         
         """ aim it """
         aimConstraintBuffer = mc.aimConstraint(startLocAim,startLoc,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,0,1], worldUpType = 'vector' )
         mc.delete(aimConstraintBuffer[0])
         
         
         """ setup the transform group"""
         transformGroup = rigging.groupMeObject(startLoc,False)
         transformGroup = mc.rename(transformGroup,('%s%s' %(startLoc,'_moveGroup')))
         groupUp = startLocAim
         groupAim = locators.locMeCvFromCvIndex(aimingObjectShapes[0],cvIndex)
         
         """aim it"""
         aimConstraintBuffer = mc.aimConstraint(groupAim,transformGroup,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,-1,0],  worldUpObject = groupUp, worldUpType = 'object')
         mc.delete(aimConstraintBuffer[0])
         mc.delete(groupUp)
         mc.delete(groupAim)
         
         startLoc = rigging.doParentReturnName(startLoc,transformGroup)
         rigging.zeroTransformMeObject(startLoc)
         returnLoc.append(startLoc)
         returnLoc.append(transformGroup)
         zeroGroup = rigging.groupMeObject(transformGroup)
         attributes.storeInfo(zeroGroup,'move',transformGroup)
         returnLoc.append(zeroGroup)
         
         return returnLoc
         
     elif modeType == 'footBase':
         returnLoc = []
         startLoc = locators.locMeObject(workingObject)
         startLoc = mc.rename(startLoc,(self.ModuleNull.nameBase+'_footcgmase_startLoc'))
         StartLoc = ObjectFactory(startLoc)
         
         masterGroup = rigging.groupMeObject(startLoc)
         
         mc.setAttr((startLoc+'.rx'),-90)
         returnLoc.append(startLoc)
         zeroGroup = rigging.zeroTransformMeObject(startLoc)
         
         currentPos = mc.xform(zeroGroup,q=True, t=True,ws=True)
         mc.xform(zeroGroup,t=[currentPos[0],0,currentPos[2]], ws = True)
         
         attributes.storeInfo(zeroGroup,'locator',startLoc)
         returnLoc.append(zeroGroup)
         returnLoc.append(masterGroup)
         
         return returnLoc
         
     elif modeType == 'parentDuplicate':
         returnLoc = []
         startLoc = locators.locMeObject(workingObject)
         startLoc = mc.rename(startLoc,(self.ModuleNull.nameBase+'_parentDup_startLoc'))
         StartLoc = ObjectFactory(startLoc)
         
         masterGroup = rigging.groupMeObject(startLoc)
         returnLoc.append(startLoc)
         returnLoc.append(masterGroup)
         
         return returnLoc
     else:
         return False
Example #33
0
def doConstraintObjectGroup(targets,obj = False,constraintTypes = [],group = False, mode=0): 
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list)
    object(string)
    constraintTypes(list)
    group(string) -- whether to pass a group through
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    log.debug(">>> doConstraintObjectGroup")
    log.info("targets: %s"%str(targets))
    log.debug("obj: %s"%str(obj))
    log.info("constraintTypes: %s"%str(constraintTypes))
    log.debug("group: %s"%str(group))
    log.debug("mode: %s"%str(mode))
    if targets and not type(targets)==list:targets=[targets]#thanks Mark, for this syntax
    if constraintTypes and not type(constraintTypes)==list:constraintTypes=[constraintTypes]
    
    normalizedDistances = False
    if not obj and not group:
        log.warning("Must have a obj or a group")
        return False
    if group and mc.objExists(group):
        objGroup = group
    elif obj:
        objGroup = rigging.groupMeObject(obj,True,True)
    else:
        log.warning("Not enough info")        
        return False
    
    for c in constraintTypes:
        constraint = False
        if mode == 1:
            distances = []
            for target in targets:
                distances.append(distance.returnDistanceBetweenObjects(target,objGroup))
            normalizedDistances = cgmMath.normList(distances)        
        if c == 'point':
            constraint = mc.pointConstraint(targets,objGroup, maintainOffset=True)
            targetWeights = mc.pointConstraint(constraint,q=True, weightAliasList=True)            
        if c == 'parent':
            constraint = mc.parentConstraint(targets,objGroup, maintainOffset=True)
            targetWeights = mc.parentConstraint(constraint,q=True, weightAliasList=True)                        
        if c == 'orient':
            constraint = mc.orientConstraint(targets,objGroup, maintainOffset=True)
            targetWeights = mc.orientConstraint(constraint,q=True, weightAliasList=True)                                    
        if c == 'scale':
            constraint = mc.scaleConstraint(targets,objGroup, maintainOffset=True)
            targetWeights = mc.scaleConstraint(constraint,q=True, weightAliasList=True)                                    
        if constraint:
            try:mc.setAttr("%s.interpType"%constraint[0],0)#Set to no flip
            except:pass
            if normalizedDistances:
                for cnt,value in enumerate(normalizedDistances):
                    mc.setAttr(('%s%s%s' % (constraint[0],'.',targetWeights[cnt])),value )
    return objGroup
Example #34
0
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}
Example #35
0
def connectBndToPivot(bnd, pivot, drivePrimary=False):
    '''
    basically the same at face.connectBndToPriCtl
    but can don't drive primary controls
    '''
    
    # bnd's "local" matrix within pivot
    bnd_wMat = bnd.getMatrix(ws=True)
    pivot_wMat = pivot.getMatrix(ws=True)
    bnd_lMat = bnd_wMat * pivot_wMat.inverse()
    lMatNd = pm.createNode('fourByFourMatrix', n=bnd.replace('_bnd', '_lMat_in_' + pivot.nodeName()))
    # populate "local" matrix
    for i in range(4):
        for j in range(4):
            lMatNd.attr('in%d%d' % (i, j)).set(bnd_lMat[i][j])
    # bnd's "local-inverse" matrix
    lInvMatNd = pm.createNode('inverseMatrix', n=bnd.replace('_bnd', '_lInvMat_in_' + pivot.nodeName()))
    lMatNd.output >> lInvMatNd.inputMatrix
    # for bnd to pivot around pivot,
    # the matrix is lMat * pivotMat * lInvMat
    mmNd = pm.createNode('multMatrix', n=bnd.replace('_bnd', '_calc_mm'))
    lMatNd.output >> mmNd.i[0]
    pivot.matrix >> mmNd.i[1]
    lInvMatNd.outputMatrix >> mmNd.i[2]
    # decompose matrix before passing into bw
    dmNd = pm.createNode('decomposeMatrix', n=bnd.replace('_bnd', '_calc_dm'))
    mmNd.o >> dmNd.inputMatrix
    # get bw nodes to connect to
    channels = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
    bwNodes = {}
    for eachChannel in channels:
        bwNodes[eachChannel] = bnd.attr(eachChannel + '_bwMsg').get()
    # get index to connect to
    existingInputs = bwNodes['tx'].i.inputs()
    nextIndex = len(existingInputs)
    # actual connections
    dmNd.otx >> bwNodes['tx'].i[nextIndex]
    dmNd.oty >> bwNodes['ty'].i[nextIndex]
    dmNd.otz >> bwNodes['tz'].i[nextIndex]
    dmNd.orx >> bwNodes['rx'].i[nextIndex]
    dmNd.ory >> bwNodes['ry'].i[nextIndex]
    dmNd.orz >> bwNodes['rz'].i[nextIndex]
    dmNd.osx >> bwNodes['sx'].i[nextIndex]
    dmNd.osy >> bwNodes['sy'].i[nextIndex]
    dmNd.osz >> bwNodes['sz'].i[nextIndex]
    # channel box separator
    bnd.addAttr(pivot.nodeName() + '_weights', at='double', k=True, dv=0)
    bnd.setAttr(pivot.nodeName() + '_weights', lock=True)
    # connect weight to be blended to 0
    for eachChannel in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']:
        bnd.addAttr(pivot.nodeName() + '_weight_' + eachChannel, at='double', k=True, min=-1, max=2, dv=1)
        bnd.attr(pivot.nodeName() + '_weight_' + eachChannel) >> bwNodes[eachChannel].weight[nextIndex]
    # scales need a minus 1, to be normalized to 0 for blending
    for eachChannel in ['sx', 'sy', 'sz']:
        adl = pm.createNode('addDoubleLinear', n=bnd.replace('_bnd', '_%s_adl' % eachChannel))
        adl.input2.set(-1)
        dmNd.attr('o%s' % eachChannel) >> adl.input1
        adl.output >> bwNodes[eachChannel].i[nextIndex]
        bnd.addAttr(pivot.nodeName() + '_weight_' + eachChannel, at='double', k=True, min=-1, max=2, dv=1)
        bnd.attr(pivot.nodeName() + '_weight_' + eachChannel) >> bwNodes[eachChannel].weight[nextIndex]
    
    if drivePrimary:
        # if this bnd already has it's own attached priCtl
        # we need to drive that too
        if bnd.hasAttr('attached_pri_ctl'):
            attachedCtl = bnd.attr('attached_pri_ctl').get()
            
            if attachedCtl != pivot:
                print 'Bnd: ' + bnd
                print 'Current Pri Ctl: ' + pivot
                print 'Attached Pri Ctl: ' + attachedCtl
                attachedCtg = attachedCtl.getParent()
                # add zero grp to take in connections
                zeroGrp = pm.PyNode(cgmrigging.groupMeObject(attachedCtg.nodeName(), True, True))
                for eachChannel in channels:
                    mdl = pm.createNode('multDoubleLinear', n=bnd.replace('_bnd', '_%s_%s_mdl' % (eachChannel, pivot)))
                    if eachChannel in ['sx', 'sy', 'sz']:
                        adl = pm.createNode('addDoubleLinear', n=bnd.replace('_bnd', '_%s_%s_adl' % (eachChannel, pivot)))
                        dmNd.attr('o' + eachChannel) >> adl.input1
                        adl.input2.set(-1)
                        adl.output >> mdl.input1
                    else:
                        dmNd.attr('o' + eachChannel) >> mdl.input1
                        
                    bnd.attr(pivot.nodeName() + '_weight_' + eachChannel) >> mdl.input2
                    
                    if eachChannel in ['sx', 'sy', 'sz']:
                        adl = pm.createNode('addDoubleLinear', n=bnd.replace('_bnd', '_%s_%s_adl' % (eachChannel, pivot)))
                        mdl.output >> adl.input1
                        adl.input2.set(1)
                        adl.output >> zeroGrp.attr(eachChannel)
                    else:
                        mdl.output >> zeroGrp.attr(eachChannel)
Example #36
0
def doPointAimConstraintObjectGroup(targets,object,mode=0): 
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    ACKNOWLEDGEMENT:
    Idea for this stype of constraint setup is from http://td-matt.blogspot.com/2011/01/spine-control-rig.html
    
    DESCRIPTION:
    Groups an object and constrains that group to the other objects
    
    ARGUMENTS:
    targets(list) - should be in format of from to back with the last one being the aim object
    object(string)
    mode(int) - 0 - equal influence
                1 - distance spread
    
    RETURNS:
    group(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    returnList = []
    """ figure out which is the aim direction  """
    aimVector = logic.returnLocalAimDirection(object,targets[-1])
    upVector = logic.returnLocalUp(aimVector)
    
    """ create locators """
    locs = []
    toMake = ['point','aim','up']
    for type in toMake:
        locBuffer = locators.locMeObject(object)
        attributes.storeInfo(locBuffer,'cgmName',object)
        attributes.storeInfo(locBuffer,'cgmTypeModifier',type)
        locs.append(NameFactory.doNameObject(locBuffer))
    
    pointLoc = locs[0]
    aimLoc = locs[1]
    upLoc = locs[2]

    """ move the locators """
    mc.xform(aimLoc,t=aimVector,r=True,os=True)
    mc.xform(upLoc,t=upVector,r=True,os=True)
    
    """group constraint"""
    objGroup = rigging.groupMeObject(object,True,True)
    attributes.storeInfo(objGroup,'cgmName',object)
    attributes.storeInfo(objGroup,'cgmTypeModifier','follow')
    objGroup = NameFactory.doNameObject(objGroup)
    
    pointConstraintBuffer = mc.pointConstraint (pointLoc,objGroup, maintainOffset=False)
    aimConstraintBuffer = mc.aimConstraint(aimLoc,objGroup,maintainOffset = False, weight = 1, aimVector = aimVector, upVector = upVector, worldUpObject = upLoc, worldUpType = 'object' )

    """loc constraints"""
    locConstraints = []
    for loc in locs:
        parentConstraintBuffer = mc.parentConstraint (targets,loc, maintainOffset=True)
        locConstraints.append(parentConstraintBuffer[0])
    
    if mode == 1:
        distances = []
        for target in targets:
            distances.append(distance.returnDistanceBetweenObjects(target,objGroup))
        normalizedDistances = cgmMath.normList(distances)
        for constraint in locConstraints:
            targetWeights = mc.parentConstraint(constraint,q=True, weightAliasList=True)      
            cnt=1
            for value in normalizedDistances:
                mc.setAttr(('%s%s%s' % (constraint,'.',targetWeights[cnt])),value )
                cnt-=1

    returnList.append(objGroup)
    returnList.append(locs)
    return returnList
Example #37
0
def addOrientationHelpers(self):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Adds orientation helpers to a template chain
    
    ARGUMENTS:
    objects(list)
    root(string) - root control of the limb chain
    moduleType(string)
    
    RETURNS:
    returnList(list) = [rootHelper(string),helperObjects(list),helperObjectGroups(list)]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    moduleColors = modules.returnModuleColors(self.ModuleNull.nameLong)
    helperObjects = []
    helperObjectGroups = []
    returnBuffer = []
    root = self.msgTemplateRoot.getMessage()
    visAttr = "%s.visOrientHelpers" % self.infoNulls['visibilityOptions'].get()
    objects = self.templatePosObjectsBuffer.bufferList

    #>>> Direction and size Stuff
    """ Directional data derived from joints """
    generalDirection = logic.returnHorizontalOrVertical(objects)

    if generalDirection == 'vertical' and 'leg' not in self.afModuleType.get():
        worldUpVector = [0, 0, -1]
    elif generalDirection == 'vertical' and 'leg' in self.afModuleType.get():
        worldUpVector = [0, 0, 1]
    else:
        worldUpVector = [0, 1, 0]

    #Get Size
    size = (distance.returnBoundingBoxSizeToAverage(objects[0]) * 2)

    #>>> Master Orient helper
    createBuffer = curves.createControlCurve('circleArrow1', (size * 2),
                                             'z+')  # make the curve
    curves.setCurveColorByName(createBuffer, moduleColors[0])

    attributes.storeInfo(createBuffer, 'cgmType',
                         'templateOrientRoot')  #copy the name attr
    mainOrientHelperObj = NameFactory.doNameObject(createBuffer)

    attributes.storeObjectToMessage(
        mainOrientHelperObj, self.msgTemplateRoot.get(),
        'orientHelper')  #store the object to it's respective  object
    returnBuffer.append(mainOrientHelperObj)

    # Snapping
    position.movePointSnap(mainOrientHelperObj, root)
    constBuffer = mc.aimConstraint(objects[1],
                                   mainOrientHelperObj,
                                   maintainOffset=False,
                                   weight=1,
                                   aimVector=[1, 0, 0],
                                   upVector=[0, 1, 0],
                                   worldUpVector=worldUpVector,
                                   worldUpType='vector')
    mc.delete(constBuffer[0])

    # Follow Groups
    mainOrientHelperGroupBuffer = rigging.groupMeObject(mainOrientHelperObj)
    mainOrientHelperGroupBuffer = NameFactory.doNameObject(
        mainOrientHelperGroupBuffer)
    mainOrientHelperGroup = rigging.doParentReturnName(
        mainOrientHelperGroupBuffer, root)
    mc.pointConstraint(objects[0],
                       mainOrientHelperGroupBuffer,
                       maintainOffset=False)
    helperObjectGroups.append(mainOrientHelperGroup)

    # set up constraints
    mc.aimConstraint(objects[-1],
                     mainOrientHelperGroup,
                     maintainOffset=True,
                     weight=1,
                     aimVector=[1, 0, 0],
                     upVector=[0, 1, 0],
                     worldUpObject=root,
                     worldUpType='objectRotation')
    # lock and hide stuff
    attributes.doSetLockHideKeyableAttr(
        mainOrientHelperObj, True, False, False,
        ['tx', 'ty', 'tz', 'rz', 'ry', 'sx', 'sy', 'sz', 'v'])

    #>>> The sub helpers
    """ make our pair lists """
    pairList = lists.parseListToPairs(objects)
    """ make our controls """
    helperObjects = []
    for pair in pairList:
        """ Get Size """
        size = (distance.returnBoundingBoxSizeToAverage(pair[0]) * 2)
        """ make the curve"""
        createBuffer = curves.createControlCurve('circleArrow2Axis', size,
                                                 'y-')
        curves.setCurveColorByName(createBuffer, moduleColors[1])
        """ copy the name attr"""
        attributes.copyUserAttrs(pair[0], createBuffer, ['cgmName'])
        attributes.storeInfo(createBuffer, 'cgmType', 'templateOrientObject')
        helperObj = NameFactory.doNameObject(createBuffer)
        """ store the object to it's respective  object and to an object list """
        attributes.storeObjectToMessage(helperObj, pair[0], 'orientHelper')
        helperObjects.append(helperObj)
        """ initial snapping """
        position.movePointSnap(helperObj, pair[0])
        constBuffer = mc.aimConstraint(pair[1],
                                       helperObj,
                                       maintainOffset=False,
                                       weight=1,
                                       aimVector=[1, 0, 0],
                                       upVector=[0, 1, 0],
                                       worldUpVector=worldUpVector,
                                       worldUpType='vector')
        mc.delete(constBuffer[0])
        """ follow groups """
        helperGroupBuffer = rigging.groupMeObject(helperObj)
        helperGroup = NameFactory.doNameObject(helperGroupBuffer)
        helperGroup = rigging.doParentReturnName(helperGroup, pair[0])
        helperObjectGroups.append(helperGroup)
        """ set up constraints """
        mc.aimConstraint(pair[1],
                         helperGroup,
                         maintainOffset=False,
                         weight=1,
                         aimVector=[1, 0, 0],
                         upVector=[0, 1, 0],
                         worldUpVector=[0, 1, 0],
                         worldUpObject=mainOrientHelperObj,
                         worldUpType='objectrotation')
        """ lock and hide stuff """
        helperObj = attributes.returnMessageObject(pair[0], 'orientHelper')
        mc.connectAttr((visAttr), (helperObj + '.v'))
        attributes.doSetLockHideKeyableAttr(
            helperObj, True, False, False,
            ['tx', 'ty', 'tz', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])

    #>>> For the last object in the chain
    for obj in objects[-1:]:
        """ Get Size """
        size = (distance.returnBoundingBoxSizeToAverage(obj) * 2)
        """ make the curve"""
        createBuffer = curves.createControlCurve('circleArrow2Axis', size,
                                                 'y-')
        curves.setCurveColorByName(createBuffer, moduleColors[1])
        """ copy the name attr"""
        attributes.copyUserAttrs(obj, createBuffer, ['cgmName'])
        attributes.storeInfo(createBuffer, 'cgmType', 'templateOrientObject')
        helperObj = NameFactory.doNameObject(createBuffer)
        """ store the object to it's respective  object """
        attributes.storeObjectToMessage(helperObj, obj, 'orientHelper')
        """ initial snapping """
        position.movePointSnap(helperObj, obj)
        constBuffer = mc.aimConstraint(objects[-2],
                                       helperObj,
                                       maintainOffset=False,
                                       weight=1,
                                       aimVector=[1, 0, 0],
                                       upVector=[0, 1, 0],
                                       worldUpVector=worldUpVector,
                                       worldUpType='vector')
        mc.delete(constBuffer[0])
        """ follow groups """
        helperGroupBuffer = rigging.groupMeObject(helperObj)
        helperGroup = NameFactory.doNameObject(helperGroupBuffer)
        helperGroup = rigging.doParentReturnName(helperGroup, obj)
        helperObjectGroups.append(helperGroup)
        """ set up constraints """
        secondToLastHelperObject = attributes.returnMessageObject(
            objects[-2], 'orientHelper')
        mc.orientConstraint(secondToLastHelperObject,
                            helperGroup,
                            maintainOffset=False,
                            weight=1)
        """ lock and hide stuff """
        helperObj = attributes.returnMessageObject(obj, 'orientHelper')
        mc.connectAttr((visAttr), (helperObj + '.v'))
        attributes.doSetLockHideKeyableAttr(
            helperObj, True, False, False,
            ['tx', 'ty', 'tz', 'sx', 'sy', 'sz', 'v'])
        helperObjects.append(helperObj)

    returnBuffer.append(helperObjects)
    returnBuffer.append(helperObjectGroups)
    return returnBuffer