Exemplo n.º 1
0
 def store(self,info,*a,**kw):
     """ 
     Store information to an object in maya via case specific attribute.
     
     Keyword arguments:
     info(string) -- must be an object in the scene
     
     """
     assert mc.objExists(info) is True, "'%s' doesn't exist"%info
     
     if info in self.bufferList:
         guiFactory.warning("'%s' is already stored on '%s'"%(info,self.nameLong))    
         return
     
     userAttrs = attributes.returnUserAttrsToDict(self.nameLong) or {}
     countList = []
     for key in userAttrs.keys():
         if 'item_' in key:
             splitBuffer = key.split('item_')
             countList.append(int(splitBuffer[-1]))
     cnt = 0
     cntBreak = 0
     while cnt in countList and cntBreak < 500:
         cnt+=1
         cntBreak += 1
 
     attributes.storeInfo(self.nameLong,('item_'+str(cnt)),info,*a,**kw)
     guiFactory.warning("'%s' stored on '%s'"%(info,self.nameLong))            
     self.bufferList.append(info)
     self.bufferDict['item_'+str(cnt)] = info
Exemplo n.º 2
0
    def store(self, info, *a, **kw):
        """ 
        Store information to an object in maya via case specific attribute.
        
        Keyword arguments:
        info(string) -- must be an object in the scene
        
        """
        assert mc.objExists(info) is True, "'%s' doesn't exist" % info

        if info in self.bufferList:
            guiFactory.warning("'%s' is already stored on '%s'" %
                               (info, self.nameLong))
            return

        userAttrs = attributes.returnUserAttrsToDict(self.nameLong) or {}
        countList = []
        for key in userAttrs.keys():
            if 'item_' in key:
                splitBuffer = key.split('item_')
                countList.append(int(splitBuffer[-1]))
        cnt = 0
        cntBreak = 0
        while cnt in countList and cntBreak < 500:
            cnt += 1
            cntBreak += 1

        attributes.storeInfo(self.nameLong, ('item_' + str(cnt)), info, *a,
                             **kw)
        guiFactory.warning("'%s' stored on '%s'" % (info, self.nameLong))
        self.bufferList.append(info)
        self.bufferDict['item_' + str(cnt)] = info
Exemplo n.º 3
0
def doUpdateName(obj):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Names an object's heirarchy below

    ARGUMENTS:
    obj(string) - the object we'd like to startfrom

    RETURNS:
    Nothin
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    ### input check
    assert mc.objExists(obj) is True, "'%s' doesn't exist" %obj

    typeDictionary = dictionary.initializeDictionary(typesDictionaryFile)
    attrName = ('%s%s' % (obj,'.cgmName'))
    # Look for cgmName tag
    if search.returnNameTag(obj) is not False:
        if mc.getAttr(attrName,lock=True) == True:
            mc.setAttr(attrName,lock=False)
        mc.setAttr(attrName,obj, type='string')
        mc.setAttr(attrName,lock=True)
    else:
        attributes.storeInfo(obj,'cgmName',obj,True)
    return doNameObject(obj)
Exemplo n.º 4
0
        def _mirrorSetup(self):	
            str_mirrorSide = self.str_mirrorSide
            str_mirrorAxis = self.str_mirrorAxis
            b_makeMirrorable = self.b_makeMirrorable
            if str_mirrorSide is not None or b_makeMirrorable:
                for mObj in [self.mi_control] + self.ml_spacePivots:
                    #log.info("mirrorsetup: {0}".format(mObj.p_nameShort))
                    try:self.mi_control._verifyMirrorable()
                    except Exception,error:raise StandardError,"_mirrorSetup | %s"%(error)
                    l_enum = cgmMeta.cgmAttr(self.mi_control,'mirrorSide').p_enum
                    if str_mirrorSide in l_enum:
                        log.debug("%s >> %s >> found in : %s"%(self._str_funcCombined, "mirrorSetup", l_enum))		
                        try:
                            self.mi_control.mirrorSide = l_enum.index(str_mirrorSide)
                            log.debug("%s >> %s >> mirrorSide set to: %s"%(self._str_funcCombined,"mirrorSetup",self.mi_control.mirrorSide ))						    
                        except Exception,error:raise StandardError,"str_mirrorSide : %s | %s"%(str_mirrorSide,error)
                    if str_mirrorAxis:
                        try:
                            self.mi_control.mirrorAxis = str_mirrorAxis
                            log.debug("%s >> %s >> str_mirrorAxis set: %s"%(self._str_funcCombined,"mirrorSetup",str_mirrorAxis))				    
                        except Exception,error:raise StandardError,"str_mirrorAxis : %s | %s"%(str_mirrorAxis,error)
                for mObj in self.mi_control.msgList_get('spacePivots'):
                    try:
                        try:mObj._verifyMirrorable()
                        except Exception,error:raise StandardError,"_mirrorSetup | %s"%(error)
                        #cgmMeta.cgmAttr(mObj,'mirrorSide').doConnectIn(self.mi_control,'mirrorSide')
                        #cgmMeta.cgmAttr(self.mi_control,'mirrorAxis').doCopyTo(mObj,connectTargetToSource = 1)
                        attributes.storeInfo(mObj.mNode,'mirrorAxis',"{0}.mirrorAxis".format(self.mi_control.mNode))
                        attributes.storeInfo(mObj.mNode,'mirrorSide',"{0}.mirrorSide".format(self.mi_control.mNode))

                    except Exception,error:raise StandardError,"spacePivot failed failed! {0}| error: {1}".format(mObj,error)
Exemplo n.º 5
0
def createPoseBuffer(name, poseList):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns the colors used on the shapes of a curve as a list in order
    of volume used

    ARGUMENTS:
    curve(string
    
    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    returnList = []

    poseBuffer = mc.group(em=True)
    attributes.storeInfo(poseBuffer, "cgmName", name)
    attributes.storeInfo(poseBuffer, "cgmType", "poseBuffer")
    poseBuffer = NameFactoryOld.doNameObject(poseBuffer)
    returnList.append(poseBuffer)

    returnList.append(attributes.addFloatAttrsToObj(poseBuffer, poseList, dv=0, keyable=True))

    attributes.doSetLockHideKeyableAttr(poseBuffer, True, False, False)

    return returnList
Exemplo n.º 6
0
def createPoseBuffer(name, poseList):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns the colors used on the shapes of a curve as a list in order
    of volume used

    ARGUMENTS:
    curve(string
    
    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    returnList = []

    poseBuffer = mc.group(em=True)
    attributes.storeInfo(poseBuffer, 'cgmName', name)
    attributes.storeInfo(poseBuffer, 'cgmType', 'poseBuffer')
    poseBuffer = NameFactory.doNameObject(poseBuffer)
    returnList.append(poseBuffer)

    returnList.append(
        attributes.addFloatAttrsToObj(poseBuffer, poseList, dv=0,
                                      keyable=True))

    attributes.doSetLockHideKeyableAttr(poseBuffer, True, False, False)

    return returnList
Exemplo n.º 7
0
def doUpdateName(obj, *a, **kw):
    """ 
    Updates the name of an object

    ARGUMENTS:
    obj(string) - the object we'd like to startfrom

    RETURNS:
    Nothin
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    ### input check
    assert mc.objExists(obj) is True, "'%s' doesn't exist" % obj

    typeDictionary = dictionary.initializeDictionary(typesDictionaryFile)
    attrName = ('%s%s' % (obj, '.cgmName'))
    # Look for cgmName tag
    if search.returnNameTag(obj) is not False:
        if mc.getAttr(attrName, lock=True) == True:
            mc.setAttr(attrName, lock=False)
        mc.setAttr(attrName, obj, type='string')
        mc.setAttr(attrName, lock=True)
    else:
        attributes.storeInfo(obj, 'cgmName', obj, True)
    return doNameObject(obj, *a, **kw)
Exemplo n.º 8
0
        def _mirrorSetup(self):	
            str_mirrorSide = self.str_mirrorSide
            str_mirrorAxis = self.str_mirrorAxis
            b_makeMirrorable = self.b_makeMirrorable
            if str_mirrorSide is not None or b_makeMirrorable:
                for mObj in [self.mi_control] + self.ml_spacePivots:
                    #log.info("mirrorsetup: {0}".format(mObj.p_nameShort))
                    try:self.mi_control._verifyMirrorable()
                    except Exception,error:raise StandardError,"_mirrorSetup | %s"%(error)
                    l_enum = cgmMeta.cgmAttr(self.mi_control,'mirrorSide').p_enum
                    if str_mirrorSide in l_enum:
                        log.debug("%s >> %s >> found in : %s"%(self._str_funcCombined, "mirrorSetup", l_enum))		
                        try:
                            self.mi_control.mirrorSide = l_enum.index(str_mirrorSide)
                            log.debug("%s >> %s >> mirrorSide set to: %s"%(self._str_funcCombined,"mirrorSetup",self.mi_control.mirrorSide ))						    
                        except Exception,error:raise StandardError,"str_mirrorSide : %s | %s"%(str_mirrorSide,error)
                    if str_mirrorAxis:
                        try:
                            self.mi_control.mirrorAxis = str_mirrorAxis
                            log.debug("%s >> %s >> str_mirrorAxis set: %s"%(self._str_funcCombined,"mirrorSetup",str_mirrorAxis))				    
                        except Exception,error:raise StandardError,"str_mirrorAxis : %s | %s"%(str_mirrorAxis,error)
                for mObj in self.mi_control.msgList_get('spacePivots'):
                    try:
                        try:mObj._verifyMirrorable()
                        except Exception,error:raise StandardError,"_mirrorSetup | %s"%(error)
                        #cgmMeta.cgmAttr(mObj,'mirrorSide').doConnectIn(self.mi_control,'mirrorSide')
                        #cgmMeta.cgmAttr(self.mi_control,'mirrorAxis').doCopyTo(mObj,connectTargetToSource = 1)
                        attributes.storeInfo(mObj.mNode,'mirrorAxis',"{0}.mirrorAxis".format(self.mi_control.mNode))
                        attributes.storeInfo(mObj.mNode,'mirrorSide',"{0}.mirrorSide".format(self.mi_control.mNode))

                    except Exception,error:raise StandardError,"spacePivot failed failed! {0}| error: {1}".format(mObj,error)
Exemplo n.º 9
0
def returnUniqueGeneratedName(obj,sceneUnique = False,fastIterate = True, ignore='none',**kws):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a generated name with iteration for heirarchy objects with the same tag info

    ARGUMENTS:
    obj(string) - object
    ignore(string) - default is 'none', only culls out cgmtags that are 
                     generated via returnCGMOrder() function

    RETURNS:
    name(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    if type(ignore) is not list:ignore = [ignore]
    log.debug("sceneUnique: %s"%sceneUnique)
    log.debug("fastIterate: %s"%fastIterate)
    log.debug("ignore: %s"%ignore)
    
    #>>> Dictionary driven order first build
    def doBuildName():
        nameBuilder=[]
        for item in order:
            buffer = updatedNamesDict.get(item)
            # Check for short name
            buffer = search.returnTagInfoShortName(buffer,item)
            if buffer and buffer != 'ignore':
                nameBuilder.append(buffer)

        return divider.join(nameBuilder)
    
    rawNamesDict = returnObjectGeneratedNameDict(obj,ignore)
    divider = returnCGMDivider()
    updatedNamesDict = returnObjectGeneratedNameDict(obj,ignore)
    order = returnCGMOrder()
    
    if 'cgmName' not in updatedNamesDict.keys() and search.returnObjectType(obj) !='group':
        buffer = mc.ls(obj,shortNames = True)
        attributes.storeInfo(obj,'cgmName',buffer[0],True)
        updatedNamesDict = returnObjectGeneratedNameDict(obj,ignore)

    coreName = doBuildName()
    
    """ add the iterator to the name dictionary if our object exists"""
    nameFactory = NameFactory(obj)
    
    if sceneUnique:
        if fastIterate:
            iterator = returnFastIterateNumber(obj)            
        else:
            iterator = returnIterateNumber(obj)
        if iterator > 0:
            updatedNamesDict['cgmIterator'] = str(iterator)
            coreName = doBuildName()
            
    log.debug(returnCombinedNameFromDict(updatedNamesDict))
    return returnCombinedNameFromDict(updatedNamesDict)
Exemplo n.º 10
0
def returnUniqueGeneratedName(obj,
                              sceneUnique=False,
                              fastIterate=True,
                              ignore='none'):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a generated name with iteration for heirarchy objects with the same tag info

    ARGUMENTS:
    obj(string) - object
    ignore(string) - default is 'none', only culls out cgmtags that are 
                     generated via returnCGMOrder() function

    RETURNS:
    name(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """

    #>>> Dictionary driven order first build
    def doBuildName():
        nameBuilder = []
        for item in order:
            buffer = updatedNamesDict.get(item)
            # Check for short name
            buffer = search.returnTagInfoShortName(buffer, item)
            if buffer > 0 and buffer != 'ignore':
                nameBuilder.append(buffer)

        return divider.join(nameBuilder)

    rawNamesDict = returnObjectGeneratedNameDict(obj, ignore)
    divider = returnCGMDivider()
    updatedNamesDict = returnObjectGeneratedNameDict(obj, ignore)
    order = returnCGMOrder()

    if 'cgmName' not in updatedNamesDict.keys():
        buffer = mc.ls(obj, shortNames=True)
        attributes.storeInfo(obj, 'cgmName', buffer[0], True)
        updatedNamesDict = returnObjectGeneratedNameDict(obj, ignore)

    coreName = doBuildName()
    """ add the iterator to the name dictionary if our object exists"""
    nameFactory = NameFactory(obj)

    if sceneUnique:
        if fastIterate:
            iterator = returnFastIterateNumber(obj)
        else:
            iterator = returnIterateNumber(obj)
        if iterator > 0:
            updatedNamesDict['cgmIterator'] = str(iterator)
            coreName = doBuildName()

    return returnCombinedNameFromDict(updatedNamesDict)
Exemplo n.º 11
0
def doRenameHeir(obj, sceneUnique=False):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Names an object's heirarchy below

    ARGUMENTS:
    obj(string) - the object we'd like to startfrom

    RETURNS:
    newNames(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    ### input check
    assert mc.objExists(obj) is True, "'%s' doesn't exist" % obj

    #children = mc.listRelatives(obj,allDescendents=True,type='transform')
    # Create a tmp group to store out objects to so that we can get them back even if heirarchal names change
    tmpGroup = mc.group(em=True)
    attributes.storeInfo(tmpGroup, ('name' + str(0)), obj)

    newNames = []
    childrenList = []
    children = mc.listRelatives(obj, allDescendents=True, fullPath=True)
    children.reverse()

    cnt = 1
    for c in children:
        attributes.storeInfo(tmpGroup, ('name' + str(cnt)), c)
        cnt += 1

    toNameAttrs = attributes.returnUserAttributes(tmpGroup)
    mayaMainProgressBar = guiFactory.doStartMayaProgressBar(
        len(toNameAttrs), 'Naming')

    for attr in toNameAttrs:
        if mc.progressBar(mayaMainProgressBar, query=True, isCancelled=True):
            break

        objectToName = (attributes.returnMessageObject(tmpGroup, attr))
        mc.progressBar(mayaMainProgressBar,
                       edit=True,
                       status=("Naming '%s'" % objectToName),
                       step=1)

        buffer = doNameObject(objectToName, sceneUnique)
        if buffer:
            newNames.append(buffer)

    guiFactory.doEndMayaProgressBar(mayaMainProgressBar)

    mc.delete(tmpGroup)
    return newNames
Exemplo n.º 12
0
def doRenameHeir(obj,sceneUnique = False):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Names an object's heirarchy below

    ARGUMENTS:
    obj(string) - the object we'd like to startfrom

    RETURNS:
    newNames(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    ### input check
    assert mc.objExists(obj) is True, "'%s' doesn't exist" %obj
    
    #children = mc.listRelatives(obj,allDescendents=True,type='transform')
    # Create a tmp group to store out objects to so that we can get them back even if heirarchal names change
    tmpGroup = mc.group(em=True)
    attributes.storeInfo(tmpGroup,('name'+str(0)),obj)
    
    newNames = []
    childrenList = []
    children = mc.listRelatives(obj,allDescendents=True,fullPath=True)
    children.reverse()

    cnt = 1
    for c in children:
        attributes.storeInfo(tmpGroup,('name'+str(cnt)),c)
        cnt += 1
        
    toNameAttrs = attributes.returnUserAttributes(tmpGroup)
    mayaMainProgressBar = guiFactory.doStartMayaProgressBar(len(toNameAttrs),'Naming')

    for attr in toNameAttrs:
        if mc.progressBar(mayaMainProgressBar, query=True, isCancelled=True ) :
            break
        
        objectToName = (attributes.returnMessageObject(tmpGroup,attr))
        mc.progressBar(mayaMainProgressBar, edit=True, status = ("Naming '%s'"%objectToName), step=1)

        buffer =  doNameObject( objectToName,sceneUnique )
        if buffer:
            newNames.append(buffer)
            
        
    guiFactory.doEndMayaProgressBar(mayaMainProgressBar)
            

    mc.delete(tmpGroup)
    return newNames
Exemplo n.º 13
0
def locMeCenter(objList,forceBBCenter = False):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Pass  an object into it and get a named locator with stored info for updating it

	ARGUMENTS:
	obj(string)

	RETURNS:
	name(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	# make it
	nameBuffer = mc.spaceLocator()

	#store info
	attributes.storeInfo(nameBuffer[0],'cgmSource',(','.join(objList)),False)
	attributes.storeInfo(nameBuffer[0],'cgmLocMode','selectCenter',False)
	attributes.storeInfo(nameBuffer[0],'cgmName',(str('_to_'.join(objList))),False)
	attributes.storeInfo(nameBuffer[0],'cgmTypeModifier','midPoint',False)

	posList = []

	for obj in objList:
		if mc.objExists(obj) == True:
			objInfo = returnInfoForLoc(obj,forceBBCenter)
			posList.append(objInfo['position'])

	objTrans = distance.returnAveragePointPosition(posList)

	mc.move (objTrans[0],objTrans[1],objTrans[2], nameBuffer[0])

	#return ( NameFactory.doNameObject(nameBuffer[0]) )
	return cgmMeta.NameFactory(nameBuffer[0]).doNameObject()
Exemplo n.º 14
0
    def create(self, setType):
        """ Creates a set object honoring our quick select set options """
        set = mc.sets(em=True)

        attributes.storeInfo(set, 'cgmName', self.baseName)
        if setType:
            self.setType = setType
            if setType in setTypes.keys():
                doType = setTypes.get(setType)
            else:
                doType = setType
            attributes.storeInfo(set, 'cgmType', setType)

        set = NameFactory.doNameObject(set, True)
        self.storeNameStrings(set)

        if self.qssState:
            self.isQss(self.qssState)
Exemplo n.º 15
0
 def create(self,setType):
     """ Creates a set object honoring our quick select set options """ 
     set = mc.sets(em=True)
         
     attributes.storeInfo(set,'cgmName',self.baseName)
     if setType:
         self.setType = setType
         if setType in setTypes.keys():
             doType = setTypes.get(setType)
         else:
             doType = setType
         attributes.storeInfo(set,'cgmType',setType)
         
     set = NameFactory.doNameObject(set,True)
     self.storeNameStrings(set)
     
     if self.qssState:
         self.isQss(self.qssState)        
Exemplo n.º 16
0
def createInfoNull(infoType):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Creates an infoNull
    
    ARGUMENTS:
    infoType(string)
    
    RETURNS:
    infoNull(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    createBuffer = mc.group (empty=True)
    attributes.storeInfo(createBuffer,'cgmName',infoType)
    attributes.storeInfo(createBuffer,'cgmType','infoNull')
    mc.xform (createBuffer, os=True, piv= (0,0,0)) 
    infoNull = NameFactory.doNameObject(createBuffer,True)
    return infoNull
Exemplo n.º 17
0
def basicEyeJointSurfaceSetup(jointList, jointRoot, surface):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    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)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    baseDistance = distance.returnAverageDistanceBetweenObjectsAndRoot (jointList,jointRoot)
    controls = []
    groups = []
    
    for joint in jointList:
        """ make the control """        
        jointControl = curves.createControlCurve('circle',1)
        scaleFactor = baseDistance*.25
        mc.setAttr((jointControl+'.sx'),scaleFactor)
        mc.setAttr((jointControl+'.sy'),scaleFactor)
        mc.setAttr((jointControl+'.sz'),scaleFactor)
        position.movePointSnap(jointControl,joint)
        position.aimSnap(jointControl,jointRoot,[0,0,-1])
        mc.xform(jointControl,t=[0,0,baseDistance*.4],os=True, r=True)
        mc.makeIdentity(jointControl, apply = True, s=True)
        
        
        """ naming it """
        attributes.storeInfo(jointControl,'cgmName',joint,True)
        attributes.storeInfo(jointControl,'cgmType','controlAnim')
        jointControl = NameFactoryOld.doNameObject(jointControl)
        controls.append(jointControl)
        
        groups.append( rigging.zeroTransformMeObject(jointControl) )
        
    for control in controls:
        indexCount = controls.index(control)
        attachAimedObjectToSurface (jointList[indexCount], surface, control, 'constrain')
Exemplo n.º 18
0
def createInfoNull(infoType):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Creates an infoNull
    
    ARGUMENTS:
    infoType(string)
    
    RETURNS:
    infoNull(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    createBuffer = mc.group(empty=True)
    attributes.storeInfo(createBuffer, 'cgmName', infoType)
    attributes.storeInfo(createBuffer, 'cgmType', 'infoNull')
    mc.xform(createBuffer, os=True, piv=(0, 0, 0))
    infoNull = NameFactory.doNameObject(createBuffer, True)
    return infoNull
Exemplo n.º 19
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]
Exemplo n.º 20
0
def basicEyeJointSurfaceSetup(jointList, jointRoot, surface):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    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)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    baseDistance = distance.returnAverageDistanceBetweenObjectsAndRoot(
        jointList, jointRoot)
    controls = []
    groups = []

    for joint in jointList:
        """ make the control """
        jointControl = curves.createControlCurve('circle', 1)
        scaleFactor = baseDistance * .25
        mc.setAttr((jointControl + '.sx'), scaleFactor)
        mc.setAttr((jointControl + '.sy'), scaleFactor)
        mc.setAttr((jointControl + '.sz'), scaleFactor)
        position.movePointSnap(jointControl, joint)
        position.aimSnap(jointControl, jointRoot, [0, 0, -1])
        mc.xform(jointControl, t=[0, 0, baseDistance * .4], os=True, r=True)
        mc.makeIdentity(jointControl, apply=True, s=True)
        """ naming it """
        attributes.storeInfo(jointControl, 'cgmName', joint, True)
        attributes.storeInfo(jointControl, 'cgmType', 'controlAnim')
        jointControl = NameFactory.doNameObject(jointControl)
        controls.append(jointControl)

        groups.append(rigging.zeroTransformMeObject(jointControl))

    for control in controls:
        indexCount = controls.index(control)
        attachAimedObjectToSurface(jointList[indexCount], surface, control,
                                   'constrain')
Exemplo n.º 21
0
def returnIterateNumber(obj):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Check through a scene to figure out what iterative number an obj

    ARGUMENTS:
    obj(string)

    RETURNS:
    order(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>> input check
    assert mc.objExists(obj) is True, "'%s' doesn't exist" %obj
    
    objToQuery = NameFactory(obj)
    objToQuery.getMatchedParents()
    objToQuery.getMatchedChildren()
    
    # First thing we do is if our object has a parent name object, we process from that object back
    if objToQuery.parentNameCnt:
        parentToQuery = NameFactory(objToQuery.matchedParents[0])
        cnt =  parentToQuery.returnIterator()
        cnt =  cnt + objToQuery.parentNameCnt
        # So we have a top parent
        objNameCandidate = objToQuery.objGeneratedNameDict.copy()
        objNameCandidate['cgmIterator'] = str(cnt)
        bufferName = returnCombinedNameFromDict(objNameCandidate)
        # If it exists in our existing tree, it forces a nameModifier tag
        if mc.objExists(bufferName) and not objToQuery.amIMe(bufferName):
            if bufferName not in objToQuery.matchedChildren and bufferName in parentToQuery.matchedChildren:
                attributes.storeInfo(obj,'cgmNameModifier','branched')
                attributes.storeInfo(obj,'cgmIterator',str(cnt))
                print ("%s has a duplicate in the same heirarchy!" %obj)
        #print ("Count after checking name parent is %i" %cnt)
        return cnt
    #otherwise, we process it by itself
    else:
        cnt = objToQuery.returnIterator()
        return cnt
Exemplo n.º 22
0
def returnIterateNumber(obj):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Check through a scene to figure out what iterative number an obj

    ARGUMENTS:
    obj(string)

    RETURNS:
    order(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>> input check
    assert mc.objExists(obj) is True, "'%s' doesn't exist" % obj

    objToQuery = NameFactory(obj)
    objToQuery.getMatchedParents()
    objToQuery.getMatchedChildren()

    # First thing we do is if our object has a parent name object, we process from that object back
    if objToQuery.parentNameCnt:
        parentToQuery = NameFactory(objToQuery.matchedParents[0])
        cnt = parentToQuery.returnIterator()
        cnt = cnt + objToQuery.parentNameCnt
        # So we have a top parent
        objNameCandidate = objToQuery.objGeneratedNameDict.copy()
        objNameCandidate['cgmIterator'] = str(cnt)
        bufferName = returnCombinedNameFromDict(objNameCandidate)
        # If it exists in our existing tree, it forces a nameModifier tag
        if mc.objExists(bufferName) and not objToQuery.amIMe(bufferName):
            if bufferName not in objToQuery.matchedChildren and bufferName in parentToQuery.matchedChildren:
                attributes.storeInfo(obj, 'cgmNameModifier', 'branched')
                attributes.storeInfo(obj, 'cgmIterator', str(cnt))
                print("%s has a duplicate in the same heirarchy!" % obj)
        #print ("Count after checking name parent is %i" %cnt)
        return cnt
    #otherwise, we process it by itself
    else:
        cnt = objToQuery.returnIterator()
        return cnt
Exemplo n.º 23
0
def createLocFromObject(obj):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Pass  an object into it and get a named locator with stored info for updating it

	ARGUMENTS:
	obj(string)

	RETURNS:
	name(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	# make it
	nameBuffer = mc.spaceLocator()
	buffer = mc.ls(obj,shortNames=True)        	
	#store info
	attributes.storeInfo(nameBuffer[0],'cgmName',buffer[0],False)
	attributes.storeInfo(nameBuffer[0],'cgmLocMode','fromObject',False)

	return ( NameFactory.doNameObject(nameBuffer[0]) )
Exemplo n.º 24
0
def createLocFromObject(obj):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Pass  an object into it and get a named locator with stored info for updating it

	ARGUMENTS:
	obj(string)

	RETURNS:
	name(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    # make it
    nameBuffer = mc.spaceLocator()

    #store info
    attributes.storeInfo(nameBuffer[0], 'cgmName', obj, False)
    attributes.storeInfo(nameBuffer[0], 'cgmLocMode', 'fromObject', False)

    return (NameFactory.doNameObject(nameBuffer[0]))
Exemplo n.º 25
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]
Exemplo n.º 26
0
def createLocFromObject(obj):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Pass  an object into it and get a named locator with stored info for updating it

	ARGUMENTS:
	obj(string)

	RETURNS:
	name(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    # make it
    nameBuffer = mc.spaceLocator()
    buffer = mc.ls(obj, shortNames=True)
    #store info
    attributes.storeInfo(nameBuffer[0], 'cgmName', buffer[0], False)
    attributes.storeInfo(nameBuffer[0], 'cgmLocMode', 'fromObject', False)

    #return nameBuffer[0]
    return mc.rename(nameBuffer[0], "{0}_loc".format(buffer[0]))
Exemplo n.º 27
0
def locMeCenter(objList, forceBBCenter=False):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Pass  an object into it and get a named locator with stored info for updating it

	ARGUMENTS:
	obj(string)

	RETURNS:
	name(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    # make it
    nameBuffer = mc.spaceLocator()

    #store info
    attributes.storeInfo(nameBuffer[0], 'cgmSource', (','.join(objList)),
                         False)
    attributes.storeInfo(nameBuffer[0], 'cgmLocMode', 'selectCenter', False)
    attributes.storeInfo(nameBuffer[0], 'cgmName', (str('_to_'.join(objList))),
                         False)
    attributes.storeInfo(nameBuffer[0], 'cgmTypeModifier', 'midPoint', False)

    posList = []

    for obj in objList:
        if mc.objExists(obj) == True:
            objInfo = returnInfoForLoc(obj, forceBBCenter)
            posList.append(objInfo['position'])

    objTrans = distance.returnAveragePointPosition(posList)

    mc.move(objTrans[0], objTrans[1], objTrans[2], nameBuffer[0])

    #return ( NameFactory.doNameObject(nameBuffer[0]) )
    return mc.rename(nameBuffer[0],
                     "{0}_midPoint_loc".format(str('_to_'.join(objList))))
Exemplo n.º 28
0
    def doSetType(self, setType=None):
        """ Set a set's type """
        assert not self.refState, "Cannot change the type of a referenced set"
        assert not self.mayaSetState, "Cannot change type of a maya default set"

        if setType is not None:
            doSetType = setType
            if setType in setTypes.keys():
                doSetType = setTypes.get(setType)

            if attributes.storeInfo(self.nameLong, 'cgmType', doSetType, True):
                self.doName()
                guiFactory.warning("'%s' renamed!" % (self.nameShort))
                return self.nameShort
            else:
                guiFactory.warning("'%s' failed to store info" %
                                   (self.nameShort))
                return False
        else:
            attributes.doDeleteAttr(self.nameShort, 'cgmType')
            self.doName()
            guiFactory.warning("'%s' renamed!" % (self.nameShort))
            return self.nameShort
Exemplo n.º 29
0
    def doSetType(self,setType = None):
        """ Set a set's type """
	assert not self.refState, "Cannot change the type of a referenced set"
	assert not self.mayaSetState, "Cannot change type of a maya default set"

	
        if setType is not None:
            doSetType = setType
            if setType in setTypes.keys():
                doSetType = setTypes.get(setType)

            if attributes.storeInfo(self.nameLong,'cgmType',doSetType,True):
                self.doName()
                guiFactory.warning("'%s' renamed!"%(self.nameShort))  
                return self.nameShort
            else:               
                guiFactory.warning("'%s' failed to store info"%(self.nameShort))  
                return False
        else:
            attributes.doDeleteAttr(self.nameShort,'cgmType')
            self.doName()
            guiFactory.warning("'%s' renamed!"%(self.nameShort))  
            return self.nameShort
Exemplo n.º 30
0
 def store(self,attr,info,*a,**kw):
     """ Store information to an object in maya via case specific attribute. """
     attributes.storeInfo(self.nameLong,attr,info,*a,**kw)
Exemplo n.º 31
0
def createMasterNull(characterName='nothingNothing'):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Creates a masterNull for a character/asset
    
    ARGUMENTS:
    characterName(string)
    
    RETURNS:
    masterNull(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    if characterName == 'nothingNothing':
        randomOptions = ['David','Josh','NameMe','Homer','Georgie']
        characterName = random.choice(randomOptions)
    
    #Create main null
    masterNullBuffer = mc.group (empty=True)
    attributes.storeInfo(masterNullBuffer,'cgmName',characterName)   
    attributes.storeInfo(masterNullBuffer,'cgmType','ignore')
    attributes.storeInfo(masterNullBuffer,'cgmModuleType','master')
    masterNull = NameFactory.doNameObject(masterNullBuffer)
    
    #Create modules container null
    modulesGroupBuffer = mc.group (empty=True)
    attributes.storeInfo(modulesGroupBuffer,'cgmName','modules')   
    attributes.storeInfo(modulesGroupBuffer,'cgmType','group')
    modulesGroup = NameFactory.doNameObject(modulesGroupBuffer)
    modulesGroup = rigging.doParentReturnName(modulesGroup,masterNull)
    attributes.storeObjectToMessage (modulesGroup, masterNull, 'modulesGroup')
    
    #Create modules container null
    meshGroupBuffer = mc.group (empty=True)
    attributes.storeInfo(meshGroupBuffer,'cgmName','geo')   
    attributes.storeInfo(modulesGroupBuffer,'cgmType','group')
    meshGroup = NameFactory.doNameObject(modulesGroupBuffer)
    meshGroup = rigging.doParentReturnName(meshGroup,masterNull)
    attributes.storeObjectToMessage (meshGroup, masterNull, 'geoGroup')
    
    #Create master info null
    masterInfoNull = createInfoNull('master')
    attributes.storeObjectToMessage (masterInfoNull, masterNull, 'info')
    masterInfoNull = rigging.doParentReturnName(masterInfoNull,masterNull)
    
    #Create modules info null
    modulesInfoNull = createInfoNull('modules')
    attributes.storeObjectToMessage (modulesInfoNull, masterInfoNull, 'modules')
    modulesInfoNull = rigging.doParentReturnName(modulesInfoNull,masterInfoNull)
    
    #Create mesh info null
    meshInfoNull = createInfoNull('geo')
    attributes.storeObjectToMessage (meshInfoNull, masterInfoNull, 'geo')
    modulesInfoNull = rigging.doParentReturnName(meshInfoNull,masterInfoNull)
    
    #Create global settings info null
    settingsInfoNull = createInfoNull('settings')
    attributes.storeObjectToMessage (settingsInfoNull, masterInfoNull, 'settings')
    settingsInfoNull = rigging.doParentReturnName(settingsInfoNull,masterInfoNull)
    defaultFont = returnSettingsData('defaultTextFont')
    attributes.storeInfo(settingsInfoNull,'font',defaultFont)

    return masterNull
Exemplo n.º 32
0
                        pos[i2] = v
                #Let's make our stuff
                if len(pos) == 3:
                    baseScale = distance.returnMayaSpaceFromWorldSpace(10)
                    if self._createMode == 'joint':
                        nameBuffer = mc.joint(radius = 1)
                        #attributes.doSetAttr(nameBuffer,'radius',1)
                        mc.select(cl=True)
                    else:
                        nameBuffer = mc.spaceLocator()[0]

                    mc.move (pos[0],pos[1],pos[2], nameBuffer)

                    for m in self.d_meshPos.keys():#check each mesh dictionary to see where it came from
                        if pos in self.d_meshPos[m]:#if the mesh has a match
                            attributes.storeInfo(nameBuffer,'cgmHitTarget',m)

                            #attributes.doSetAttr(nameBuffer,'localScaleX',(self.f_meshArea*.025))
                            #attributes.doSetAttr(nameBuffer,'localScaleY',(self.f_meshArea*.025))
                            #attributes.doSetAttr(nameBuffer,'localScaleZ',(self.f_meshArea*.025))

                            if self.v_posOffset is not None and self.v_posOffset and nameBuffer and self.str_offsetMode and self._createMode not in ['follicle']:
                                mi_obj = cgmMeta.cgmObject(nameBuffer)
                                mc.move (pos[0],pos[1],pos[2], mi_obj.mNode,ws=True)	
                                if self.str_offsetMode =='vector':
                                    mi_hitLoc = cgmMeta.cgmObject(mc.spaceLocator(n='hitLoc')[0])
                                    mc.move (self.startPoint[0],self.startPoint[1],self.startPoint[2], mi_hitLoc.mNode,ws=True)				
                                    constBuffer = mc.aimConstraint(mi_hitLoc.mNode,mi_obj.mNode,
                                                                   aimVector=[0,0,1],
                                                                   upVector=[0,1,0],
                                                                   worldUpType = 'scene')
Exemplo n.º 33
0
                            log.debug("%s >> %s >> str_mirrorAxis set: %s" %
                                      (self._str_funcCombined, "mirrorSetup",
                                       str_mirrorAxis))
                        except Exception, error:
                            raise StandardError, "str_mirrorAxis : %s | %s" % (
                                str_mirrorAxis, error)
                for mObj in self.mi_control.msgList_get('spacePivots'):
                    try:
                        try:
                            mObj._verifyMirrorable()
                        except Exception, error:
                            raise StandardError, "_mirrorSetup | %s" % (error)
                        #cgmMeta.cgmAttr(mObj,'mirrorSide').doConnectIn(self.mi_control,'mirrorSide')
                        #cgmMeta.cgmAttr(self.mi_control,'mirrorAxis').doCopyTo(mObj,connectTargetToSource = 1)
                        attributes.storeInfo(
                            mObj.mNode, 'mirrorAxis',
                            "{0}.mirrorAxis".format(self.mi_control.mNode))
                        attributes.storeInfo(
                            mObj.mNode, 'mirrorSide',
                            "{0}.mirrorSide".format(self.mi_control.mNode))

                    except Exception, error:
                        raise StandardError, "spacePivot failed failed! {0}| error: {1}".format(
                            mObj, error)

        def _freeze(self):
            shapeParentTo = self.d_kws['shapeParentTo']
            freezeAll = self.d_kws['freezeAll']
            controlType = self.d_kws['controlType']

            if not shapeParentTo:
Exemplo n.º 34
0
def createMasterNull(characterName='nothingNothing'):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Creates a masterNull for a character/asset
    
    ARGUMENTS:
    characterName(string)
    
    RETURNS:
    masterNull(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    if characterName == 'nothingNothing':
        randomOptions = ['David', 'Josh', 'NameMe', 'Homer', 'Georgie']
        characterName = random.choice(randomOptions)

    #Create main null
    masterNullBuffer = mc.group(empty=True)
    attributes.storeInfo(masterNullBuffer, 'cgmName', characterName)
    attributes.storeInfo(masterNullBuffer, 'cgmType', 'ignore')
    attributes.storeInfo(masterNullBuffer, 'cgmModuleType', 'master')
    masterNull = NameFactory.doNameObject(masterNullBuffer)

    #Create modules container null
    modulesGroupBuffer = mc.group(empty=True)
    attributes.storeInfo(modulesGroupBuffer, 'cgmName', 'modules')
    attributes.storeInfo(modulesGroupBuffer, 'cgmType', 'group')
    modulesGroup = NameFactory.doNameObject(modulesGroupBuffer)
    modulesGroup = rigging.doParentReturnName(modulesGroup, masterNull)
    attributes.storeObjectToMessage(modulesGroup, masterNull, 'modulesGroup')

    #Create modules container null
    meshGroupBuffer = mc.group(empty=True)
    attributes.storeInfo(meshGroupBuffer, 'cgmName', 'geo')
    attributes.storeInfo(modulesGroupBuffer, 'cgmType', 'group')
    meshGroup = NameFactory.doNameObject(modulesGroupBuffer)
    meshGroup = rigging.doParentReturnName(meshGroup, masterNull)
    attributes.storeObjectToMessage(meshGroup, masterNull, 'geoGroup')

    #Create master info null
    masterInfoNull = createInfoNull('master')
    attributes.storeObjectToMessage(masterInfoNull, masterNull, 'info')
    masterInfoNull = rigging.doParentReturnName(masterInfoNull, masterNull)

    #Create modules info null
    modulesInfoNull = createInfoNull('modules')
    attributes.storeObjectToMessage(modulesInfoNull, masterInfoNull, 'modules')
    modulesInfoNull = rigging.doParentReturnName(modulesInfoNull,
                                                 masterInfoNull)

    #Create mesh info null
    meshInfoNull = createInfoNull('geo')
    attributes.storeObjectToMessage(meshInfoNull, masterInfoNull, 'geo')
    modulesInfoNull = rigging.doParentReturnName(meshInfoNull, masterInfoNull)

    #Create global settings info null
    settingsInfoNull = createInfoNull('settings')
    attributes.storeObjectToMessage(settingsInfoNull, masterInfoNull,
                                    'settings')
    settingsInfoNull = rigging.doParentReturnName(settingsInfoNull,
                                                  masterInfoNull)
    defaultFont = returnSettingsData('defaultTextFont')
    attributes.storeInfo(settingsInfoNull, 'font', defaultFont)

    return masterNull
Exemplo n.º 35
0
def bakeBlendShapeNode(sourceObject, blendShapeNode, baseNameToUse = False, stripPrefix = False, ignoreInbetweens = False, ignoreTargets = False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for exporting an object's blendshapes

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    stripPrefix(bool) - whether to strip the first '_' segment
    ignoreInbetweens(bool)
    ignoreTargets(list) - targets to ignore in the processing

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    targetDict = returnBlendShapeTargetsAndWeights(sourceObject,blendShapeNode)
    targetSets = []
    blendShapeNodeChannels = []

    for key in targetDict.keys():
        targetSetBuffer = targetDict.get(key)
        targetSets.append(targetSetBuffer)

        baseSet = targetSetBuffer[-1]
        blendShapeNodeChannels.append(baseSet[0])

    blendShapeShortNames = []

    """ first loop gets connections, breaks them and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ get the connection """
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        print blendShapeConnections
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeBuffer,0)


    # Bake it
    bakedGeo = bakeBlendShapes(sourceObject, sourceObject, blendShapeNode, baseNameToUse, stripPrefix, ignoreInbetweens, ignoreTargets)


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """ group for geo """
    meshGroup = mc.group( em=True)
    if baseNameToUse != False:
        attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    return returnList
    def updatePos(self, debugReport=False):
        """
        Get updated position data via shooting rays
        """
        if not self.meshList:
            return guiFactory.warning(
                "No mesh objects have been added to '%s'" % (self.name))

        buffer = screenToWorld(int(self.x),
                               int(self.y))  #get world point and vector!

        self.clickPos = buffer[0]  #Our world space click point
        self.clickVector = buffer[1]  #Camera vector
        self.posBuffer = []  #Clear our pos buffer

        for m in self.meshList:  #Get positions per mesh piece
            #First get the distance to try to check
            checkDistance = self.getDistanceToCheck(m)
            #print ("Checking distance of %s"%checkDistance)
            if m not in self.meshPosDict.keys():
                self.meshPosDict[m] = []
                self.meshUVDict[m] = []

            if mc.objExists(m):
                if self.mode == 'surface':
                    buffer = findMeshIntersection(m, self.clickPos,
                                                  self.clickVector,
                                                  checkDistance)
                    if buffer is not None:
                        hit = self.convertPosToLocalSpace(buffer['hit'])
                        self.posBuffer.append(hit)
                        self.startPoint = self.convertPosToLocalSpace(
                            buffer['source'])
                        self.meshPosDict[m].append(hit)
                        self.meshUVDict[m].append(buffer['uv'])
                else:
                    buffer = findMeshIntersections(m, self.clickPos,
                                                   self.clickVector,
                                                   checkDistance)
                    if buffer:
                        conversionBuffer = []
                        #Need to convert to local space
                        for hit in buffer['hits']:
                            conversionBuffer.append(
                                self.convertPosToLocalSpace(hit))

                        self.posBuffer.extend(conversionBuffer)
                        self.startPoint = self.convertPosToLocalSpace(
                            buffer['source'])

                        self.meshPosDict[m].extend(conversionBuffer)
                        self.meshUVDict[m].extend(buffer['uvs'])

        if not self.posBuffer:
            if debugReport: guiFactory.warning('No hits detected!')
            return

        if self.clampSetting and self.clampSetting < len(self.posBuffer):
            if debugReport:
                guiFactory.warning(
                    "Position buffer was clamped. Check settings if this was not desired."
                )
            self.posBuffer = distance.returnPositionDataDistanceSortedList(
                self.startPoint, self.posBuffer)
            self.posBuffer = self.posBuffer[:self.clampSetting]

        if self.mode == 'midPoint':
            self.posBuffer = [
                distance.returnAveragePointPosition(self.posBuffer)
            ]

        if self.posBuffer:  #Check for closest and just for hits
            if self.closestOnly and self.mode != 'intersections':
                buffer = distance.returnClosestPoint(self.startPoint,
                                                     self.posBuffer)
                self.posBuffer = [buffer]
        else:
            pass
        #guiFactory.warning("No hits detected")

        if self.createMode and self.posBuffer:  # Make our stuff
            #Delete the old stuff
            if self.createModeBuffer and not self.dragStoreMode:
                for o in self.createModeBuffer:
                    try:
                        mc.delete(o)
                    except:
                        pass
                self.createModeBuffer = []

            for pos in self.posBuffer:
                if len(pos) == 3:
                    baseScale = distance.returnMayaSpaceFromWorldSpace(10)
                    if self.createMode == 'joint':
                        nameBuffer = mc.joint(radius=1)
                        #attributes.doSetAttr(nameBuffer,'radius',1)

                        mc.select(cl=True)
                    else:
                        nameBuffer = mc.spaceLocator()[0]
                        for m in self.meshPosDict.keys(
                        ):  #check each mesh dictionary to see where it came from
                            if pos in self.meshPosDict[
                                    m]:  #if the mesh has a match
                                attributes.storeInfo(nameBuffer,
                                                     'cgmHitTarget', m)

                                attributes.doSetAttr(nameBuffer, 'localScaleX',
                                                     (self.meshArea * .025))
                                attributes.doSetAttr(nameBuffer, 'localScaleY',
                                                     (self.meshArea * .025))
                                attributes.doSetAttr(nameBuffer, 'localScaleZ',
                                                     (self.meshArea * .025))
                                break

                    mc.move(pos[0], pos[1], pos[2], nameBuffer)

                    self.createModeBuffer.append(nameBuffer)
                else:
                    if debugReport:
                        guiFactory.warning("'%s' isn't a valid position" % pos)

        if self.dragStoreMode:
            if self.posBuffer:
                for p in self.posBuffer:
                    self.returnList.append(p)

        mc.refresh()  #Update maya to make it interactive!
Exemplo n.º 37
0
    def updatePos(self,debugReport = False):
        """
        Get updated position data via shooting rays
        """
        if not self.meshList:
            return guiFactory.warning("No mesh objects have been added to '%s'"%(self.name))
        
        buffer =  screenToWorld(int(self.x),int(self.y))#get world point and vector!
                
        self.clickPos = buffer[0] #Our world space click point
        self.clickVector = buffer[1] #Camera vector
        self.posBuffer = []#Clear our pos buffer
        
        for m in self.meshList:#Get positions per mesh piece
            #First get the distance to try to check
            checkDistance = self.getDistanceToCheck(m)
            #print ("Checking distance of %s"%checkDistance)
            if m not in self.meshPosDict.keys():
                self.meshPosDict[m] = []
                self.meshUVDict[m] = []
                
            if mc.objExists(m):
                if self.mode == 'surface':
                    buffer = findMeshIntersection(m, self.clickPos , self.clickVector, checkDistance)                
                    if buffer is not None:
                        hit = self.convertPosToLocalSpace( buffer['hit'] )
                        self.posBuffer.append(hit)  
                        self.startPoint = self.convertPosToLocalSpace( buffer['source'] )
                        self.meshPosDict[m].append(hit)
                        self.meshUVDict[m].append(buffer['uv'])
                else:
                    buffer = findMeshIntersections(m, self.clickPos , self.clickVector , checkDistance)                                    
                    if buffer:
                        conversionBuffer = []
                        #Need to convert to local space
                        for hit in buffer['hits']:
                            conversionBuffer.append(self.convertPosToLocalSpace( hit ))
                             
                        self.posBuffer.extend(conversionBuffer)
                        self.startPoint = self.convertPosToLocalSpace( buffer['source'] )
                        
                        self.meshPosDict[m].extend(conversionBuffer)
                        self.meshUVDict[m].extend(buffer['uvs'])
                        
                        
        if not self.posBuffer:
            if debugReport:guiFactory.warning('No hits detected!')
            return
        
        if self.clampSetting and self.clampSetting < len(self.posBuffer):
            if debugReport:guiFactory.warning("Position buffer was clamped. Check settings if this was not desired.")
            self.posBuffer = distance.returnPositionDataDistanceSortedList(self.startPoint,self.posBuffer)
            self.posBuffer = self.posBuffer[:self.clampSetting]
            
        if self.mode == 'midPoint':                
            self.posBuffer = [distance.returnAveragePointPosition(self.posBuffer)]

        if self.posBuffer: #Check for closest and just for hits
            if self.closestOnly and self.mode != 'intersections':
                buffer = distance.returnClosestPoint(self.startPoint,self.posBuffer)
                self.posBuffer = [buffer]               
        else:pass
            #guiFactory.warning("No hits detected")
            
        if self.createMode and self.posBuffer: # Make our stuff
            #Delete the old stuff
            if self.createModeBuffer and not self.dragStoreMode:
                for o in self.createModeBuffer:
                    try:mc.delete(o)
                    except:pass
                self.createModeBuffer = []
            
            for pos in self.posBuffer:
                if len(pos) == 3:
                    baseScale = distance.returnMayaSpaceFromWorldSpace(10)
                    if self.createMode == 'joint':
                        nameBuffer = mc.joint(radius = 1)
                        #attributes.doSetAttr(nameBuffer,'radius',1)
                        
                        mc.select(cl=True)
                    else:
                        nameBuffer = mc.spaceLocator()[0]
                        for m in self.meshPosDict.keys():#check each mesh dictionary to see where it came from
                            if pos in self.meshPosDict[m]:#if the mesh has a match
                                attributes.storeInfo(nameBuffer,'cgmHitTarget',m)
                                
                                attributes.doSetAttr(nameBuffer,'localScaleX',(self.meshArea*.025))
                                attributes.doSetAttr(nameBuffer,'localScaleY',(self.meshArea*.025))
                                attributes.doSetAttr(nameBuffer,'localScaleZ',(self.meshArea*.025))
                                break                              
                        
                    mc.move (pos[0],pos[1],pos[2], nameBuffer)
                    
                    self.createModeBuffer.append(nameBuffer)
                else:
                    if debugReport:guiFactory.warning("'%s' isn't a valid position"%pos)
        
        if self.dragStoreMode:
            if self.posBuffer:
                for p in self.posBuffer:
                    self.returnList.append(p)  
               
        mc.refresh()#Update maya to make it interactive!
Exemplo n.º 38
0
def zeroTransformMeObject(obj, scaleZero=False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Makes sure an object is zeroed out, parents the zero group back to the original objects parent

    ARGUMENTS:
    obj(string)

    RETURNS:
    groupName(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    parent = mc.listRelatives(obj, parent=True, fullPath=True)

    group = groupMeObject(obj, True, True)
    group2 = ''
    attributes.storeInfo(group, 'cgmTypeModifier', 'zero')

    objScale = []
    objScale.append(mc.getAttr(obj + '.sx'))
    objScale.append(mc.getAttr(obj + '.sy'))
    objScale.append(mc.getAttr(obj + '.sz'))

    #Check if we got zero translates
    zeroCheck = mc.xform(obj, q=True, os=True, rp=True)
    if zeroCheck:
        if scaleZero:
            mc.makeIdentity(obj, apply=True, t=0, r=0, s=1)
        group2 = groupMeObject(obj, True, True)
        zeroCheck = mc.xform(obj, q=True, os=True, rp=True)

        zeroCheck = cgmMath.multiplyLists([objScale, zeroCheck])
        mc.xform(group2,
                 t=(-zeroCheck[0], -zeroCheck[1], -zeroCheck[2]),
                 os=True)
        attributes.storeInfo(group, 'cgmTypeModifier', 'zeroParent')
        attributes.storeInfo(group2, 'cgmTypeModifier', 'zero')
        group2 = NameFactoryOld.doNameObject(group2)

        for attr in 'tx', 'ty', 'tz':
            attributes.doSetAttr(obj, attr, 0)

    #Check for zero rotates
    rotateCheck = mc.xform(obj, q=True, os=True, ro=True)
    if rotateCheck:
        if not group2:
            group2 = groupMeObject(obj, True, True)
            attributes.storeInfo(group, 'cgmTypeModifier', 'zeroParent')
            attributes.storeInfo(group2, 'cgmTypeModifier', 'zero')
            NameFactoryOld.doNameObject(group2)

        mc.xform(group2,
                 ro=(rotateCheck[0], rotateCheck[1], rotateCheck[2]),
                 os=True)
        for attr in 'rx', 'ry', 'rz':
            attributes.doSetAttr(obj, attr, 0)
    """
    objScale = []
    objScale.append(mc.getAttr(obj+'.sx'))
    objScale.append(mc.getAttr(obj+'.sy'))
    objScale.append(mc.getAttr(obj+'.sz'))
    grpScale = []
    grpScale.append(mc.getAttr(group+'.sx'))
    grpScale.append(mc.getAttr(group+'.sy'))
    grpScale.append(mc.getAttr(group+'.sz'))
    multScale = cgmMath.multiplyLists([objScale,grpScale])
    
    mc.scale(multScale[0], multScale[1], multScale[2],[group])
    for attr in 'sx','sy','sz':
        attributes.doSetAttr(obj,attr,1)
    """
    return NameFactoryOld.doNameObject(group)
Exemplo n.º 39
0
def locClosest(objectList,targetObject):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Creates a locator on the surface of the last object in a selection set closest
	to each remaining object in the selection

	ARGUMENTS:
	objectList

	RETURNS:
	locatorList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	bufferList = []

	lastObjectType = search.returnObjectType(targetObject)
	
	#Get our source objects locators as sometimes the pivot has no correlation to the objects pivot - like a cv
	fromObjects = []
	for item in objectList:
		fromObjects.append(locMeObject(item))
	

	if lastObjectType == 'mesh':
		if mayaVersion >=2011:
			for item in fromObjects:
				bufferList.append( locMeClosestPointOnMesh(item, targetObject) )
		else:
			guiFactory.warning('Apologies, but in maya 2010 and below this only supports nurbsSurface target objects')
			return False
	elif lastObjectType == 'nurbsSurface':
		for item in fromObjects:
			bufferList.append( locMeClosestUVOnSurface(item, targetObject) )
	elif lastObjectType == 'nurbsCurve':
		if mayaVersion >=2011:
			for item in fromObjects:
				bufferList.append( locMeClosestPointOnCurve(item, targetObject) )
		else:
			guiFactory.warning('Apologies, but in maya 2010 and below this only supports nurbsSurface target objects')
			return False

	else:
		guiFactory.warning('Your target object must be a mesh, nurbsSurface, or nurbsCurve')
		return False

	for loc in fromObjects:
		mc.delete(loc)
		
	for loc in bufferList:
		cnt = bufferList.index(loc)
		storeList = []
		storeList = objectList
		storeList.append(targetObject)
		attributes.storeInfo(loc,'cgmName',('%s_to_%s'%(objectList[0],objectList[-1])),False)		
		attributes.storeInfo(loc,'cgmSource',(','.join(storeList)),False)
		attributes.storeInfo(loc,'cgmLocMode','closestPoint',False)
		attributes.storeInfo(loc,'cgmTypeModifier','closestPoint',False)
		#bufferList[cnt] = NameFactory.doNameObject(loc)
		bufferList[cnt] =  cgmMeta.NameFactory(loc).doNameObject()

	return bufferList[0]
Exemplo n.º 40
0
def bakeCombinedBlendShapeNode(sourceObject, blendShapeNode, baseNameToUse = False, directions=['left','right']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes out from one object that have a split type

    ARGUMENTS:
    sourceObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    directions[list] = (['left','right'])

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(sourceObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    blendShapeNodeChannels = search.returnBlendShapeAttributes(blendShapeNode)
    blendShapeShortNames = []

    """ first loop stores and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeBuffer,0)

    """ Find pairs """
    blendshapePairs = lists.returnMatchedStrippedEndList(blendShapeNodeChannels,directions)

    """ first loop stores and sets everything to 0 """
    for pair in blendshapePairs:
        blendShapeBuffer = (blendShapeNode+'.'+pair[0])
        splitBuffer = pair[0].split('_')
        nameBuffer = splitBuffer[:-1]
        pairBaseName = '_'.join(nameBuffer)

        if '_' in list(pairBaseName):
            newSplitBuffer = pair[0].split('_')
            newNameBuffer = newSplitBuffer[1:]
            blendShapeShortNames.append('_'.join(newNameBuffer))
        else:
            blendShapeShortNames.append(pairBaseName)

    t=1
    pair = 0
    for i in range (len(blendshapePairs)):
        row = i//5
        if t>5:
            t=1
        """ start extracting """
        blendShapeNodeChannelsBuffer = blendshapePairs[pair]
        shape1 = blendShapeNodeChannelsBuffer[0]
        shape2 = blendShapeNodeChannelsBuffer[1]
        blendShape1Buffer = (blendShapeNode+'.'+shape1)
        blendShape2Buffer = (blendShapeNode+'.'+shape2)
        attributes.doSetAttr(blendShape1Buffer,1)
        attributes.doSetAttr(blendShape2Buffer,1)
        dupBuffer = mc.duplicate(sourceObject)


        splitBuffer = blendShapeShortNames[pair].split('_')
        if len(splitBuffer)>1:
            nameBuffer = splitBuffer[:-1]
        else:
            nameBuffer = splitBuffer
        shortName = '_'.join(nameBuffer)

        dupBuffer = mc.rename (dupBuffer,(baseName+shortName))
        """ Unlock it """
        attributes.doSetLockHideKeyableAttr(dupBuffer,False,True,True)

        mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
        bakedGeo.append(dupBuffer)

        attributes.doSetAttr(blendShape1Buffer,0)
        attributes.doSetAttr(blendShape2Buffer,0)
        pair +=1
        t+=1

    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    return returnList
Exemplo n.º 41
0
 def create(self):
     """ Creates a cgm buffer object """        
     buffer = mc.group(em=True)
     attributes.storeInfo(buffer,'cgmName',self.baseName)
     buffer = NameFactory.doNameObject(buffer,True)
     self.storeNameStrings(buffer)
Exemplo n.º 42
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
Exemplo n.º 43
0
def skeletonize(moduleNull, stiffIndex=0):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Basic limb skeletonizer
    
    ARGUMENTS:
    moduleNull(string)
    stiffIndex(int) - the index of the template objects you want to not have roll joints
                      For example, a value of -1 will let the chest portion of a spine 
                      segment be solid instead of having a roll segment. Default is '0'
                      which will put roll joints in every segment
    
    RETURNS:
    limbJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>>Get our info
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    partName = NameFactory.returnUniqueGeneratedName(moduleNull,
                                                     ignore='cgmType')
    """ template null """
    templateNull = modules.returnTemplateNull(moduleNull)
    templateNullData = attributes.returnUserAttrsToDict(templateNull)
    """ template object nulls """
    templatePosObjectsInfoNull = modules.returnInfoTypeNull(
        moduleNull, 'templatePosObjects')
    templateControlObjectsNull = modules.returnInfoTypeNull(
        moduleNull, 'templateControlObjects')
    templatePosObjectsInfoData = attributes.returnUserAttrsToDict(
        templatePosObjectsInfoNull)
    templateControlObjectsData = attributes.returnUserAttrsToDict(
        templateControlObjectsNull)

    jointOrientation = modules.returnSettingsData('jointOrientation')
    moduleRootBuffer = modules.returnInfoNullObjects(moduleNull,
                                                     'templatePosObjects',
                                                     types='templateRoot')
    moduleRoot = moduleRootBuffer[0]
    stiffIndex = templateNullData.get('stiffIndex')
    rollJoints = templateNullData.get('rollJoints')
    """ AutonameStuff """
    divider = NameFactory.returnCGMDivider()
    skinJointsNull = modules.returnInfoTypeNull(moduleNull, 'skinJoints')

    templateObjects = []
    coreNamesArray = []

    #>>>TemplateInfo
    for key in templatePosObjectsInfoData.keys():
        if (mc.attributeQuery(key, node=templatePosObjectsInfoNull,
                              msg=True)) == True:
            templateObjects.append(templatePosObjectsInfoData[key])
        coreNamesArray.append(key)

    posTemplateObjects = []
    """ Get the positional template objects"""
    for obj in templateObjects:
        bufferList = obj.split(divider)
        if (typesDictionary.get('templateObject')) in bufferList:
            posTemplateObjects.append(obj + divider +
                                      typesDictionary.get('locator'))
    """put objects in order of closeness to root"""
    posTemplateObjects = distance.returnDistanceSortedList(
        moduleRoot, posTemplateObjects)
    curve = (templatePosObjectsInfoData['curve'])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Actually making the skeleton with consideration for roll joints and the stiffIndex!
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    if stiffIndex == 0:
        """ If no roll joints """
        limbJoints = joints.createJointsFromCurve(curve, partName, rollJoints)
    else:
        rolledJoints = joints.createJointsFromCurve(curve, partName,
                                                    rollJoints)
        if rollJoints == 0:
            limbJoints = rolledJoints
        else:
            if stiffIndex < 0:
                """ Get our to delete number in a rolledJoints[-4:] format"""
                #searchIndex = (int('%s%s' %('-',(rollJoints+1)))*abs(stiffIndex)-1)
                searchIndex = (int('%s%s' % ('-', (rollJoints + 1))) *
                               abs(stiffIndex))
                toDelete = rolledJoints[searchIndex:]
                """ delete out the roll joints we don't want"""
                mc.delete(toDelete[0])
                for name in toDelete:
                    rolledJoints.remove(name)
                """ make our stiff joints """
                jointPositions = []
                if abs(stiffIndex) == 1:
                    jointPositions.append(
                        distance.returnClosestUPosition(
                            posTemplateObjects[stiffIndex], curve))
                else:
                    for obj in posTemplateObjects[stiffIndex:]:
                        jointPositions.append(
                            distance.returnClosestUPosition(obj, curve))

                stiffJoints = joints.createJointsFromPosListName(
                    jointPositions, 'partName')
                """ connect em up """
                mc.parent(stiffJoints[0], rolledJoints[-1])
                limbJoints = []
                for joint in rolledJoints:
                    limbJoints.append(joint)
                for joint in stiffJoints:
                    limbJoints.append(joint)

            else:
                """ if it's not negative, it's positive...."""
                searchIndex = ((rollJoints + 1) * abs(stiffIndex))
                toDelete = rolledJoints[:searchIndex]
                toKeep = rolledJoints[searchIndex:]
                """ delete out the roll joints we don't want"""
                mc.parent(toKeep[0], world=True)
                mc.delete(toDelete[0])
                for name in toDelete:
                    rolledJoints.remove(name)
                """ make our stiff joints """
                jointPositions = []
                if abs(stiffIndex) == 1:
                    jointPositions.append(
                        distance.returnClosestUPosition(
                            posTemplateObjects[stiffIndex - 1], curve))
                else:
                    for obj in posTemplateObjects[:stiffIndex]:
                        jointPositions.append(
                            distance.returnClosestUPosition(obj, curve))

                stiffJoints = joints.createJointsFromPosListName(
                    jointPositions, 'partName')
                """ connect em up """
                mc.parent(rolledJoints[0], stiffJoints[-1])
                limbJoints = []
                for joint in stiffJoints:
                    limbJoints.append(joint)
                for joint in rolledJoints:
                    limbJoints.append(joint)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Naming
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ 
    Copy naming information from template objects to the joints closest to them
    copy over a cgmNameModifier tag from the module first
    """
    attributes.copyUserAttrs(moduleNull,
                             limbJoints[0],
                             attrsToCopy=['cgmNameModifier'])
    """
    First we need to find our matches
    """
    for obj in posTemplateObjects:
        closestJoint = distance.returnClosestObject(obj, limbJoints)
        transferObj = attributes.returnMessageObject(obj, 'cgmName')
        """Then we copy it"""
        attributes.copyUserAttrs(
            transferObj,
            closestJoint,
            attrsToCopy=['cgmNameModifier', 'cgmDirection', 'cgmName'])

    limbJointsBuffer = NameFactory.doRenameHeir(limbJoints[0])
    limbJoints = []
    limbJoints.append(limbJointsBuffer[0])
    for joint in limbJointsBuffer[1]:
        limbJoints.append(joint)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Orientation
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    limbJoints = orientSegment(limbJoints, posTemplateObjects,
                               jointOrientation)

    #>>> Set its radius and toggle axis visbility on
    #averageDistance = distance.returnAverageDistanceBetweenObjects (limbJoints)
    jointSize = (
        distance.returnDistanceBetweenObjects(limbJoints[0], limbJoints[-1]) /
        6)
    for jnt in limbJoints:
        mc.setAttr((jnt + '.radi'), jointSize * .2)
        #>>>>>>> TEMP
        joints.toggleJntLocalAxisDisplay(jnt)

    print 'to orientation'
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Storing data
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    skinJointsNull = modules.returnInfoTypeNull(moduleNull, 'skinJoints')
    skinJointsNullData = attributes.returnUserAttrsToList(skinJointsNull)
    existingSkinJoints = lists.removeMatchedIndexEntries(
        skinJointsNullData, 'cgm')
    print existingSkinJoints
    if len(existingSkinJoints) > 0:
        for entry in existingSkinJoints:
            attrBuffer = (skinJointsNull + '.' + entry[0])
            print attrBuffer
            attributes.doDeleteAttr(skinJointsNull, entry[0])

    for i in range(len(limbJoints)):
        buffer = ('%s%s' % ('joint_', i))
        attributes.storeInfo(skinJointsNull, buffer, limbJoints[i])

    return limbJoints
Exemplo n.º 44
0
def polyUniteGeo(objList,name='unitedGeo'):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Unites polys with the poly unite command. Every piece of geo must have
    a deformer node with an .outputGeometry

    ARGUMENTS:
    objList(string)
    name(string) - base name for the geo and node created

    RETURNS:
    returnList = [unifedGeoName,polyUniteNode]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    geoOutNodes = []

    """ get all of the outMesh possibilities"""
    for obj in objList:
        outGeoNode = False
        deformers = returnObjectDeformers(obj)
        if deformers:
            for i in range(len(deformers)):
                if mc.objExists(deformers[i]+'.outputGeometry') == True:
                    #Check for FFD
                    if search.returnObjectType(deformers[i]) == 'ffd':
                        geoShapes = mc.listRelatives(obj,shapes=True,fullPath=True)
                        for shape in geoShapes:
                            if 'Deformed' in shape and mc.objExists(shape+'.outMesh') == True:
                                outGeoNode = (shape+'.outMesh')
                                geoOutNodes.append(shape)                        
                    else:
                        outGeoNode = (deformers[i]+'.outputGeometry')
                        geoOutNodes.append(outGeoNode)
                if outGeoNode != False:
                    break
        else:
            geoShapes = mc.listRelatives(obj,shapes=True,fullPath=True)
            if mc.objExists(geoShapes[0]+'.outMesh') == True:
                outGeoNode = (geoShapes[0]+'.outMesh')
                geoOutNodes.append(geoShapes[0])

    if len(geoOutNodes) != len(objList):
        print "Don't have connections for all geo pieces"
        return False

    """ check for a dup list"""
    #geoOutNodes = lists.returnListNoDuplicates(geoOutNodes)
    

    """ make the node """
    uniteNode = mc.createNode('polyUnite')
    uniteNode = mc.rename(uniteNode,(name+'_polyUniteNode'))

    
    """ connect our stuff """
    nodeTracker = []
    for obj in objList:
        print "On '%s'"%obj
        try:
            index = objList.index(obj)
            print geoOutNodes[index]
            if search.returnObjectType( (geoOutNodes[index]) ) is 'shape':
                mc.connectAttr(('%s%s'% (geoOutNodes[index],'.outMesh')),('%s%s%i%s'% (uniteNode,'.inputPoly[',index,']')),f=True)
                mc.connectAttr(('%s%s'% (obj,'.worldMatrix[0]')),('%s%s%i%s'% (uniteNode,'.inputMat[',index,']')),f=True)
            else:
                # Check if we've already used this connection, if so we need to iterate
                if geoOutNodes[index] in nodeTracker:
                    mc.connectAttr(('%s%s%i%s'% (geoOutNodes[index],'[', (nodeTracker.count(geoOutNodes[index]) ) ,']')),('%s%s%i%s'% (uniteNode,'.inputPoly[',index,']')),f=True)
                else:
                    mc.connectAttr(('%s%s'% (geoOutNodes[index],'[0]')),('%s%s%i%s'% (uniteNode,'.inputPoly[',index,']')),f=True)
                mc.connectAttr(('%s%s'% (obj,'.worldMatrix[0]')),('%s%s%i%s'% (uniteNode,'.inputMat[',index,']')),f=True)
                nodeTracker.append(geoOutNodes[index])
            
        except:
            guiFactory.warning("'%s' failed to add. Verify that the object is polyGeo"%obj)
        
    """ Create our outPut mesh"""
    unitedGeoShape = mc.createNode('mesh')
    unitedGeo = mc.listRelatives(unitedGeoShape,parent=True,type='transform')

    # and the group parts node
    groupPartsNode = mc.createNode('groupParts')
    groupPartsNode = mc.rename(groupPartsNode,(name+'_groupParts'))

    """ Connect it up """
    mc.connectAttr((uniteNode+'.output'),(groupPartsNode+'.inputGeometry'))
    mc.connectAttr((groupPartsNode+'.outputGeometry'),(unitedGeoShape+'.inMesh'))

    """Store and return"""
    attributes.storeInfo(unitedGeo[0],'cgmName',name)
    attributes.storeInfo(unitedGeo[0],'cgmType','polyUniteGeo')
    unitedGeo = mc.rename(unitedGeo[0],(name+'_UniteGeo'))

    attributes.storeInfo(uniteNode,'cgmSourceObjects',(';'.join(objList)))
    attributes.storeInfo(uniteNode,'cgmResultGeo',(unitedGeo))

    return [unitedGeo,uniteNode,groupPartsNode]
Exemplo n.º 45
0
def bakeBlendShapeNodeToTargetObject(targetObject,sourceObject, blendShapeNode, baseNameToUse = False, stripPrefix = False,ignoreInbetweens = False, ignoreTargets = False, transferConnections = True):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes from one object to another

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseNameToUse(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    stripPrefix(bool)
    ignoreInbetweens(bool)
    ignoreTargets(list) - list of targets to ignore
    transferConnections(bool) - if True, builds a new blendshape node and transfers the connections from our base objects

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(targetObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'

    """ wrap deform object """
    wrapBuffer = wrapDeformObject(targetObject,sourceObject,True)
    targetObjectBaked = wrapBuffer[1]

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    blendShapeNodeChannels = returnBlendShapeAttributes(blendShapeNode)

    blendShapeShortNames = []
    """ first loop stores and sets everything to 0 """

    for shape in blendShapeNodeChannels:
        keepGoing = True
        if ignoreTargets != False:
            if shape in ignoreTargets:
                keepGoing = False
            else:
                keepGoing = True

        blendShapeBuffer = (blendShapeNode + '.' + shape)
        """ get the connection """
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))

        if keepGoing == True:
            print ('breaking....' + blendShapeBuffer)
            """break it """
            attributes.doBreakConnection(blendShapeBuffer)
            attributes.doSetAttr(blendShapeNode,shape,0)

    # Bake it
    bakedGeo = bakeBlendShapes(sourceObject, targetObjectBaked, blendShapeNode, baseNameToUse, stripPrefix, ignoreInbetweens, ignoreTargets)


    """ restore connections """
    for shape in blendShapeNodeChannels:
        keepGoing = True
        if ignoreTargets != False:
            if shape in ignoreTargets:
                keepGoing = False
            else:
                keepGoing = True

        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if keepGoing == True:
            print ('connecting....' + blendShapeBuffer)
            print blendShapeConnections[currentIndex]
            if blendShapeConnections[currentIndex] != False:
                attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)


    # Need to build a new blendshape node?
    if transferConnections == True:
        # Build it
        newBlendShapeNode = buildBlendShapeNode(targetObject, bakedGeo, baseNameToUse)

        newBlendShapeChannels = returnBlendShapeAttributes(newBlendShapeNode)

        for shape in newBlendShapeChannels:
            blendShapeBuffer = (newBlendShapeNode+'.'+shape)
            currentIndex = newBlendShapeChannels.index(shape)
            if blendShapeConnections[currentIndex] != False:
                attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """delete the wrap"""
    mc.delete(wrapBuffer[0])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    if baseNameToUse != False:
        attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    mc.delete(targetObjectBaked)
    return returnList
Exemplo n.º 46
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
Exemplo n.º 47
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
Exemplo n.º 48
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]
Exemplo n.º 49
0
def bakeCombinedBlendShapeNodeToTargetObject(targetObject,sourceObject, blendShapeNode, baseName = False, directions=['left','right']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes from one object to another when you have a left/right variant

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    directions[list] = (['left','right'])

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(targetObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseName == False:
        baseName = ''
    else:
        baseName = baseName + '_'

    """reference check """
    refPrefix = search.returnReferencePrefix(sourceObject)
    if refPrefix != False:
        referencePrefix = (search.returnReferencePrefix(sourceObject) + ':')
    else:
        referencePrefix = ''

    """ wrap deform object """
    wrapBuffer = wrapDeformObject(targetObject,sourceObject,True)
    targetObjectBaked = wrapBuffer[1]

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    #setAttr ($wrapDeformer[0] + ".autoWeightThreshold") 1;
    """ cause maya is stupid and doesn't have a python equivalent"""
    mc.select(targetObjectBaked,r=True)
    mc.select(sourceObject,tgl=True)
    mel.eval('AddWrapInfluence')
    mc.select(cl=True)

    """
    may need to add this in later
    //reorders deformation order for proper baking of skinned mesh
    //reorderDeformers "tweak1" "face_skinCluster" $deformerGeo;
    """

    blendShapeNodeChannels = search.returnBlendShapeAttributes(blendShapeNode)
    blendShapeShortNames = []

    """ first loop stores and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeNode,shape,0)

    """ Find pairs """
    blendshapePairs = lists.returnMatchedStrippedEndList(blendShapeNodeChannels,directions)

    """ first loop stores and sets everything to 0 """
    for pair in blendshapePairs:
        blendShapeBuffer = (blendShapeNode+'.'+pair[0])
        splitBuffer = pair[0].split('_')
        nameBuffer = splitBuffer[:-1]
        pairBaseName = '_'.join(nameBuffer)

        if '_' in list(pairBaseName):
            newSplitBuffer = pair[0].split('_')
            newNameBuffer = newSplitBuffer[1:]
            blendShapeShortNames.append('_'.join(newNameBuffer))
        else:
            blendShapeShortNames.append(pairBaseName)

    t=1
    pair = 0
    for i in range (len(blendshapePairs)):
        row = i//5
        if t>5:
            t=1
        """ start extracting """
        blendShapeNodeChannelsBuffer = blendshapePairs[pair]
        shape1 = blendShapeNodeChannelsBuffer[0]
        shape2 = blendShapeNodeChannelsBuffer[1]
        attributes.doSetAttr(blendShapeNode,shape1,1)
        attributes.doSetAttr(blendShapeNode,shape2,1)
        dupBuffer = mc.duplicate(targetObjectBaked)
        splitBuffer = blendShapeShortNames[pair].split('_')
        nameBuffer = splitBuffer[:-1]
        shortName = '_'.join(nameBuffer)

        dupBuffer = mc.rename (dupBuffer,(baseName+shortName))
        mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
        bakedGeo.append(dupBuffer)

        attributes.doSetAttr(blendShapeNode,shape1,0)
        attributes.doSetAttr(blendShapeNode,shape2,0)
        pair +=1
        t+=1

    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """delete the wrap"""
    mc.delete(wrapBuffer[0])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    attributes.storeInfo(meshGroup,'cgmName', baseName)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    mc.delete(targetObjectBaked)
    return returnList
Exemplo n.º 50
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)
Exemplo n.º 51
0
def zeroTransformMeObject(obj,scaleZero=False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Makes sure an object is zeroed out, parents the zero group back to the original objects parent

    ARGUMENTS:
    obj(string)

    RETURNS:
    groupName(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    parent = mc.listRelatives(obj,parent=True,fullPath = True)

    group = groupMeObject(obj,True,True)
    group2 = ''
    attributes.storeInfo(group,'cgmTypeModifier','zero')
    
    
    objScale = []
    objScale.append(mc.getAttr(obj+'.sx'))
    objScale.append(mc.getAttr(obj+'.sy'))
    objScale.append(mc.getAttr(obj+'.sz'))
    
    #Check if we got zero translates
    zeroCheck = mc.xform (obj, q=True, os=True, rp=True)
    if zeroCheck:
        if scaleZero:
            mc.makeIdentity(obj,apply=True,t=0,r=0,s=1)              
        group2 = groupMeObject(obj,True,True)
        zeroCheck = mc.xform (obj, q=True, os=True, rp=True)
        
        zeroCheck = cgmMath.multiplyLists([objScale,zeroCheck])
        mc.xform (group2,t=(-zeroCheck[0],-zeroCheck[1],-zeroCheck[2]), os=True)
        attributes.storeInfo(group,'cgmTypeModifier','zeroParent')
        attributes.storeInfo(group2,'cgmTypeModifier','zero')
        group2 = NameFactoryOld.doNameObject(group2) 
    
        for attr in 'tx','ty','tz':
            attributes.doSetAttr(obj, attr, 0)
    
    #Check for zero rotates
    rotateCheck = mc.xform(obj, q=True, os=True, ro=True)
    if rotateCheck:
        if not group2:
            group2 = groupMeObject(obj,True,True)
            attributes.storeInfo(group,'cgmTypeModifier','zeroParent')
            attributes.storeInfo(group2,'cgmTypeModifier','zero')
            NameFactoryOld.doNameObject(group2) 
        
        mc.xform (group2,ro=(rotateCheck[0],rotateCheck[1],rotateCheck[2]), os=True)
        for attr in 'rx','ry','rz':
            attributes.doSetAttr(obj, attr, 0)        
    
    """
    objScale = []
    objScale.append(mc.getAttr(obj+'.sx'))
    objScale.append(mc.getAttr(obj+'.sy'))
    objScale.append(mc.getAttr(obj+'.sz'))
    grpScale = []
    grpScale.append(mc.getAttr(group+'.sx'))
    grpScale.append(mc.getAttr(group+'.sy'))
    grpScale.append(mc.getAttr(group+'.sz'))
    multScale = cgmMath.multiplyLists([objScale,grpScale])
    
    mc.scale(multScale[0], multScale[1], multScale[2],[group])
    for attr in 'sx','sy','sz':
        attributes.doSetAttr(obj,attr,1)
    """
    return NameFactoryOld.doNameObject(group)
Exemplo n.º 52
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]