def _validate(self): assert type(self.d_kws['addExtraGroups']) in [int, bool] assert type(self.d_kws['addSpacePivots']) in [int, bool] i_obj = self.mi_control self.mi_control = cgmMeta.asMeta(i_obj, 'cgmControl', setClass=True) self.str_mirrorAxis = VALID.stringArg( self.d_kws['mirrorAxis'], calledFrom=self._str_funcCombined) self.str_mirrorSide = VALID.stringArg( self.d_kws['mirrorSide'], calledFrom=self._str_funcCombined) self.b_makeMirrorable = VALID.boolArg( self.d_kws['makeMirrorable'], calledFrom=self._str_funcCombined) self._addMirrorAttributeBridges = self.d_kws.get( 'addMirrorAttributeBridges') or False if self._addMirrorAttributeBridges: if type(self._addMirrorAttributeBridges) not in [list, tuple]: raise StandardError, "[Bad addMirrorAttributeBridge arg]{arg: %s}" % self._addMirrorAttributeBridge for i, l in enumerate(self._addMirrorAttributeBridges): if type(l) not in [list, tuple]: raise StandardError, "[Bad addMirrorAttributeBridge arg: %s]{arg: %s}" % ( i, l) # Running lists ------------------------------------------------------------------------------------------ self.ml_groups = [] #Holder for groups self.ml_constraintGroups = [] self.ml_spacePivots = []
def test_unicode(self): uArg = u"CGMonks" self.assertEqual( validateArgs.stringArg(uArg, noneValid=True), uArg, "validateArgs.stringArgs did not return the unicode "+\ "it was passed when noneValid=True") self.assertEqual( validateArgs.stringArg(uArg, noneValid=False), uArg, "validateArgs.stringArgs did not return the unicode "+\ "it was passed when noneValid=False")
def get_all_parents(node=None, shortNames=True): """ Get all the parents of a given node where the last parent is the top of the heirarchy :parameters: node(str): Object to check shortNames(bool): Whether you just want short names or long :returns parents(list) """ _str_func = 'get_all_parents' _node = VALID.stringArg(node, False, _str_func) _l_parents = [] tmpObj = node noParent = False while noParent == False: tmpParent = mc.listRelatives(tmpObj, allParents=True, fullPath=True) if tmpParent: if len(tmpParent) > 1: raise ValueError, "Resolve what to do with muliple parents...{0} | {1}".format( node, tmpParent) _l_parents.append(tmpParent[0]) tmpObj = tmpParent[0] else: noParent = True if shortNames: return [NAME.get_short(o) for o in _l_parents] return _l_parents
def __func__(self): """ """ self.mi_baseCurve = cgmMeta.validateObjArg(self.d_kws['baseCurve'],mayaType='nurbsCurve',noneValid=False) self._str_funcCombined = self._str_funcCombined + "(%s)"%self.mi_baseCurve.p_nameShort self.str_arg = cgmValid.stringArg(self.d_kws['arg'],noneValid=True) self.b_keepOriginal = cgmValid.boolArg(self.d_kws['keepOriginal'], calledFrom=self._str_funcCombined) if isEP(self.mi_baseCurve): log.warning("%s %s already an ep curve"%(self._str_reportStart,self.mi_baseCurve.p_nameShort)) return False mi_crv = self.mi_baseCurve if self.str_arg.lower() == 'ep': l_pos = [] for cv in mi_crv.getComponents('cv'): locatorName = locators.locMeObject(cv) pos = distance.returnClosestUPosition(locatorName,mi_crv.mNode) mc.delete(locatorName) l_pos.append( pos ) if not self.b_keepOriginal:mi_crv.delete() return mc.curve(d = 2,ep = l_pos, os = True) #return curves.curveFromPosList(l_pos) raise NotImplementedError,"arg: %s"%self.str_arg
def stripInvalidChars(arg = None,invalidChars = """`~!@#$%^&*()-+=[]\\{}|;':"/?><., """, functionSwap = True, replaceChar = '', cleanDoubles = True, stripTailing=True): """ Modified from Hamish MacKenzie's zoo one returns l_pos """ _str_funcName = 'stripInvalidChars' try: str_Clean = cgmValid.stringArg(arg,False,_str_funcName) for char in invalidChars: if functionSwap and char in d_functionStringSwaps.keys(): str_Clean = str_Clean.replace( char, d_functionStringSwaps.get(char) ) else: str_Clean = str_Clean.replace( char, replaceChar ) for n in range(10): while str_Clean.startswith( str(n) ): log.debug("Cleaning : %s"%str(n)) str_Clean = str_Clean[ 1: ] if cleanDoubles and replaceChar: doubleChar = replaceChar + replaceChar while doubleChar in cleanStr: str_Clean = str_Clean.replace( doubleChar, replaceChar ) if stripTailing: while str_Clean.endswith( '_' ): str_Clean = str_Clean[ :-1 ] return str_Clean except StandardError,error: raise StandardError,"%s >>> error : %s"%(_str_funcName,error)
def get_nodeTagInfo(node=None, tag=None): """ Get the info on a given node with a provided tag :parameters: node(str): Object to check :returns status(bool) """ _str_func = 'get_nodeTagInfo' _node = VALID.stringArg(node, False, _str_func) if (mc.objExists('%s.%s' % (_node, tag))) == True: messageQuery = (mc.attributeQuery(tag, node=_node, msg=True)) if messageQuery == True: log.debug("|{0}| >> message...".format(_str_func)) returnBuffer = attributes.returnMessageData(_node, tag, False) if not returnBuffer: return False elif VALID.get_mayaType(returnBuffer[0]) == 'reference': if attributes.repairMessageToReferencedTarget(_node, tag): return attributes.returnMessageData(_node, tag, False)[0] return returnBuffer[0] return returnBuffer[0] else: log.debug("|{0}| >> reg...".format(_str_func)) infoBuffer = mc.getAttr('%s.%s' % (_node, tag)) if infoBuffer is not None and len(list(str(infoBuffer))) > 0: return infoBuffer else: return False else: return False
def test_string(self): ''' Confirm that the function will return the same value if it is passed a string or unicode. ''' arg = "CGMonks" self.assertEqual( validateArgs.stringArg(arg, noneValid=True), arg, "validateArgs.stringArgs did not return the string "+\ "it was passed when noneValid=True") self.assertEqual( validateArgs.stringArg(arg, noneValid=False), arg, "validateArgs.stringArgs did not return the string "+\ "it was passed when noneValid=False")
def _mirrorAttributeBridges_(self): addForwardBack = self.d_kws['addForwardBack'] if addForwardBack: mPlug_forwardBackDriver = cgmMeta.cgmAttr(self.mi_control,"forwardBack",attrType = 'float',keyable=True) try: mPlug_forwardBackDriven = cgmMeta.validateAttrArg([self.mi_control,addForwardBack])['mi_plug'] except Exception,error:raise StandardError,"push pull driver | %s"%(error) if self.str_mirrorSide.lower() == 'right': arg_forwardBack = "%s = -%s"%(mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) else: arg_forwardBack = "%s = %s"%(mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) mPlug_forwardBackDriven.p_locked = True mPlug_forwardBackDriven.p_hidden = True mPlug_forwardBackDriven.p_keyable = False NodeF.argsToNodes(arg_forwardBack).doBuild() if self._addMirrorAttributeBridges: for l_bridge in self._addMirrorAttributeBridges: _attrName = cgmValid.stringArg(l_bridge[0]) _attrToBridge = cgmValid.stringArg(l_bridge[1]) if not self.mi_control.hasAttr(_attrToBridge): raise StandardError,"['%s' lacks the bridge attr '%s']"%(self.mi_control.p_nameShort,_attrToBridge) mPlug_attrBridgeDriver = cgmMeta.cgmAttr(self.mi_control,_attrName,attrType = 'float',keyable=True) try: mPlug_attrBridgeDriven = cgmMeta.validateAttrArg([self.mi_control,_attrToBridge])['mi_plug'] except Exception,error:raise StandardError,"[validate control attribute bridge attr]{%s}"%(error) if self.str_mirrorSide.lower() == 'right': arg_attributeBridge = "%s = -%s"%(mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) else: arg_attributeBridge = "%s = %s"%(mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) mPlug_attrBridgeDriven.p_locked = True mPlug_attrBridgeDriven.p_hidden = True mPlug_attrBridgeDriven.p_keyable = False NodeF.argsToNodes(arg_attributeBridge).doBuild()
def _mirrorAttributeBridges_(self): addForwardBack = self.d_kws['addForwardBack'] if addForwardBack: mPlug_forwardBackDriver = cgmMeta.cgmAttr(self.mi_control,"forwardBack",attrType = 'float',keyable=True) try: mPlug_forwardBackDriven = cgmMeta.validateAttrArg([self.mi_control,addForwardBack])['mi_plug'] except Exception,error:raise StandardError,"push pull driver | %s"%(error) if self.str_mirrorSide.lower() == 'right': arg_forwardBack = "%s = -%s"%(mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) else: arg_forwardBack = "%s = %s"%(mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) mPlug_forwardBackDriven.p_locked = True mPlug_forwardBackDriven.p_hidden = True mPlug_forwardBackDriven.p_keyable = False NodeF.argsToNodes(arg_forwardBack).doBuild() if self._addMirrorAttributeBridges: for l_bridge in self._addMirrorAttributeBridges: _attrName = VALID.stringArg(l_bridge[0]) _attrToBridge = VALID.stringArg(l_bridge[1]) if not self.mi_control.hasAttr(_attrToBridge): raise StandardError,"['%s' lacks the bridge attr '%s']"%(self.mi_control.p_nameShort,_attrToBridge) mPlug_attrBridgeDriver = cgmMeta.cgmAttr(self.mi_control,_attrName,attrType = 'float',keyable=True) try: mPlug_attrBridgeDriven = cgmMeta.validateAttrArg([self.mi_control,_attrToBridge])['mi_plug'] except Exception,error:raise StandardError,"[validate control attribute bridge attr]{%s}"%(error) if self.str_mirrorSide.lower() == 'right': arg_attributeBridge = "%s = -%s"%(mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) else: arg_attributeBridge = "%s = %s"%(mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) mPlug_attrBridgeDriven.p_locked = True mPlug_attrBridgeDriven.p_hidden = True mPlug_attrBridgeDriven.p_keyable = False NodeF.argsToNodes(arg_attributeBridge).doBuild()
def test_nonStringValidTrue(self): ''' Confirm that the function will return false if the value passed is not a string but noneValid is set to True. ''' self.assertFalse( validateArgs.stringArg(None, noneValid=True), "validateArgs.stringArgs did not return False "+\ "when passed a nont-string value when noneValid=True" )
def _validate(self): assert type(self.d_kws['addExtraGroups']) in [int,bool] assert type(self.d_kws['addSpacePivots']) in [int,bool] i_obj = self.mi_control self.mi_control = cgmMeta.asMeta(i_obj,'cgmControl', setClass=True) self.str_mirrorAxis = cgmValid.stringArg(self.d_kws['mirrorAxis'],calledFrom = self._str_funcCombined) self.str_mirrorSide = cgmValid.stringArg(self.d_kws['mirrorSide'],calledFrom = self._str_funcCombined) self.b_makeMirrorable = cgmValid.boolArg(self.d_kws['makeMirrorable'],calledFrom = self._str_funcCombined) self._addMirrorAttributeBridges = self.d_kws.get('addMirrorAttributeBridges') or False if self._addMirrorAttributeBridges : if type(self._addMirrorAttributeBridges ) not in [list,tuple]:raise StandardError,"[Bad addMirrorAttributeBridge arg]{arg: %s}"%self._addMirrorAttributeBridge for i,l in enumerate(self._addMirrorAttributeBridges): if type(l) not in [list,tuple]:raise StandardError,"[Bad addMirrorAttributeBridge arg: %s]{arg: %s}"%(i,l) # Running lists ------------------------------------------------------------------------------------------ self.ml_groups = []#Holder for groups self.ml_constraintGroups = [] self.ml_spacePivots = []
def validateModifier(self): _modifier = self._d_fromUI.get('modifier', self._d_kws['modifier']) if _modifier is None: return False elif cgmValid.stringArg(_modifier): if _modifier.lower() in cgmHotkeyer._l_modifierOptions: return _modifier else:return False elif cgmValid.valueArg(_modifier, inRange = [0,len(cgmHotkeyer._l_modifierOptions)]): return cgmHotkeyer._l_modifierOptions[_modifier] return False
def _validate(self): """ Validate the args, get our data """ self.mi_baseCurve = cgmMeta.validateObjArg(self.d_kws['baseCurve'],mayaType='nurbsCurve',noneValid=False) self.mi_targetCurve = cgmMeta.validateObjArg(self.d_kws['targetCurve'],mayaType='nurbsCurve',noneValid=True) self.f_threshold = cgmValid.valueArg(self.d_kws['mirrorThreshold'],calledFrom = self._str_funcCombined) self.str_mirrorAcross = cgmValid.stringArg(self.d_kws['mirrorAcross'],noneValid=True) self.int_across = 0#This is the index to check -- ie pos[0] for x if self.str_mirrorAcross.lower() != 'x': raise NotImplementedError, "Only implmeneted x mirror so far | kw: %s"%self.str_mirrorAcross
def stripInvalidChars(arg=None, invalidChars="""`~!@#$%^&*()-+=[]\\{}|;':"/?><., """, noNumberStart=True, functionSwap=True, replaceChar='', cleanDoubles=True, stripTailing=True): """ Modified from Hamish MacKenzie's zoo one :parameters: arg(str) - String to clean invalidChars(str) - Sequence of characters to remove noNumberStart(bool) - remove numbers at start functionSwap(bool) - whether to replace functions with string from dict replaceChar(str) - Character to use to replace with cleanDoubles(bool) - remove doubles stripTrailing(bool) - remove trailing '_' returns l_pos """ _str_funcName = 'stripInvalidChars' try: str_Clean = cgmValid.stringArg(arg, False, _str_funcName) for char in invalidChars: if functionSwap and char in d_functionStringSwaps.keys(): str_Clean = str_Clean.replace(char, d_functionStringSwaps.get(char)) else: str_Clean = str_Clean.replace(char, replaceChar) if noNumberStart: for n in range(10): while str_Clean.startswith(str(n)): log.debug("Cleaning : %s" % str(n)) str_Clean = str_Clean[1:] if cleanDoubles and replaceChar: doubleChar = replaceChar + replaceChar while doubleChar in str_Clean: str_Clean = str_Clean.replace(doubleChar, replaceChar) if stripTailing: while str_Clean.endswith('_'): str_Clean = str_Clean[:-1] return str_Clean except Exception, err: cgmGeneral.cgmException(Exception, err)
def ribbon_seal( driven1=None, driven2=None, influences1=None, influences2=None, msgDriver=None, #...msgLink on joint to a driver group for constaint purposes extendEnds=False, loftAxis='z', orientation='zyx', secondaryAxis='y+', baseName=None, baseName1=None, baseName2=None, connectBy='constraint', sectionSpans=1, settingsControl=None, specialMode=None, sealSplit=False, sealDriver1=None, sealDriver2=None, sealDriverMid=None, sealName1='left', sealName2='right', sealNameMid='center', maxValue=10.0, moduleInstance=None, parentGutsTo=None): try: _str_func = 'ribbon_seal' ml_rigObjectsToConnect = [] md_drivers = {} md_base = {} md_seal = {} md_blend = {} md_follicles = {} md_follicleShapes = {} d_dat = {1: {}, 2: {}} if msgDriver: ml_missingDrivers = [] def check_msgDriver(mObj): mDriver = mObj.getMessageAsMeta(msgDriver) if mDriver: md_drivers[mObj] = mDriver else: log.error("|{0}| >> Missing driver: {1}".format( _str_func, mObj)) ml_missingDrivers.append(mObj) return False #>>> Verify =================================================================================== log.debug("|{0}| >> driven1 [Check]...".format(_str_func)) d_dat[1]['driven'] = cgmMeta.validateObjListArg(driven1, mType='cgmObject', mayaType=['joint'], noneValid=False) log.debug("|{0}| >> driven2 [Check]...".format(_str_func)) d_dat[2]['driven'] = cgmMeta.validateObjListArg(driven2, mType='cgmObject', mayaType=['joint'], noneValid=False) #Check our msgDrivers ----------------------------------------------------------- if msgDriver: log.debug("|{0}| >> msgDriver [Check]...".format(_str_func)) for mObj in d_dat[1]['driven'] + d_dat[2]['driven']: if mObj not in ml_missingDrivers: check_msgDriver(mObj) if ml_missingDrivers: raise ValueError, "Missing drivers. See errors." log.debug("|{0}| >> msgDriver [Pass]...".format(_str_func)) d_dat[1]['int_driven'] = len(d_dat[1]['driven']) d_dat[2]['int_driven'] = len(d_dat[2]['driven']) log.debug("|{0}| >> Driven lengths {1} | {2}".format( _str_func, d_dat[1]['int_driven'], d_dat[2]['int_driven'])) log.debug("|{0}| >> influences1 [Check]...".format(_str_func)) d_dat[1]['mInfluences'] = cgmMeta.validateObjListArg( influences1, mType='cgmObject', mayaType=['joint'], noneValid=False) log.debug("|{0}| >> influences2 [Check]...".format(_str_func)) d_dat[2]['mInfluences'] = cgmMeta.validateObjListArg( influences2, mType='cgmObject', mayaType=['joint'], noneValid=False) d_dat[1]['int_influences'] = len(d_dat[1]['mInfluences']) d_dat[2]['int_influences'] = len(d_dat[2]['mInfluences']) log.debug("|{0}| >> Influence lengths {1} | {2}".format( _str_func, d_dat[1]['int_influences'], d_dat[2]['mInfluences'])) mi_mayaOrientation = VALID.simpleOrientation(orientation) str_orientation = mi_mayaOrientation.p_string str_secondaryAxis = VALID.stringArg(secondaryAxis, noneValid=True) if specialMode and specialMode not in [ 'noStartEnd', 'endsToInfluences' ]: raise ValueError, "Unknown special mode: {0}".format(specialMode) #module ----------------------------------------------------------------------------------------------- mModule = cgmMeta.validateObjArg(moduleInstance, noneValid=True) #try:mModule.isModule() #except:mModule = False mi_rigNull = False if mModule: log.debug("|{0}| >> mModule [Check]...".format(_str_func)) mi_rigNull = mModule.rigNull if str_baseName is None: str_baseName = mModule.getPartNameBase() #Get part base name if not baseName: baseName = 'testRibbonSeal' if not baseName1: baseName1 = 'ribbon1' if not baseName2: baseName2 = 'ribbon2' d_check = { 'driven1': d_dat[1]['int_driven'], 'driven2': d_dat[2]['int_driven'] } for k, i in d_check.iteritems(): if i < 3: raise ValueError, "needs at least three driven. Found : {0} | {1}".format( k, i) log.debug("|{0}| >> Group [Check]...".format(_str_func)) if parentGutsTo is None: mGroup = cgmMeta.cgmObject(name='newgroup') mGroup.addAttr('cgmName', str(baseName), lock=True) mGroup.addAttr('cgmTypeModifier', 'segmentStuff', lock=True) mGroup.doName() else: mGroup = cgmMeta.validateObjArg(parentGutsTo, 'cgmObject', False) if mModule: mGroup.parent = mModule.rigNull #Good way to verify an instance list? #validate orientation #> axis ------------------------------------------------------------- """ axis_aim = VALID.simpleAxis("{0}+".format(str_orientation[0])) axis_aimNeg = axis_aim.inverse axis_up = VALID.simpleAxis("{0}+".format(str_orientation [1])) axis_out = VALID.simpleAxis("{0}+".format(str_orientation [2])) v_aim = axis_aim.p_vector#aimVector v_aimNeg = axis_aimNeg.p_vector#aimVectorNegative v_up = axis_up.p_vector #upVector v_out = axis_out.p_vector str_up = axis_up.p_string loftAxis2 = False #Figure out our loft axis stuff if loftAxis not in orientation: _lower_loftAxis = loftAxis.lower() if _lower_loftAxis in ['out','up']: if _lower_loftAxis == 'out': loftAxis = str_orientation[2] else: loftAxis = str_orientation[1] else: raise ValueError,"Not sure what to do with loftAxis: {0}".format(loftAxis) """ outChannel = str_orientation[2] #outChannel upChannel = str_orientation[1] #upChannel = '{0}up'.format(str_orientation[1])#upChannel #>>> Ribbon Surface ============================================================================ log.debug("|{0}| >> Ribbons generating...".format(_str_func)) l_surfaceReturn1 = IK.ribbon_createSurface(d_dat[1]['driven'], loftAxis, sectionSpans, extendEnds) d_dat[1]['mSurf'] = cgmMeta.validateObjArg(l_surfaceReturn1[0], 'cgmObject', setClass=True) d_dat[1]['mSurf'].addAttr('cgmName', str(baseName1), attrType='string', lock=True) d_dat[1]['mSurf'].addAttr('cgmType', 'controlSurface', attrType='string', lock=True) d_dat[1]['mSurf'].doName() l_surfaceReturn2 = IK.ribbon_createSurface(d_dat[2]['driven'], loftAxis, sectionSpans, extendEnds) d_dat[2]['mSurf'] = cgmMeta.validateObjArg(l_surfaceReturn1[0], 'cgmObject', setClass=True) d_dat[2]['mSurf'].addAttr('cgmName', str(baseName2), attrType='string', lock=True) d_dat[2]['mSurf'].addAttr('cgmType', 'controlSurface', attrType='string', lock=True) d_dat[2]['mSurf'].doName() log.debug("d_dat[1]['mSurf']: {0}".format(d_dat[1]['mSurf'])) log.debug("d_dat[2]['mSurf']: {0}".format(d_dat[2]['mSurf'])) ml_toConnect = [] ml_toConnect.extend([d_dat[1]['mSurf'], d_dat[2]['mSurf']]) #Special Mode ================================================================================= if specialMode in ['noStartEnd', 'endsToInfluences']: log.debug( "|{0}| >> Special Mode: {1}".format(_str_func, specialMode) + cgmGEN._str_subLine) if specialMode == 'endsToInfluences': d_special = { '1start': { 'mObj': d_dat[1]['driven'][0], 'mDriver': d_dat[1]['mInfluences'][0] }, '1end': { 'mObj': d_dat[1]['driven'][-1], 'mDriver': d_dat[1]['mInfluences'][-1] }, '2start': { 'mObj': d_dat[2]['driven'][0], 'mDriver': d_dat[2]['mInfluences'][0] }, '2end': { 'mObj': d_dat[2]['driven'][-1], 'mDriver': d_dat[2]['mInfluences'][-1] } } for n, dat in d_special.iteritems(): mObj = dat['mObj'] mDriven = md_drivers[mObj] mDriver = dat['mDriver'] log.debug("|{0}| >> {1} | Driver: {2}".format( _str_func, i, mDriven)) _const = mc.parentConstraint([mDriver.mNode], mDriven.mNode, maintainOffset=True)[0] ATTR.set(_const, 'interpType', 2) d_dat[1]['driven'] = d_dat[1]['driven'][1:-1] d_dat[2]['driven'] = d_dat[2]['driven'][1:-1] driven1 = driven1[1:-1] driven2 = driven2[1:-1] #>>> Setup our Attributes ================================================================ log.debug("|{0}| >> Settings...".format(_str_func)) if settingsControl: mSettings = cgmMeta.validateObjArg(settingsControl, 'cgmObject') else: mSettings = d_dat[1]['mSurf'] mPlug_sealHeight = cgmMeta.cgmAttr(mSettings.mNode, 'sealHeight', attrType='float', lock=False, keyable=True) mPlug_sealHeight.doDefault(.5) mPlug_sealHeight.value = .5 #>>> Setup blend results -------------------------------------------------------------------- if sealSplit: d_split = split_blends( driven1, #d_dat[1]['driven'], driven2, #d_dat[2]['driven'], sealDriver1, sealDriver2, sealDriverMid, nameSeal1=sealName1, nameSeal2=sealName2, nameSealMid=sealNameMid, settingsControl=mSettings, maxValue=maxValue) for k, d in d_split.iteritems(): d_dat[k]['mPlugs'] = d['mPlugs'] else: mPlug_seal = cgmMeta.cgmAttr(mSettings.mNode, 'seal', attrType='float', lock=False, keyable=True) mPlug_sealOn = cgmMeta.cgmAttr(mSettings, 'result_sealOn', attrType='float', defaultValue=0, keyable=False, lock=True, hidden=False) mPlug_sealOff = cgmMeta.cgmAttr(mSettings, 'result_sealOff', attrType='float', defaultValue=0, keyable=False, lock=True, hidden=False) NODEFACTORY.createSingleBlendNetwork(mPlug_seal.p_combinedName, mPlug_sealOn.p_combinedName, mPlug_sealOff.p_combinedName) d_dat[1]['mPlug_sealOn'] = mPlug_sealOn d_dat[1]['mPlug_sealOff'] = mPlug_sealOff d_dat[2]['mPlug_sealOn'] = mPlug_sealOn d_dat[2]['mPlug_sealOff'] = mPlug_sealOff mPlug_FavorOneMe = cgmMeta.cgmAttr(mSettings, 'result_sealOneMe', attrType='float', defaultValue=0, keyable=False, lock=True, hidden=False) mPlug_FavorOneThee = cgmMeta.cgmAttr(mSettings, 'result_sealOneThee', attrType='float', defaultValue=0, keyable=False, lock=True, hidden=False) mPlug_FavorTwoMe = cgmMeta.cgmAttr(mSettings, 'result_sealTwoMe', attrType='float', defaultValue=0, keyable=False, lock=True, hidden=False) mPlug_FavorTwoThee = cgmMeta.cgmAttr(mSettings, 'result_sealTwoThee', attrType='float', defaultValue=0, keyable=False, lock=True, hidden=False) NODEFACTORY.createSingleBlendNetwork(mPlug_sealHeight.p_combinedName, mPlug_FavorOneThee.p_combinedName, mPlug_FavorOneMe.p_combinedName) NODEFACTORY.createSingleBlendNetwork(mPlug_sealHeight.p_combinedName, mPlug_FavorTwoThee.p_combinedName, mPlug_FavorTwoMe.p_combinedName) d_dat[1]['mPlug_me'] = mPlug_FavorOneMe d_dat[1]['mPlug_thee'] = mPlug_FavorOneThee d_dat[2]['mPlug_me'] = mPlug_FavorTwoMe d_dat[2]['mPlug_thee'] = mPlug_FavorTwoThee """ b_attachToInfluences = False if attachEndsToInfluences: log.debug("|{0}| >> attachEndsToInfluences flag. Checking...".format(_str_func)) if influences and len(influences) > 1: b_attachToInfluences = True log.debug("|{0}| >> b_attachToInfluences: {1}".format(_str_func,b_attachToInfluences)) """ #>>> Skinning ============================================================================ log.debug("|{0}| >> Skinning Ribbons...".format(_str_func)) for idx, dat in d_dat.iteritems(): max_influences = 2 mode_tighten = 'twoBlend' blendLength = int(dat['int_driven'] / 2) blendMin = 2 _hardLength = 2 if extendEnds: blendMin = 4 _hardLength = 4 mode_tighten = None if dat['int_influences'] > 2: mode_tighten = None #blendLength = int(int_lenInfluences/2) max_influences = MATH.Clamp(blendLength, 2, 4) blendLength = MATH.Clamp(int(dat['int_influences'] / 2), 2, 6) if dat['int_influences'] == dat['int_driven']: _hardLength = 3 #Tighten the weights... mSkinCluster = cgmMeta.validateObjArg(mc.skinCluster( [mObj.mNode for mObj in dat['mInfluences']], dat['mSurf'].mNode, tsb=True, maximumInfluences=max_influences, normalizeWeights=1, dropoffRate=5.0), 'cgmNode', setClass=True) mSkinCluster.doStore('cgmName', dat['mSurf']) mSkinCluster.doName() #Tighten the weights... RIGSKIN.surface_tightenEnds(dat['mSurf'].mNode, hardLength=_hardLength, blendLength=blendLength, mode=mode_tighten) #>>> Meat ============================================================================ ml_processed = [] for idx, dat in d_dat.iteritems(): idx_seal = 1 if idx == 1: idx_seal = 2 dat_seal = d_dat[idx_seal] log.debug("|{0}| >> Building [{1}] | seal idx: {2} |".format( _str_func, idx, idx_seal) + cgmGEN._str_subLine) mSurfBase = dat['mSurf'] mSurfSeal = dat_seal['mSurf'] for i, mObj in enumerate(dat['driven']): if mObj in ml_processed: log.debug("|{0}| >> Already completed: {1}".format( _str_func, mObj)) continue ml_processed.append(mObj) log.debug("|{0}| >> {1} | Driven: {2}".format( _str_func, i, mObj)) mDriven = md_drivers[mObj] log.debug("|{0}| >> {1} | Driver: {2}".format( _str_func, i, mDriven)) log.debug("|{0}| >> Create track drivers...".format(_str_func)) mTrackBase = mDriven.doCreateAt(setClass=True) mTrackBase.doStore('cgmName', mObj) mTrackSeal = mTrackBase.doDuplicate() mTrackBlend = mTrackBase.doDuplicate() mTrackSeal.doStore('cgmType', 'trackSeal') mTrackBase.doStore('cgmType', 'trackBase') mTrackBlend.doStore('cgmType', 'trackBlend') for mTrack in mTrackBase, mTrackSeal, mTrackBlend: mTrack.doName() log.debug("|{0}| >> Attach drivers...".format(_str_func)) d_tmp = { 'base': { 'mSurf': mSurfBase, 'mTrack': mTrackBase }, 'seal': { 'mSurf': mSurfSeal, 'mTrack': mTrackSeal }, } for n, d in d_tmp.iteritems(): mTrack = d['mTrack'] mSurf = d['mSurf'] _res = RIGCONSTRAINTS.attach_toShape( mTrack.mNode, mSurf.mNode, 'parent') mFollicle = _res[-1][ 'mFollicle'] #cgmMeta.asMeta(follicle) mFollShape = _res[-1][ 'mFollicleShape'] #cgmMeta.asMeta(shape) md_follicleShapes[mObj] = mFollShape md_follicles[mObj] = mFollicle mFollicle.parent = mGroup.mNode if mModule: #if we have a module, connect vis mFollicle.overrideEnabled = 1 cgmMeta.cgmAttr( mModule.rigNull.mNode, 'gutsVis', lock=False).doConnectOut( "%s.%s" % (mFollicle.mNode, 'overrideVisibility')) cgmMeta.cgmAttr( mModule.rigNull.mNode, 'gutsLock', lock=False).doConnectOut( "%s.%s" % (mFollicle.mNode, 'overrideDisplayType')) #Blend point -------------------------------------------------------------------- _const = mc.parentConstraint( [mTrackBase.mNode, mTrackSeal.mNode], mTrackBlend.mNode)[0] ATTR.set(_const, 'interpType', 2) targetWeights = mc.parentConstraint(_const, q=True, weightAliasList=True) #Connect if idx == 1: dat['mPlug_thee'].doConnectOut('%s.%s' % (_const, targetWeights[0])) dat['mPlug_me'].doConnectOut('%s.%s' % (_const, targetWeights[1])) else: dat['mPlug_me'].doConnectOut('%s.%s' % (_const, targetWeights[0])) dat['mPlug_thee'].doConnectOut('%s.%s' % (_const, targetWeights[1])) #seal -------------------------------------------------------------------- _const = mc.parentConstraint( [mTrackBase.mNode, mTrackBlend.mNode], mDriven.mNode)[0] ATTR.set(_const, 'interpType', 2) targetWeights = mc.parentConstraint(_const, q=True, weightAliasList=True) if sealSplit: dat['mPlugs']['off'][i].doConnectOut( '%s.%s' % (_const, targetWeights[0])) dat['mPlugs']['on'][i].doConnectOut( '%s.%s' % (_const, targetWeights[1])) else: dat['mPlug_sealOff'].doConnectOut( '%s.%s' % (_const, targetWeights[0])) dat['mPlug_sealOn'].doConnectOut( '%s.%s' % (_const, targetWeights[1])) log.debug("|{0}| >> Blend drivers...".format(_str_func)) """ #Simple contrain if b_attachToInfluences and mJnt in [ml_joints[0],ml_joints[-1]]: if mJnt == ml_joints[0]: mUse = ml_influences[0] else: mUse = ml_influences[-1] mc.parentConstraint([mUse.mNode], mDriven.mNode, maintainOffset=True) else: mc.parentConstraint([mDriver.mNode], mDriven.mNode, maintainOffset=True) """ #pprint.pprint(d_dat) return except Exception, err: cgmGEN.cgmExceptCB(Exception, err, msg=vars())
def register( controlObject=None, #(mObject - None) -- The object to use as a control typeModifier=None, #(string - None) -- Tag for cgmTypeModifier for naming copyTransform=None, #(mObject - None) -- Object to copy the transform of for our control object copyPivot=None, #(mObject - None) -- Object to copy the pivot of for our control object shapeParentTo=None, #'(mObject - None) -- Object to shape parent our control curve to to use that transform useShape=None, #'(mObject - None) -- Object to use the curve shape of for our control setRotateOrder=None, #'(rotateOrder - None) -- Argument for a rotate order to set autoLockNHide=None, #'(bool - None) -- Try to set lock and hide mirrorAxis=None, #'(string - None) -- Mirror axis to set - using red9's setup terms mirrorSide=None, #'(string/int - None) -- Mirror side - using red9's setup terms makeMirrorable=True, #'(bool - True) -- Setup for mirrorability (using red9) -- implied by other mirror args addDynParentGroup=False, #'(False) -- Add a dynParent group setup addExtraGroups=False, #'(int - False) -- Number of nested extra groups desired addConstraintGroup=False, #'(bool - False) -- If a group just above the control is desired for consraining freezeAll=False, #'(bool - False) -- Freeze all transforms on the control object noFreeze=False, addSpacePivots=False, #'(int - False) -- Number of space pivots to generate and connect controlType=None, #'(string - None) -- Tag for cgmType aim=None, #'(string/int - None) -- aim axis to use up=None, #'(string/int - None) -- up axis to use out=None, #'(string/int - None) -- out axis to use makeAimable=None, #'(mObject - False) -- Make object aimable -- implied by aim/up/out): **kws): _str_func = 'register' """ [{'step':'validate','call':self._validate}, {'step':'Copy Transform','call':self._copyTransform}, {'step':'Shape Parent','call':self._shapeParent}, {'step':'Copy Pivot','call':self._copyPivot}, {'step':'Naming','call':self._naming}, {'step':'Aim Setup','call':self._aimSetup}, {'step':'Rotate Order','call':self._rotateOrder}, {'step':'Initial Freeze','call':self._initialFreeze}, {'step':'Groups Setup','call':self._groupsSetup}, {'step':'Space Pivot','call':self._spacePivots}, {'step':'Mirror Setup','call':self._mirrorSetup}, {'step':'Freeze','call':self._freeze}, {'step':'Mirror Attribute Bridges','call':self._mirrorAttributeBridges_}, {'step':'lock N Hide','call':self._lockNHide}, {'step':'Return build','call':self._returnBuild}] """ try: #Validate ================================================================================================ mi_control = cgmMeta.validateObjArg(controlObject, 'cgmControl', setClass=True) str_mirrorAxis = VALID.stringArg(mirrorAxis, calledFrom=_str_func) str_mirrorSide = cgmGeneral.verify_mirrorSideArg( mirrorSide) #VALID.stringArg(mirrorSide,calledFrom = _str_func) b_makeMirrorable = VALID.boolArg(makeMirrorable, calledFrom=_str_func) _addMirrorAttributeBridges = kws.get('addMirrorAttributeBridges', False) addForwardBack = kws.get('addForwardBack', False) if _addMirrorAttributeBridges: if type(_addMirrorAttributeBridges) not in [list, tuple]: raise ValueError, "[Bad addMirrorAttributeBridge arg]{arg: %s}" % _addMirrorAttributeBridge for i, l in enumerate(_addMirrorAttributeBridges): if type(l) not in [list, tuple]: raise ValueError, "[Bad addMirrorAttributeBridge arg: %s]{arg: %s}" % ( i, l) # Running lists ------------------------------------------------------------------------------------------ ml_groups = [] #Holder for groups ml_constraintGroups = [] ml_spacePivots = [] #Copy Transform ================================================================================================ if copyTransform is not None: mTarget = cgmMeta.validateObjArg(copyTransform, 'cgmObject', noneValid=True) if not mTarget: raise StandardError, "Failed to find suitable copyTransform object: '%s" % copyTransform #Need to move this to default cgmNode stuff mBuffer = mi_control i_newTransform = cgmMeta.cgmObject( rigging.groupMeObject(mTarget.mNode, False)) for a in mc.listAttr(mi_control.mNode, userDefined=True): ATTR.copy_to(mi_control.mNode, a, i_newTransform.mNode) curves.parentShapeInPlace(i_newTransform.mNode, mi_control.mNode) #Parent shape i_newTransform.parent = mi_control.parent #Copy parent mi_control = cgmMeta.asMeta(i_newTransform, 'cgmControl', setClass=True) mc.delete(mBuffer.mNode) #ShapeParent ================================================================================================ if shapeParentTo: i_target = cgmMeta.validateObjArg(shapeParentTo, 'cgmObject') CORERIG.shapeParent_in_place(i_target.mNode, mi_control.mNode) i_target = cgmMeta.asMeta(i_target, 'cgmControl', setClass=True) #mi_control.delete() mi_control = i_target #replace the control with the joint if useShape is not None: i_shape = cgmMeta.validateObjArg(useShape, cgmMeta.cgmObject, mayaType='nurbsCurve') curves.parentShapeInPlace(mi_control.mNode, i_shape.mNode) #Copy Pivot ============================================================================================ if copyPivot is not None: if issubclass(type(copyPivot), cgmMeta.cgmNode): i_target = copyPivot elif mc.objExists(copyPivot): i_target = cgmMeta.cgmObject(copyPivot) else: raise StandardError, "Failed to find suitable copyTransform object: '%s" % copyPivot #Need to move this to default cgmNode stuff mi_control.doCopyPivot(i_target.mNode) #Naming ============================================================================================ mi_control.addAttr('cgmType', 'controlAnim', lock=True) if typeModifier is not None: mi_control.addAttr('cgmTypeModifier', str(typeModifier), lock=True) mi_control.doName() #mi_control.doName(nameShapes=True) #Rotate Order ============================================================================================ _rotateOrder = False if setRotateOrder is not None: _rotateOrder = setRotateOrder elif controlType in __d_rotateOrderDefaults__.keys(): _rotateOrder = __d_rotateOrderDefaults__[controlType] elif mi_control.getAttr('cgmName') in __d_rotateOrderDefaults__.keys(): _rotateOrder = __d_rotateOrderDefaults__[mi_control.getAttr( 'cgmName')] else: log.debug("|{0}| >> Rotate order not set on: {1}".format( _str_func, mi_control.p_nameShort)) #Set it --------------------------------------------------------------- if _rotateOrder: mRotateOrder = VALID.simpleOrientation(_rotateOrder) #dictionary.validateRotateOrderString(_rotateOrder) mc.xform(mi_control.mNode, rotateOrder=mRotateOrder.p_string) #Initial Freeze ============================================================================================ if freezeAll: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=1, s=1, n=0) #Groups ============================================================================================ if addDynParentGroup or addSpacePivots or mi_control.getAttr( 'cgmName') == 'cog' or _addMirrorAttributeBridges: mi_control.addAttr('________________', attrType='int', keyable=False, hidden=False, lock=True) ATTR.reorder(mi_control.mNode, '________________', top=True) #Aim Setup ============================================================================================ if aim is not None or up is not None or makeAimable: mi_control._verifyAimable() #First our master group: i_masterGroup = (cgmMeta.asMeta(mi_control.doGroup(True), 'cgmObject', setClass=True)) i_masterGroup.doStore('cgmName', mi_control) i_masterGroup.addAttr('cgmTypeModifier', 'master', lock=True) i_masterGroup.doName() mi_control.connectChildNode(i_masterGroup, 'masterGroup', 'groupChild') if addDynParentGroup: i_dynGroup = (cgmMeta.cgmObject(mi_control.doGroup(True))) i_dynGroup = cgmRigMeta.cgmDynParentGroup(dynChild=mi_control, dynGroup=i_dynGroup) i_dynGroup.doName() """ i_zeroGroup = (cgmMeta.cgmObject(mi_control.doGroup(True))) i_zeroGroup.addAttr('cgmTypeModifier','zero',lock=True) i_zeroGroup.doName() mi_control.connectChildNode(i_zeroGroup,'zeroGroup','groupChild')""" if addExtraGroups: for i in range(addExtraGroups): i_group = (cgmMeta.asMeta(mi_control.doGroup(True), 'cgmObject', setClass=True)) if type( addExtraGroups ) == int and addExtraGroups > 1: #Add iterator if necessary i_group.addAttr('cgmIterator', str(i + 1), lock=True) i_group.doName() ml_groups.append(i_group) mi_control.msgList_connect("extraGroups", ml_groups, 'groupChild') if addConstraintGroup: #ConstraintGroups i_constraintGroup = (cgmMeta.asMeta(mi_control.doGroup(True), 'cgmObject', setClass=True)) i_constraintGroup.addAttr('cgmTypeModifier', 'constraint', lock=True) i_constraintGroup.doName() ml_constraintGroups.append(i_constraintGroup) mi_control.connectChildNode(i_constraintGroup, 'constraintGroup', 'groupChild') #Space Pivot ============================================================================================ if addSpacePivots: parent = mi_control.getMessage('masterGroup')[0] for i in range(int(addSpacePivots)): #i_pivot = rUtils.create_spaceLocatorForObject(mi_control.mNode,parent) i_pivot = SPACEPIVOTS.create(mi_control.mNode, parent) ml_spacePivots.append(i_pivot) #log.info("spacePivot created: {0}".format(i_pivot.p_nameShort)) #Mirror Setup ============================================================================================ if str_mirrorSide is not None or b_makeMirrorable: for mObj in [mi_control] + ml_spacePivots: mi_control._verifyMirrorable() l_enum = cgmMeta.cgmAttr(mi_control, 'mirrorSide').p_enum if str_mirrorSide in l_enum: #log.debug("|{0}| >> Rotate order not set on: {1}".format(_str_func,mi_control.p_nameShort)) #log.debug("%s >> %s >> found in : %s"%(_str_funcCombined, "mirrorSetup", l_enum)) mi_control.mirrorSide = l_enum.index(str_mirrorSide) if str_mirrorAxis: mi_control.mirrorAxis = str_mirrorAxis for mObj in mi_control.msgList_get('spacePivots'): mObj._verifyMirrorable() mi_control.doConnectOut('mirrorAxis', mObj.mNode + '.mirrorAxis') mi_control.doConnectOut('mirrorSide', mObj.mNode + '.mirrorSide') #cgmMeta.cgmAttr(mObj,'mirrorSide').doConnectIn(mi_control,'mirrorSide') #cgmMeta.cgmAttr(mi_control,'mirrorAxis').doCopyTo(mObj,connectTargetToSource = 1) #ATTR.connect(mObj.mNode + '.mirrorAxis',"{0}.mirrorAxis".format(mi_control.mNode)) #ATTR.connect(mObj.mNode + 'mirrorSide',"{0}.mirrorSide".format(mi_control.mNode)) #Freeze ============================================================================================ if not shapeParentTo and noFreeze is not True: if not freezeAll: if mi_control.getAttr( 'cgmName' ) == 'cog' or controlType in __l_fullFreezeTypes__: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=1, s=1, n=0) else: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=0, s=1, n=0) else: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=1, s=1, n=0) #Mirror attriubte Bridges ========================================================================== if addForwardBack: mPlug_forwardBackDriver = cgmMeta.cgmAttr(mi_control, "forwardBack", attrType='float', keyable=True) try: mPlug_forwardBackDriven = cgmMeta.validateAttrArg( [mi_control, addForwardBack])['mi_plug'] except Exception, error: raise StandardError, "push pull driver | %s" % (error) if str_mirrorSide.lower() == 'right': arg_forwardBack = "%s = -%s" % ( mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) else: arg_forwardBack = "%s = %s" % ( mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) mPlug_forwardBackDriven.p_locked = True mPlug_forwardBackDriven.p_hidden = True mPlug_forwardBackDriven.p_keyable = False NodeF.argsToNodes(arg_forwardBack).doBuild() if _addMirrorAttributeBridges: for l_bridge in _addMirrorAttributeBridges: _attrName = VALID.stringArg(l_bridge[0]) _attrToBridge = VALID.stringArg(l_bridge[1]) if not mi_control.hasAttr(_attrToBridge): raise StandardError, "['%s' lacks the bridge attr '%s']" % ( mi_control.p_nameShort, _attrToBridge) mPlug_attrBridgeDriver = cgmMeta.cgmAttr(mi_control, _attrName, attrType='float', keyable=True) try: mPlug_attrBridgeDriven = cgmMeta.validateAttrArg( [mi_control, _attrToBridge])['mi_plug'] except Exception, error: raise StandardError, "[validate control attribute bridge attr]{%s}" % ( error) if str_mirrorSide.lower() == 'right': arg_attributeBridge = "%s = -%s" % ( mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) else: arg_attributeBridge = "%s = %s" % ( mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) mPlug_attrBridgeDriven.p_locked = True mPlug_attrBridgeDriven.p_hidden = True mPlug_attrBridgeDriven.p_keyable = False NodeF.argsToNodes(arg_attributeBridge).doBuild()
arg_forwardBack = "%s = -%s" % ( mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) else: arg_forwardBack = "%s = %s" % ( mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) mPlug_forwardBackDriven.p_locked = True mPlug_forwardBackDriven.p_hidden = True mPlug_forwardBackDriven.p_keyable = False NodeF.argsToNodes(arg_forwardBack).doBuild() if self._addMirrorAttributeBridges: for l_bridge in self._addMirrorAttributeBridges: _attrName = VALID.stringArg(l_bridge[0]) _attrToBridge = VALID.stringArg(l_bridge[1]) if not self.mi_control.hasAttr(_attrToBridge): raise StandardError, "['%s' lacks the bridge attr '%s']" % ( self.mi_control.p_nameShort, _attrToBridge) mPlug_attrBridgeDriver = cgmMeta.cgmAttr(self.mi_control, _attrName, attrType='float', keyable=True) try: mPlug_attrBridgeDriven = cgmMeta.validateAttrArg( [self.mi_control, _attrToBridge])['mi_plug'] except Exception, error: raise StandardError, "[validate control attribute bridge attr]{%s}" % ( error)