def _buildSpeedExpression(boatWorldCtrl = ''): """ Builds the base expression for the boats world_ctrl speed attr @param boatWorldCtrl: The name of the boat world_ctrl to build the expression for @type boatWorldCtrl: String """ expStringList = [ 'float $time;\n', 'float $translation[] = `xform -q -ws -translation "%s"`;\n' % boatWorldCtrl, 'float $trx;\n', 'float $try;\n', 'float $trz;\n', 'float $dx = $translation[0] - $trx;\n', 'float $dy = $translation[1] - $try;\n', 'float $dz = $translation[2] - $trz;\n', 'float $d = sqrt( ($dx * $dx) + ($dy * $dy) + ($dz * $dz) );\n', '%s.speed = abs( $d / ( time - ($time + 0.001) ) );\n' % boatWorldCtrl, '$trx = $translation[0];\n', '$try = $translation[1];\n', '$trz = $translation[2];\n', '$time = time;\n' ] ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists( '%s_speed' % boatWorldCtrl) ## Build new expression try: cmds.expression(n = '%s_speed' % boatWorldCtrl.replace(':', '_'), string = utils.processExpressionString(expStringList)) except: cmds.warning('YOU ARE USING OLD RIGS!!! PLEASE UPDATE YOUR RIGS!!!')
def __setExpression(self, footCtl, insideRollGrp, outsideRollGrp, forward_roll, backward_roll): expression = """ if (footCtl.side < 0.0) insideRollGrp.rotateZ = footCtl.side; else insideRollGrp.rotateZ = 0.0; if (footCtl.side > 0.0) outsideRollGrp.rotateZ = footCtl.side; else outsideRollGrp.rotateZ = 0.0; if (footCtl.roll < 0.0) backward_roll.rotateX = footCtl.roll; else backward_roll.rotateX = 0.0; if (footCtl.roll > 0.0) forward_roll.rotateX = footCtl.roll; else forward_roll.rotateX = 0.0; forward_roll.rotateY = footCtl.rotY; """.replace('footCtl', footCtl).\ replace('insideRollGrp', insideRollGrp).\ replace('outsideRollGrp', outsideRollGrp).\ replace('forward_roll', forward_roll).\ replace('backward_roll', backward_roll) mc.expression(s=expression, object=footCtl, alwaysEvaluate=1, unitConversion='all')
def generate(self): self.m_fingers = [] names = ["indexFing", "middleFing", "ringFing", "pinkyFing", "thumb"] for i in range(len(names)): thumb = False if i == (len(names) - 1): thumb = True newFinger = fing.FingerRig( "%s_%s" %(self.m_name, names[i]), self.m_handJoints.getFinger(i), thumb ) newFinger.generate() cmds.parent(newFinger.getGroup(), self.m_group) self.m_fingers.append(newFinger) #create control self.m_control = cmds.spaceLocator(n="%s_CTRL" %(self.m_name))[0] rc.orientControl(self.m_control, self.m_fingers[3].getKnuckle()) group = rg.addGroup(self.m_control, "%s_0" %(self.m_control)) rc.lockAttrs(self.m_control, ["tx", "rotate", "scale"], True, False) cmds.parent(group, self.m_group) cmds.expression(n="%s_EXP" %(self.m_name), s=self.createExp())
def _buildNURBSPlaneExpression(NURBSPlane, xRes, zRes, oceanShader): """ Function to setup the expression that hooks the nurbsPlane to the ocean @param NURBSPlane: The build of the nurbsPlane, this build command should have returned a list. Due to refactoring we're just handling this list instead of accepting the actual name @type NURBSPlane: List """ ## Now build the expression to connect the cv's of the NURBSPlane to the ocean xSize = xRes+1 zSize = zRes+1 expStringList = ['float $u, $v;\n float $minx = %s.scaleX * -0.5 + %s.translateX;\n' % (NURBSPlane[0], NURBSPlane[0]), 'float $maxx = %s.scaleX * 0.5 + %s.translateX;\n' % (NURBSPlane[0], NURBSPlane[0]), 'float $minz = %s.scaleZ * -0.5 + %s.translateZ;\n' % (NURBSPlane[0], NURBSPlane[0]), 'float $maxz = %s.scaleZ * 0.5 + %s.translateZ;\n' % (NURBSPlane[0], NURBSPlane[0]), 'float $disp[] = `colorAtPoint -o A -su %s -sv %s -mu $minx -mv $minz -xu $maxx -xv $maxz %s`;\n' % (str(xSize), str(zSize), oceanShader) ] expString = utils.processExpressionString(expStringList) #unfold loop and use output connections i=0 for x in range(xSize): planeX = x * zSize for z in range(zSize): planeZ= zSize - z - 1 addTo = "%s.cv[%s].yv = $disp[%s];\n" % (NURBSPlane[0], str(planeX +planeZ), str(i)) expString += addTo #increment by 1 i=i+1 ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists( '%s_IntersectionPlane' % NURBSPlane[0]) ## Build new expression cmds.expression(n = '%s_IntersectionPlane' % '_'.join(NURBSPlane[0].split(':')), string = expString)
def eyeRig(scaler): #try 4 target = mc.ls(sl=1) mc.delete(e=True) for i in range(0,len(target)): if(i<len(target)-1): mc.expression(s=target[i]+".rotateX = " + target[len(target)-1] + ".translateY * -1 * " + str(scaler)) mc.expression(s=target[i]+".rotateY = " + target[len(target)-1] + ".translateX * " + str(scaler))
def rotationExpression(): """This function adds an expression that allows the tread to rotate while moving""" cmds.select(data.mainController) cmds.addAttr(data.mainController, longName="treadSpeed", attributeType="double", defaultValue=20, keyable=True) cmds.expression(name="TreadRotation", string="{0}.rotateX = -{1}.translateZ*{1}.treadSpeed".format(data.treadBaseWire, data.mainController))
def turntable(): """ Main function. Creates turntable. Requires a list of selected objects. :return: None """ objs = cmds.ls(selection=True) meshes = checkSelection(objs) if not meshes: cmds.error('Please select a mesh object') pivlist = getSelectionPivot(meshes) turnCam = createCamera() centroid = findCentroid(pivlist) # change camera pivot to centroid cmds.xform(turnCam[0], ws=True, piv=centroid) # animate camera. rotate around y axis. firstFrame = str(cmds.playbackOptions(q=True, minTime=True)) lastFrame = str(cmds.playbackOptions(q=True, maxTime=True)) cmds.expression(name='TurnTableExpression', string='{0}.rotateY=360*(frame-{1})/{2}-{1};'.format(turnCam[0], firstFrame, lastFrame)) # create a 3 point light rig. keyLight = createLight('areaLight', 'key', centroid) fillLight = createLight('areaLight', 'fill', centroid) rimLight = createLight('areaLight', 'rim', centroid) cmds.lookThru(turnCam[0])
def createSSLocator(tag, camera): #check if camera exists if not cmds.objExists(camera): raise RuntimeError('Camera doesn\'t exists in the scene') # create locator locator_name = tag + '_2D_loc1' loc = cmds.spaceLocator(name=locator_name)[0] loc_shape = cmds.listRelatives(loc, s=True)[0] cmds.setAttr(loc_shape + '.localScaleX', 0.1) cmds.setAttr(loc_shape + '.localScaleY', 0.1) cmds.setAttr(loc_shape + '.localScaleZ', 0.1) # add attributes cmds.addAttr(loc, ln='cam_x_value', at='double', dv=0, k=True) cmds.addAttr(loc, ln='cam_y_value', at='double', dv=0, k=True) #matrix_nodes mmn = cmds.createNode('multMatrix', name=tag + '_2D_mmn1') cmds.connectAttr(loc + '.worldMatrix[0]', mmn + '.matrixIn[0]') cmds.connectAttr(camera + '.worldInverseMatrix[0]', mmn + '.matrixIn[1]') dmn = cmds.createNode('decomposeMatrix', name=tag + '_2D_dmn1') cmds.connectAttr(mmn + '.matrixSum', dmn + '.inputMatrix') #add script to locator cmds.expression(name=tag + '_2D_exp1', o=loc, s='float $hfv = `camera -q -hfv ' + camera + '`;\n' + 'float $vfv = `camera -q -vfv ' + camera + '`;\n' + 'cam_x_value = (((' + dmn + '.otx/(-' + dmn + '.otz))/tand($hfv/2))/2.0+.5)*1920;\n' + 'float $y_value = (((' + dmn + '.oty/(-' + dmn + '.otz))/tand($vfv/2))/2.0+.5);\n' + 'cam_y_value = (-($y_value*1440)+1440)-180;') return loc
def makeWingExp(): #Defining Variables axis = cmds.radioButtonGrp('whichAx', q=True, select=True) neg = cmds.radioButtonGrp('neg', q=True, select=True) speed = cmds.floatSliderGrp('speed', q=True, v=True) arc = cmds.floatSliderGrp('arc', q=True, v=True) if (axis == 1): chosenAxis = "rotateX" elif (axis == 2): chosenAxis = "rotateY" elif (axis == 3): chosenAxis = "rotateZ" if (neg == 1): negated = 1 elif (neg == 2): negated = -1 #Defining Selection selection = cmds.ls(sl=True) #Creating Expression expContent = (selection[0] + "." + str(chosenAxis) + " = ( " + str(negated) + "* sin (time * " + str(speed) + ") * " + str(arc) + ");") cmds.expression(string=expContent)
def customizeCamera(self, camera): cmds.lookThru(camera) cmds.addAttr( camera, ln="Overlay", at="enum", en= "No Overlay:Grid:SpiralTopRight:SpiralTopLeft:SpiralBottomRight:SpiralBottomLeft" ) cmds.addAttr(camera, ln="Overlay_Value", at="long") cmds.setAttr(camera + '.Overlay', e=True, keyable=True) cmds.setAttr(camera + '.Overlay_Value', e=True, keyable=True) cmds.expression( s='int $a=%s.Overlay;\r\n' % camera + '%s.Overlay_Value=$a;' % camera + 'switch($a) { \r\n' + ' case 0: \r\n' + ' python("camera_overlays.Overlay_Function().noOverlay()"); \r\n' + ' break;\r\n' + ' case 1: \r\n' + ' python("camera_overlays.Overlay_Function().toggleThirdsGrid()"); \r\n' + ' break;\r\n' + ' case 2: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialTopRight()"); \r\n' + ' break;\r\n' + ' case 3: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialTopLeft()"); \r\n' + ' break;\r\n' + ' case 4: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialBottomRight()"); \r\n' + ' break;\r\n' + ' case 5: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialBottomLeft()"); \r\n' + '}select %s;\r' % camera, ae=False, o="renderCam")
def stabilizer (): global _camera_ _point = cmds.ls (selection = True) if cmds.objExists ('stabilizator_expression') == False and len(_point) > 0: _camera_ = Camera() _point = _point[0] if (cmds.nodeType (_point) == 'mesh' or cmds.nodeType (_point) == 'transform') and _camera_.transform != 'empty': _expression = r''' $pos=`python "fmmu.get_normalized_screen_position(\"''' + _point + r'''\")"`; setAttr "''' + _camera_.shape + r'''.horizontalFilmOffset" $pos[2]; setAttr "''' + _camera_.shape + r'''.verticalFilmOffset" $pos[3];''' print "==================================" print _expression cmds.expression (name = 'stabilizator_expression', string = _expression) cmds.frameLayout ('adjustCam_frml', edit = True, visible = True) cmds.symbolButton ('button_stabilizer', edit = True, image = 'ford_matchMoveUtilities__deStabilize.xpm', annotation = 'deStabilizer') cmds.floatField ('field_overscan', edit = True, value = _camera_.overscan) else: if cmds.objExists ('stabilizator_expression') == True: cmds.delete ('stabilizator_expression') cmds.symbolButton ('button_stabilizer', edit = True, image = 'ford_matchMoveUtilities__stabilize.xpm', annotation = 'deStabilizer') cmds.frameLayout ('adjustCam_frml', edit = True, collapse = True, visible = False) try: _camera_.reset_camera() except: pass
def create(self, objnum, shape="cone"): if shape == "cone": node = cmds.cone(ch=False, n='herdmemb') else: node = cmds.duplicate(shape, ic=True, n='herdmemb') cmds.addAttr(node, sn='fad', ln='frameAdjust', dv=0, k=True) values = herds().values() cmds.expression(s=("$herdvar = " + str(random.random() - 0.5) + " * " + self.leader + ".rnds + " + str(objnum) + ";\n" + "$randfac = " + self.leader + ".stry;\n" + "$foc = " + self.leader + ".lf;\n" + "if( $foc != 0 ) {\n" + "$randfac *= min( 1.0,abs($herdvar)*(1-$foc)/($foc*"+ str(values["population"]) +") );}\n" + "$herdvar = $herdvar * -" + self.leader + ".frameOffset + frame +" + node[0] + ".frameAdjust;\n" + "$offset = " + str(random.random() - 0.45) + " * $randfac;\n" + node[0] + ".tx = $offset + `getAttr -time $herdvar " + self.leader + ".tx`;\n" + "$offset = " + str(random.random() - 0.45) + " * $randfac;\n" + node[0] + ".ty = $offset + `getAttr -time $herdvar " + self.leader + ".ty`;\n" + "$offset = " + str(random.random() - 0.45) + " * $randfac;\n" + node[0] + ".tz = $offset + `getAttr -time $herdvar " + self.leader + ".tz`;\n" ), n=(node[0] + "_herd_exp")) # Turns off the checker for finding cycles - throws up lots of warnings without it. cmds.cycleCheck(e=True, all=False) self.node = node[0] self.point() return node
def turntable(): """ Main function. Creates turntable. Requires a list of selected objects. :return: None """ objs = cmds.ls(selection=True) meshes = checkSelection(objs) if not meshes: cmds.error('Please select a mesh object') pivlist = getSelectionPivot(meshes) turnCam = createCamera() centroid = findCentroid(pivlist) # change camera pivot to centroid cmds.xform(turnCam[0], ws=True, piv=centroid) # animate camera. rotate around y axis. firstFrame = str(cmds.playbackOptions(q=True, minTime=True)) lastFrame = str(cmds.playbackOptions(q=True, maxTime=True)) cmds.expression(name='TurnTableExpression', string='{0}.rotateY=360*(frame-{1})/{2}-{1};'.format( turnCam[0], firstFrame, lastFrame)) # create a 3 point light rig. keyLight = createLight('areaLight', 'key', centroid) fillLight = createLight('areaLight', 'fill', centroid) rimLight = createLight('areaLight', 'rim', centroid) cmds.lookThru(turnCam[0])
def setupScapula(self, jointScapula, colourTU, leftRight, shoulderOffsetCtrl, *args): jntScap = jointScapula[0] childScap = mc.listRelatives(jntScap, c=True, type="joint")[0] scapLength = mc.getAttr("{0}.ty".format(childScap)) scapulaOffsetCtrl = CRU.createCTRLs(jntScap, size=6, ornt=True, colour=colourTU, orientVal=(1, 0, 0), sectionsTU=8) mc.select(scapulaOffsetCtrl[1] + ".cv[:]") mc.move(-scapLength * 0.5, scapLength * 0.5, 0, r=True, ls=True) autoAttrName = "autoScapula" mc.addAttr(scapulaOffsetCtrl, longName=autoAttrName, at="float", k=True, min=0, max=1, dv=0.5) autoName = scapulaOffsetCtrl[2] xprNameScap = "expr_" + leftRight + "scapula" # AUTO_CTRL_l_scapula.rotateX = -1*CTRL_l_shoulder.rotateZ * CTRL_l_scapula.autoScapula; exprStringScap = "{0}.rotateX = -1*{1}.rotateZ * {2}.{3};\n".format( autoName, shoulderOffsetCtrl[1], scapulaOffsetCtrl[1], autoAttrName) mc.expression(s=exprStringScap, n=xprNameScap) mc.parent(scapulaOffsetCtrl[0], shoulderOffsetCtrl[1]) return scapulaOffsetCtrl
def execute(self): if not Maya.load_plugin("redshift4maya.mll"): self.append_error("Load redshift4maya.mll failed.") return if not self.files: self.append_error("No rs files found") return file_num = len(self.files) if file_num == 1: file_name = self.files[0] else: frame_padding = self.frame_padding(self.files[0], "rs") file_name = re.sub("\d+\.rs$", "%s.rs" % ("#" * frame_padding), self.files[0]) node = Maya.import_rs(file_name) if file_num > 1: mc.setAttr("%s.useFrameExtension" % node, True) exp = mc.createNode("expression", name="expression") mc.connectAttr("%s.out[0]" % exp, "%s.frameExtension" % node, f=1) mc.expression(exp, e=1, s="{0}.frameExtension=(frame-1)%{1}+1".format( node, file_num), ae=1, uc="all")
def setupClavicle(self, jointClavicle, colourTU, leftRight, shoulderOffsetCtrl, jntArmArray, *args): jntClav = jointClavicle[0] childClavicle = mc.listRelatives(jntClav, c=True, type="joint")[0] clavLength = mc.getAttr("{0}.ty".format(childClavicle)) clavicleOffsetCtrl = CRU.createCTRLs(jntClav, size=6, ornt=True, colour=colourTU, orientVal=(0, 0, 1), sectionsTU=6) mc.select(clavicleOffsetCtrl[1] + ".cv[:]") mc.move(clavLength * 0.5, clavLength * 0.5, 0, r=True, ls=True) autoAttrName = "autoClavicle" mc.addAttr(clavicleOffsetCtrl, longName=autoAttrName, at="float", k=True, min=0, max=1, dv=0.05) autoName = clavicleOffsetCtrl[2] xprNameClav = "expr_" + leftRight + "clavicle" # AUTO_CTRL_l_clavicle.rotateX = JNT_l_upperArm.rotateX * CTRL_l_clavicle.autoClavicle; exprStringClav = self.tgpAutoClavicleRotate(autoName, jntArmArray[0], clavicleOffsetCtrl[1], autoAttrName) mc.expression(s=exprStringClav, n=xprNameClav) mc.parent(clavicleOffsetCtrl[0], shoulderOffsetCtrl[1]) return clavicleOffsetCtrl
def stabilizer (task): camera = Camera() point = cmds.ls (selection = True) if task == 'end': # turn off stab expression = str (cmds.expression ('stabilizator_expression', string = True, query = True)) camera.shape = expression[2:expression.find('#')] cmds.delete ('stabilizator_expression') camera.reset_camera () cmds.button ('button_stabilizer', edit = True, label = 'stabilize', backgroundColor = (0, 0.5, 0), command = 'fstab.stabilizer("start")') else: # start stab if cmds.objExists ('stabilizator_expression'): # stabilizator exists expression = str (cmds.expression ('stabilizator_expression', string = True, query = True)) camera.shape = expression[2:expression.find('#')] cmds.delete ('stabilizator_expression') cmds.select (camera.shape, replace = True) cmds.warning (('>>> STAB WAS TURNED ON. CHECK: ' + camera.shape + ' <<< FOR NONZERO OFFSET VALUES ::..')) else: if cmds.nodeType (point) != 'mesh' and cmds.nodeType (point) != 'transform' and len (point) == 0: # wrong selection cmds.warning ('..:: SELECT SOMETHING TO STABILIZE ::..') else: point = point[0] if point != camera.transform and point != camera.shape and camera.transform != 'empty': # stabilize cmds.setAttr( camera.shape + '.displayResolution', 0) cmds.setAttr( camera.shape + '.displayFilmGate', 0) expression = '//%s#' % camera.shape expression += '\npython "import maya.cmds as cmds";' expression += '\npython "fov_h = cmds.camera (\'%s\', query = True, horizontalFieldOfView = True)";' % camera.shape expression += '\npython "fov_v = cmds.camera (\'%s\', query = True, verticalFieldOfView = True)";' % camera.shape expression += '\npython "aperture_h = cmds.camera (\'%s\', query = True, horizontalFilmAperture = True)";' % camera.shape expression += '\npython "aperture_v = cmds.camera (\'%s\', query = True, verticalFilmAperture = True)";' % camera.shape expression += '\n$pos=`python "fstab.get_normalized_screen_position(\'%s\',\'%s\',fov_h, fov_v,aperture_h,aperture_v)"`;' % (point, camera.transform) expression += '\nsetAttr "%s.horizontalFilmOffset" ($pos[2]);' % camera.shape expression += '\nsetAttr "%s.verticalFilmOffset" ($pos[3]);' % camera.shape # create expression cmds.expression (name = 'stabilizator_expression', string = expression) # update GUI cmds.button ('button_stabilizer', edit = True, label ="deStabilize", backgroundColor = (1, 0, 0), command = 'fstab.stabilizer("end")') else: cmds.warning ('..:: CLICK IN THE PANE WITH THE CAMERA ::..')
def createSpeedAttribute(*args): '''This will create an attribute on any object which shows its speed in kmh at current frame''' sel = cmds.ls(selection=True) if len(sel) != 1: cmds.warning('One object must be selected') else: sel = sel[0] cmds.addAttr(sel, ln='speed', nn='Speed (kmh)', at='double', dv=0, h=False, k=True) cmds.expression( s="float $lastPosX = `getAttr -t (frame-1) " + sel + ".tx`;\nfloat $lastPosY = `getAttr -t (frame-1) " + sel + ".ty`;\nfloat $lastPosZ = `getAttr -t (frame-1) " + sel + ".tz`;\n\nfloat $tempSpeed = abs (mag (<<" + sel + ".translateX," + sel + ".translateY," + sel + ".translateZ>>)- mag (<<$lastPosX,$lastPosY,$lastPosZ>>) );\n\n" + sel + ".speed = ((($tempSpeed/100)*24)*3.6)", ae=1, uc='all') cmds.select(sel, r=True)
def __init__(self, curve, objects, pointsCount, useTips = False, keepConnected = True, tangent = False,rand = False, groupit = False, animated = False ): """creates objects allong curve, curve: Curve Class object that handles the curve objects: Array of one o more transforms objects to position allong curve pointsCount: Amount of points in the curve useTips: is to position objects in the curve keepConnected: Keep pointOnCurveInfo connected between transform and curve tangent: Manage rotation on objects also rand: Place the objects in random order animated: Add speed attribute to move objects along curve""" self._nodes = [] self._curve = curve if useTips: val = -1 else: val = 1 startParam = 1.0 / ( pointsCount + val ) param = 0 objsIter = it.bicycle( objects ) grp = mn.Node( curve.name + '_grp' ) if groupit: grp = mn.Node( mc.group( n = grp.name, em = True ) ) if animated: grp.a.laps.add( k = True ) with undo.Undo(): for p in range( pointsCount ): #place transform in param point if not useTips: param += startParam if rand: baseobj = random.choice( objects ) else: baseobj = objsIter.next() obj = baseobj.duplicate() self._nodes.append( obj ) if groupit: obj.parent = grp pcurveNode = mn.Node( mc.pathAnimation( obj.name, su=0.5, c=curve.name, fm = True, follow=tangent, followAxis = 'z', upAxis = 'y', worldUpType = 'object', worldUpObject = curve.parent.name ) ) animCurve = pcurveNode.a.uValue.input.node animCurve.delete() if keepConnected: obj.a.parameter.add( k = True ) obj.a.parameter.v = param obj.a.parameter.min = 0 obj.a.parameter.max = 1 obj.a.parameter >> pcurveNode.a.uValue else: if param > 1.0: param = 1 pcurveNode.a.uValue.v = param t = obj.a.t.v r = obj.a.r.v pcurveNode.delete() obj.a.t.v = t[0] obj.a.r.v = r[0] if useTips: param += startParam if animated: cmd = obj.a.parameter.fullname + ' = ( abs( ' + str( obj.a.parameter.v ) + ' + ' + grp.a.laps.fullname + ' ) ) % 1;' mc.expression( s=cmd )
def mirror_locators(**kwargs): file_name = kwargs.setdefault('filename') unmirror = kwargs.setdefault('unmirror', False) file_list = ['up_eye', 'low_eye', 'cheek', 'up_mouth', 'low_mouth'] if unmirror is False: if file_name == 'all': for i in range(0, len(file_list)): file_path = get_file_path('expressions/%s' % file_list[i]) with open(file_path) as myfile: expressionData = myfile.read() mc.expression(string=expressionData, name="%s_Expression" % file_list[i], ae=1, uc='all') py.headsUpMessage('Mirroring for all enabled. Must unmirror to reset locations') else: file_path = get_file_path('expressions/%s' % file_name) with open(file_path) as myfile: expressionData = myfile.read() mc.expression(string=expressionData, name="%s_Expression" % file_name, ae=1, uc='all') py.headsUpMessage('Mirroring for %s enabled. Must unmirror to reset locations' % file_name) else: for i in range(0, len(file_list)): try: mc.delete('%s_Expression' % file_list[i]) except: pass py.headsUpMessage('Mirroring disabled')
def createPolyImagePlane(camera, cameraShape, imagePlane): # Create Nodes implane, polyPlane = cmds.polyPlane(n="projectionCam_PLY", sx=1, sy=1, cuv=2, ch=1, ax=(0, 1, 0), w=1, h=1) planeShape = str(cmds.listRelatives(implane, c=True, type="mesh")[0]) cmds.parent(implane, camera) # Add expression exp = '' exp += 'float $f = %s.focalLength;\n' % cameraShape exp += 'float $fbw = %s.horizontalFilmAperture;\n' % cameraShape exp += 'float $fbh = %s.verticalFilmAperture;\n' % cameraShape exp += 'float $fov = rad_to_deg(2 * atan( ($fbw*25.4) / (2 * $f) ));\n' exp += 'float $planeScale = 2*(%s.depth)*(tand($fov/2.0));\n\n' % imagePlane exp += '%s.width = 1.0;\n' % polyPlane exp += '%s.height = $fbh/$fbw;\n\n' % polyPlane exp += 'translateX = $planeScale*0.5*((%s.offsetX/2.54)/(($fbw/2.54)*0.5));\n' % imagePlane exp += 'translateY = $planeScale*0.5*((%s.offsetY/2.54)/(($fbw/2.54)*0.5));\n' % imagePlane exp += 'translateZ = -1*%s.depth;\n' % imagePlane exp += 'rotateX = 90.0;\n' exp += 'rotateY = rotateZ = 0.0;\n\n' exp += 'scaleX = scaleY = scaleZ = $planeScale;\n\n' cmds.expression(string=exp, object=implane, alwaysEvaluate=True, unitConversion='all') return (implane, planeShape, polyPlane)
def MakeWheel(radius=3.6): # Function returns group name for a wheel myListOfRotValues = range(0, 360, 20) wheel = [] x = 0 for curCyl in myListOfRotValues: curSpoke = mc.polyCylinder(r=0.1, h=radius) wheel.append(curSpoke[0]) mc.move(0, radius / 2, 0) mc.move(0, 0, 0, curSpoke[0] + ".scalePivot", curSpoke[0] + ".rotatePivot") mc.rotate(20 * x, 0, 0) x += 1 wheelCenter = mc.polyCylinder(ax=(1, 0, 0)) wheel.append(wheelCenter[0]) mc.scale(0.22, 0.6, 0.6) wheelEdge = mc.polyTorus(r=radius, sr=0.3, sx=40, sy=5, ax=(1, 0, 0)) mc.scale(0.537, 1, 1) wheel.append(wheelEdge[0]) finalWheel = mc.group(wheel) if trainSpeed > 0: circumference = 2 * 3.14 * radius wheelRotationTime = (circumference / trainSpeed) mc.expression(s="rotateX = time * (360 / " + str(wheelRotationTime) + ");", o=finalWheel) return finalWheel
def runPreset(): cmds.select(clear=True) cmds.promptDialog(message='Nome do sistema MASH:') mashName = cmds.promptDialog(query=True, text=True) if not mashName: mashName = '#' else: mashName = '_' + mashName ############################################################################################ steps = [ 'Selecione as instancias | n >= 2 (arraste com o botao do meio)', 'Selecione a superficie | n = 1 (arraste com o botao do meio)'] accepts = [['mesh'], ['mesh']] ############################################################################################ fx.DropWindow.getDrop( steps, lambda data: smartPreset.send(data), accepts=accepts) node = yield nodes = node.split('\n') ############################################################################################ cmds.promptDialog(message='Numero de pontos:') pointCount = cmds.promptDialog(query=True, text=True) try: pointCount = int(pointCount) except: pointCount = 10 mash = mapi.Network() mash.createNetwork(name='MASH' + mashName, geometry='Instancer') node = yield node = node.split('\n')[0] mash.meshDistribute(node) ############################################################################################ distNodeName = mash.waiter + '_Distribute' cmds.setAttr(distNodeName + '.pointCount', pointCount) idNodeName = mash.waiter + '_ID' cmds.setAttr(idNodeName + '.idtype', 2) count = cmds.getAttr(idNodeName + '.numObjects') pyNode = mash.addNode('MASH_Python') cmds.addAttr(pyNode.name, longName='countID', attributeType='long', defaultValue=count) expr = '{0}.countID = {1}.numObjects'.format(pyNode.name, idNodeName) cmds.expression(s=expr) cmds.addAttr(pyNode.name, longName='seed', attributeType='long', defaultValue=1234) scriptID = ''.join(['p[{0}] = 1 # {1} prob.\n'.format(i, e) for i, e in enumerate(nodes)]) cmds.setAttr(pyNode.name + '.pyScript', SCRIPT.format(scriptID), type='string') randNode = mash.addNode('MASH_Random') cmds.setAttr(randNode.name + '.positionX', 0) cmds.setAttr(randNode.name + '.positionY', 0) cmds.setAttr(randNode.name + '.positionZ', 0) cmds.setAttr(randNode.name + '.rotationY', 180) cmds.setAttr(randNode.name + '.scaleX', 1) cmds.setAttr(randNode.name + '.uniformRandom', 1) strengthNode = mash.addNode('MASH_Strength') yield
def main(): if mc.objExists("*horizonLine*"): mc.delete("*horizonLine*") # Delete existing "horizonLine" return active3dViewCamShape, active3dViewCamTrans = getActive3dViewCam() horizonLineTrans = mc.circle(name='horizonLine', radius=2, normal=(0, 1, 0), sections=32)[0] horizonLineShape = mc.listRelatives(horizonLineTrans, shapes=True, fullPath=True)[0] mc.expression(s=""" {0}.sx = {1}.nearClipPlane; {0}.sy = {1}.nearClipPlane; {0}.sz = {1}.nearClipPlane; """.format(horizonLineTrans, active3dViewCamShape), object=horizonLineTrans) mc.setAttr(horizonLineShape + '.overrideEnabled', 1) mc.setAttr(horizonLineShape + '.overrideColor', 14) mc.pointConstraint(active3dViewCamTrans, horizonLineTrans, maintainOffset=False) mc.select(clear=True)
def customizeCamera(self, camera): cmds.lookThru(camera) cmds.addAttr(camera, ln="Overlay", at="enum", en="No Overlay:Grid:SpiralTopRight:SpiralTopLeft:SpiralBottomRight:SpiralBottomLeft") cmds.addAttr(camera, ln="Overlay_Value", at="long") cmds.setAttr(camera + '.Overlay', e=True, keyable=True) cmds.setAttr(camera + '.Overlay_Value', e=True, keyable=True) cmds.expression(s='int $a=%s.Overlay;\r\n' % camera + '%s.Overlay_Value=$a;' % camera+ 'switch($a) { \r\n' + ' case 0: \r\n' + ' python("camera_overlays.Overlay_Function().noOverlay()"); \r\n' + ' break;\r\n' + ' case 1: \r\n' + ' python("camera_overlays.Overlay_Function().toggleThirdsGrid()"); \r\n' + ' break;\r\n' + ' case 2: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialTopRight()"); \r\n' + ' break;\r\n' + ' case 3: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialTopLeft()"); \r\n' + ' break;\r\n' + ' case 4: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialBottomRight()"); \r\n' + ' break;\r\n' + ' case 5: \r\n' + ' python("camera_overlays.Overlay_Function().toggleGoldenSprialBottomLeft()"); \r\n' + '}select %s;\r' % camera, ae=False, o="renderCam")
def _update_flipbook_node(new_page, current_frame): """ Updates the flipbook node with a new page in the enumerator and sets the key for that frame. :param new_page: :type new_page: :returns: None """ # ...: cmds.expression(object=new_page, name="%s_visbility_EXP" % (new_page), string="int $page = %d;\n" "int $current_keyed_frame = flipbook_LOC.pagesToDisplay;\n" "%s.visibility = ($page==$current_keyed_frame)||(visibilityOverride);" % (current_frame, new_page), alwaysEvaluate=True) # We will also be adding another attribute with just integer values. # This will be set here at this point as well. cmds.setKeyframe("flipbook_LOC.pagesToDisplay", value=current_frame, time=current_frame, outTangentType="step") # Return: return
def createExpression(att, minVal, maxVal, speed): """ create a expresion for wave animation - animate objects attribute using a wave Function - create a custom speed atribute - Calculate values for the wave fuction: speed = wave to strech or shrink alnog the horizantal multiplier = overal range (min/max, or top/down wave) offset = min/max values are where they should be. we move the 0 position of the wave to be midway between our minVal and maxVal - Create the expression - run script when item is seleced """ # get selected object objs = cmds.ls(selection=True) obj = objs[0] # create Attr: Speed cmds.addAttr(obj, longName="speed", shortName="speed", min=0, keyable=True) amplitude = (maxVal - minVal)/2.0 # multiplier offset = minVal + amplitude # offset # set expresion items baseString = "{0}.{1} = ".format(obj, att) # object.attribute as string sineClause = '(sin(time * '+ obj + '.speed)' # sin Function as a string valueClause = ' * ' + str(amplitude) + ' + ' + str(offset) + ')' # set expression expressionString = baseString + sineClause + valueClause cmds.expression(string=expressionString)
def editMainExpression(objectName="", splashDisc="", oceanShader="", objectNameEmitter="", wakeEmitter="", splashDiscEmitter=""): """ editing the main expression for the scene @param splashDiscParticle: Name of SplashDiscParticle @type splashDiscParticle: String -------------------------------------------- @return: 0-ExpressionText """ oldMainExoression = cmds.expression("ocean_MainExpression",query=True, string=True) startExpression = "\n////////////////////////////// Start %s Expression //////////////////////////////\n"%objectName newExp = "" newExp += "float $%s_particleSprayRate = 3000;\n"%objectName newExp += "float $%s_particleBubblesRate = 100;\n" %objectName newExp += "float $%s_fluidDisplacement = 6.0;\n" %objectName newExp += "float $%s_fluidFoam = 2.0;\n" %objectName newExp += "float $%s_u = .I[0];\n" %objectName newExp += "float $%s_v = .I[1];\n" %objectName newExp += "float $%s_disp[] = `colorAtPoint -u $%s_u -v $%s_v %s`;\n" %(objectName,objectName,objectName,oceanShader) newExp += "float $%s_lastY = `getAttr -time (frame - 2) %s.translateY`;\n" %(objectName,objectName) newExp += "float $%s_curY = %s.translateY;\n" %(objectName,objectName) newExp += "float $%s_ydiff = $%s_lastY - $%s_curY;\n" %(objectName,objectName,objectName) newExp += "if( $%s_curY < 0.5 ){\n\t"%objectName newExp += "%s.rate = $%s_particleBubblesRate;"%(objectNameEmitter,objectName) newExp += "\n} else {\n\t" newExp += "%s.rate = 0;\n}\n"%objectNameEmitter newExp += "if( $%s_ydiff < 0 ){\n\t"%objectName newExp += "$%s_ydiff = -$%s_ydiff;"%(objectName,objectName) newExp += "\n}\n" newExp += "if( $%s_curY > -1 && $%s_curY < 0.6 ){\n\t"%(objectName,objectName) newExp += "%s.fluidDensityEmission = $%s_fluidDisplacement;\n\t"%(wakeEmitter,objectName) newExp += "%s.fluidHeatEmission = $%s_fluidFoam;"%(wakeEmitter,objectName) newExp += "\n} else {\n\t" newExp += "%s.fluidDensityEmission = 0;\n\t"%wakeEmitter newExp += "%s.fluidHeatEmission = 0;"%wakeEmitter newExp += "\n}\n" newExp += "if( $%s_curY > -1 && $%s_curY < 0.5 && $%s_ydiff > 0.05 ){\n\t"%(objectName,objectName,objectName) newExp += "%s.rate = $%s_particleSprayRate * $%s_ydiff;\n\t"%(splashDiscEmitter,objectName,objectName) newExp += "float $%s_speed = $%s_ydiff * 10;\n\t"%(objectName,objectName) newExp += "if( $%s_speed > 10 ){\n\t\t"%objectName newExp += "$%s_speed = 10;"%objectName newExp += "\n\t}\n\t" newExp += "%s.speed = $%s_speed;"%(splashDiscEmitter,objectName) newExp += "\n} else {\n\t" newExp += "%s.rate = 0;"%splashDiscEmitter newExp += "\n}\n" newExp += "%s.translateY = $%s_disp[0];\n"%(splashDisc,objectName) newExp += "float $%s_dummy = %s.displacement;\n"%(objectName,oceanShader) endExpression = "////////////////////////////// End %s Expression //////////////////////////////\n\n"%objectName totalExp = oldMainExoression+startExpression+newExp+endExpression cmds.expression ("ocean_MainExpression",string=totalExp ,edit=True, alwaysEvaluate=1, unitConversion="all") return totalExp
def createObjs(self): #Materials matCols = [[0, 1, 1], [1, 1, 0], [0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0.5, 0], [1, 0, 1]] for num in range(7): name = 'mino_' + str(num) + '_mat' if not cmds.objExists(name + 'SG'): cmds.sets(n=name + 'SG', renderable=1, noSurfaceShader=1, empty=1) if not cmds.objExists(name): cmds.shadingNode('lambert', asShader=1, n=name) cmds.setAttr(name + '.color', matCols[num][0], matCols[num][1], matCols[num][2], type='double3') cmds.connectAttr(name + '.outColor', name + 'SG.surfaceShader', f=1) #Anim for force evaluation if (not cmds.objExists('dummyAnim')): cmds.createNode('animCurveTU', name='dummyAnim') cmds.setAttr('dummyAnim.postInfinity', 3) cmds.setKeyframe('dummyAnim', t=0, v=1) cmds.setKeyframe('dummyAnim', t=1, v=1.0001) #borad for x in range(w): for y in range(h): coreName = '_' + str(x) + '_' + str(y) for c in range(7): name = 'c' + str(c) + coreName sgName = 'mino_' + str(c) + '_matSG' if not cmds.objExists(name): cmds.polyCube(n=name, w=0.95, d=0.95, h=0.95) cmds.setAttr('.t', x, y, 0) cmds.sets(name, e=1, fe=sgName) cmds.connectAttr('dummyAnim.o', name + '.sz', f=1) #controllers if not cmds.objExists('b_left'): cmds.group(em=1, n='b_left') cmds.group(n='b_up') cmds.group(em=1, n='b_down') cmds.group(n='neutral', parent='b_up') cmds.group(em=1, n='b_right', parent='b_up') #expression if not cmds.objExists('input_exp'): cmds.expression( n='input_exp', s="neutral.translateX=0;\nstring $sels[]=`ls -sl`;\n" + "python (\"t.tetObj.update('\"+$sels[0]+\"')\");\nselect -r neutral;", o='right', ae=1, uc='all')
def connectAttrs(newObj,oldObj): #r = str(0.7) for attr in attrs: #if attr=='translateX': # #scale translateX # cmds.expression(s = newObj+'.' +attr+ ' = ' + r + '*' + oldObj+'.' +attr) #else: cmds.expression(s = newObj+'.' +attr+ ' = ' + oldObj+'.' +attr)
def loop_selection(num_loops, step=1): """ Loop over selected pages num_loop times. With the pages selected in the maya scene, loop over the pages num_loop times with step amount of frames between each loop. And some... :param num_loops: The page to display. :param step: The number of frames between the loop. :type num_loops: int. :type step: int. :returns: List. :raises: None. .. note:: There is a Maya Expression declared in this function as a string. This could be removed to another file and use something like Jinja to work with it. """ # If there are pages selected: pages = cmds.ls(selection=True) if pages: regex = re.compile(r"page_(\d{4})") page_vals = [int(regex.search(page).group(1)) for page in pages] inc_value = (page_vals[-1] + step) - page_vals[0] page_loop = [page_vals[i] + (j * inc_value) for j in xrange(num_loops) for i in xrange(len(page_vals))] # page_array = "" # Set the expression now: for index, page in enumerate(page_vals): page_name = "page_%04d" % (page) expr_name = "page_%04d_visbility_EXP" % (page) if cmds.objExists(expr_name): cmds.delete(expr_name) # Reads the expression from the ./templates folder and fills # in the values before setting the expression on the curves # for that given page: exp = open(os.path.join(TEMPLATE_DIR, 'flipbookexpression.mel'), 'r').read() exp = exp % {'values': ','.join(map(str, page_loop[index::len(page_vals)])), 'end_values': ','.join(map(str, page_loop[index + 1::len(page_vals)])), 'page': page, 'page_name': page_name} cmds.expression(object=page_name, name=expr_name, string=exp, alwaysEvaluate=True) go_to_page(page_vals[-1] + 1) page_name = "page_%04d" % (page_vals[-1] + 1) set_empty_page() # Return the loop list: return page_loop
def mkCam(name=None, img_plane_imgs=None, *args, **kwds): camera_node = mkNode("%s_cam" % name, "camera", *args, **kwds) img_plane_node = mkNode("%s_imagePlane" % name, "imagePlane") img_plane_node = mc.listRelatives(img_plane_node, shapes=True, fullPath=True)[0] annotate_node = mc.annotate("%s_cam" % name, text="tc=...", point=(0, -3, -10)) annotate_node = mc.rename( mc.listRelatives(annotate_node, parent=True, fullPath=True), "%s_timecode" % name) if img_plane_imgs: if ROOT_DIR is not None: img_plane_imgs = os.path.join(ROOT_DIR, img_plane_imgs) mc.setAttr("%s.imageName" % img_plane_node, img_plane_imgs, type="string") mc.connectAttr("%s.message" % img_plane_node, "%s.imagePlane[0]" % camera_node) # you'd think that this was the default, to actually use frameOffset, but nooooooo.... mc.expression(s="%s.frameExtension=frame+%s.frameOffset" % (img_plane_node, img_plane_node)) mc.setAttr("%s.rotateOrder" % camera_node, 3) mc.setAttr("%s.focalLength" % camera_node, 28.0) mc.setAttr("%s.alphaGain" % img_plane_node, 0.85) mc.setAttr("%s.useFrameExtension" % img_plane_node, 1) mc.addAttr(camera_node, longName="tc_h", attributeType="byte") mc.addAttr(camera_node, longName="tc_m", attributeType="byte") mc.addAttr(camera_node, longName="tc_s", attributeType="byte") mc.addAttr(camera_node, longName="tc_f", attributeType="byte") mc.addAttr(camera_node, longName="msg_num", attributeType="long") mc.parent(annotate_node, img_plane_node, camera_node, relative=True) script = """string $tc = ""; string $h = $$NAME$$_cam.tc_h; string $m = $$NAME$$_cam.tc_m; string $s = $$NAME$$_cam.tc_s; string $f = $$NAME$$_cam.tc_f; if (size($h)==1) $h = "0" + $h; if (size($m)==1) $m = "0" + $m; if (size($s)==1) $s = "0" + $s; if (size($f)==1) $f = "0" + $f; $tc = "tc=" + $h + ":" + $m + ":" + $s + "." + $f; setAttr $$NAME$$_timecodeShape.text -type \"string\" $tc; """.replace("$$NAME$$", name) mc.expression(name="%s_tc_update" % annotate_node, object=annotate_node, string=script) mc.select(camera_node) return camera_node
def _setDistance(self): ''' Creates expression Exp: moveVector = currentPosition - oldPosition ''' exp = 'vector $move = <<%s.mvx,%s.mvy,%s.mvz>>;\n'%(self.node,self.node,self.node) exp += '%s.distance = mag($move);\n'%self.node cmds.expression(s=exp,n='%s_distExp'%self.ctrlName)
def CreateArnoldShader(self): if not mc.pluginInfo('mtoa.mll', q=True, l=True): mc.loadPlugin('mtoa.mll') planel = mc.ls(sl=True) if not planel: mc.confirmDialog(title=u"提示", message=u'请选择polyPlane!') return for p in planel: try: mc.setAttr('%s.aiOpaque' % p, 0) mc.setAttr('%s.aiSubdivType' % p, 1) mc.setAttr('%s.aiSubdivIterations' % p, 4) except: pass seaShader = mc.shadingNode('aiStandard', asShader=True, n='seaShader') #seaSG = mc.shadingNode('shadingEngine', asShader = True, n = 'seaSG') seaSG = mc.sets(renderable=True, noSurfaceShader=True, empty=True, name='seaSG') mc.connectAttr('%s.outColor' % seaShader, '%s.surfaceShader' % seaSG, f=True) mc.select(planel) mc.sets(e=True, forceElement=seaSG) mc.setAttr('%s.color' % seaShader, 0, 0, 0, type='double3') mc.setAttr('%s.Kd' % seaShader, 0) mc.setAttr('%s.KsColor' % seaShader, 1, 1, 1, type='double3') mc.setAttr('%s.Ks' % seaShader, 0.5) mc.setAttr('%s.specularRoughness' % seaShader, 0) mc.setAttr('%s.specularFresnel' % seaShader, 1) mc.setAttr('%s.Ksn' % seaShader, 0.45) mc.setAttr('%s.Kt' % seaShader, 1) mc.setAttr('%s.IOR' % seaShader, 1.33) mc.setAttr('%s.opacity' % seaShader, 0.78, 0.78, 0.78, type='double3') seaDeform = mc.shadingNode('Ocean_Octvision', asShader=True, n='Ocean_Octvision') disShader = mc.shadingNode('displacementShader', asShader=True, n='OceanDisplacement') mc.connectAttr('%s.outColor' % seaDeform, '%s.vectorDisplacement' % disShader, f=True) mc.connectAttr('%s.displacement' % disShader, '%s.displacementShader' % seaSG, f=True) mc.expression(s='%s.time = 0.5*time;' % seaDeform, o=seaDeform, ae=True, uc=all)
def addCorrectiveExpressionToMaster(master, blendshape_dummy, blendshape1, blendshape2): """ Add expression to turn on corrective expression when bs1 and bs2 are active. """ master_blendshape = getBlendshapesFromMaster(master)[0] expression_name = "exp_" + blendshape_dummy expression_string = master_blendshape+"."+blendshape_dummy + "=" + master_blendshape +"."+blendshape1 + " * " + master_blendshape+"."+blendshape2 + ";" expression(s=expression_string, n=expression_name)
def createAnimation(): freq = .1 offset = 0 amp = 10 cmds.expression(s = 'ctrl_0.rotateZ = sin((frame*.1)+0)*10') cmds.expression(s = 'ctrl_2.rotateZ = sin((frame*.1)+0)*10')
def swimExp(conObj, trgObjs, roAxis): for trg in trgObjs: cmds.expression( n='%s_swim_exp' % trg, ae=True, uc=all, s="// master controls\n $on_off = %s.on_off;\n $masSpeed = %s.speed;\n $masDelay = %s.delay;\n $masAmplitude = %s.amplitude;\n\n $speed = %s.%s_speed;\n $delay = %s.%s_delay;\n $amplitude = %s.%s_amplitude;\n\n %s_swim_grp.rotate%s = (sin((time * $speed * $masSpeed) + $delay + $masDelay) * $amplitude * $masAmplitude) * $on_off;" % (conObj, conObj, conObj, conObj, conObj, trg, conObj, trg, conObj, trg, trg, roAxis))
def modifyBtnCmd(self, *args): nodeName = self.getNodeName() movieInputList = cmds.listConnections('%s_movieNode'%nodeName) expressions = [item for item in movieInputList if 'expression' in item] print expressions expressionString = cmds.expression(expressions[0], q = 1, s = 1) offsetFrame = cmds.intField(self.frameOffset, q = 1, v = 1) newString = '%s.frameExtension = frame - %s'%('%s_movieNode'%nodeName, str(offsetFrame)) cmds.expression(expressions[0], e = 1, s = newString)
def generateSpider(input_namespace, startTime, endTime): ''' this function attaches all curves together, without replacing the orignal curves, using it as a motion path for an animated spider. the animated spider is imported, and a simple expression links the U value of the motion path to a rotation attribute on the spider rig, controlling its walk cycle. there is also a custom attribute on the controller that appears with the spider rig, controlling the length of its steps as it walks. ''' filePath = cmds.internalVar( usd=True ) + 'SpiderGen/spider.ma' #the file path at which the spider model should exist fileExists = cmds.file(filePath, q=True, ex=True) #queries whether the file exists if fileExists is True: #selects all of the spiralling curves and connects them, providing a 'path' for the spiders movement. cmds.select(str(input_namespace) + 'curve_spiral*') curves = cmds.ls(selection=True) path = cmds.attachCurve(curves, n=str(input_namespace) + 'spiderpath', rpo=False) cmds.rebuildCurve(path, rt=3) cmds.hide(path) cmds.file(filePath, i=True) #renames the spider and it's callable controllers so that they are using the current 'namespace'. cmds.rename('SPIDER_RIG', str(input_namespace) + 'SPIDER_RIG') cmds.rename('SCALE_HANDLE', str(input_namespace) + 'CONTROLLER_ScaleMe') cmds.rename('CONTROLLER', str(input_namespace) + 'CONTROLLER') #selects the scale controller and the path and connects them to a path animation. cmds.select(str(input_namespace) + 'CONTROLLER_ScaleMe', path) cmds.pathAnimation(stu=startTime, etu=endTime, f=True, fa='x', ua='y', name=str(input_namespace) + 'motionpath') #creates a command that links the controller rotation to the 'length' of the animation. command = str(input_namespace) + 'CONTROLLER.rotateX = ' + str( input_namespace) + 'motionpath_uValue.output * ' + str( (endTime - startTime) / 10) #creates an expression of that command which is used for moving the legs as the spider moves around the path. cmds.expression(name=str(input_namespace) + 'leg_movement', alwaysEvaluate=True, s=command) else: #an error window for if the file is not found cmds.confirmDialog( title='Error', message='Spider Model not found, please ensure it located at: ' + str(filePath), button=['OK'], cancelButton='OK') return fileExists #so that the grouping functions know not to expect the spider model or motionpath
def createRamdomRotationInSpace(CNT=None, targets=None, nameNode='RAMDOMSIN_'): if not cmds.attributeQuery(nameNode + 'AMPLITUDE', n=CNT, exists=True): cmds.addAttr(CNT, shortName=nameNode + 'AMPLITUDE', longName=nameNode + 'AMPLITUDE', defaultValue=0, k=True) if not cmds.attributeQuery(nameNode + 'FRECUENCY_X', n=CNT, exists=True): cmds.addAttr(CNT, shortName=nameNode + 'FRECUENCY_X', longName=nameNode + 'FRECUENCY_X', defaultValue=0.6, k=True) if not cmds.attributeQuery(nameNode + 'FRECUENCY_Y', n=CNT, exists=True): cmds.addAttr(CNT, shortName=nameNode + 'FRECUENCY_Y', longName=nameNode + 'FRECUENCY_Y', defaultValue=0.8, k=True) if not cmds.attributeQuery(nameNode + 'FRECUENCY_Z', n=CNT, exists=True): cmds.addAttr(CNT, shortName=nameNode + 'FRECUENCY_Z', longName=nameNode + 'FRECUENCY_Z', defaultValue=-0.5, k=True) if not cmds.attributeQuery(nameNode + 'TIME_OFFSET_X', n=CNT, exists=True): cmds.addAttr(CNT, shortName=nameNode + 'TIME_OFFSET_X', longName=nameNode + 'TIME_OFFSET_X', defaultValue=0.0, k=True) if not cmds.attributeQuery(nameNode + 'TIME_OFFSET_Y', n=CNT, exists=True): cmds.addAttr(CNT, shortName=nameNode + 'TIME_OFFSET_Y', longName=nameNode + 'TIME_OFFSET_Y', defaultValue=0.0, k=True) if not cmds.attributeQuery(nameNode + 'TIME_OFFSET_Z', n=CNT, exists=True): cmds.addAttr(CNT, shortName=nameNode + 'TIME_OFFSET_Z', longName=nameNode + 'TIME_OFFSET_Z', defaultValue=0.0, k=True) cmds.expression( s=str(targets) + ".rx = sin( time*" + str(CNT) + '.' + nameNode + 'FRECUENCY_X+' + str(CNT) + '.' + nameNode + 'TIME_OFFSET_X' + ")*" + str(CNT) + '.' + nameNode + 'AMPLITUDE' + ";\n" + str(targets) + ".ry = sin( time*" + str(CNT) + '.' + nameNode + 'FRECUENCY_Y+' + str(CNT) + '.' + nameNode + 'TIME_OFFSET_Y' + ")*" + str(CNT) + '.' + nameNode + 'AMPLITUDE' + ";\n" + str(targets) + ".rz = sin( time*" + str(CNT) + '.' + nameNode + 'FRECUENCY_Z+' + str(CNT) + '.' + nameNode + 'TIME_OFFSET_Z' + ")*" + str(CNT) + '.' + nameNode + 'AMPLITUDE' + ";", n=nameNode + 'RAMDOM_EXP')
def _setMoveVector(self): ''' Creates expression Exp: Using currentPosition, oldPosition, get moveVector. ''' exp = '%s.mvx = %s.cpx - %s.ppx;\n'%(self.node,self.node,self.node) exp += '%s.mvy = %s.cpy - %s.ppy;\n'%(self.node,self.node,self.node) exp += '%s.mvz = %s.cpz - %s.ppz;\n'%(self.node,self.node,self.node) cmds.expression(s=exp,n='%s_moveVecExp'%self.ctrlName)
def createShoulderIndicator(trackway): shoulders, shape = cmds.polyCube(name='shoulders', width=15, height=15, depth=15) groupItems.append(shoulders) cmds.move(0, 100, 0, shoulders) manus = trackway.manus cmds.expression("%s.z = 0.5*abs(%s.z - %s.z) + min(%s.z, %s.z)" % ( shoulders, manus.left, manus.right, manus.left, manus.right)) return shoulders
def _set_expression(cls, driven_ctl, driver_ctl, attr_dict): expression = '' for k, v in attr_dict.iteritems(): if mc.getAttr('%s.%s' % (driven_ctl, k), lock=True): mc.setAttr('%s.%s' % (driven_ctl, k), lock=False, keyable=True, channelBox=True) expression += '%s.%s = %s.%s;' % (driven_ctl, k, driver_ctl, v) mc.expression(s=expression)
def AngleD(): tar_jo = list(range(3)) exps = list(range(0)) jnt = mc.ls(sl=True) tar = mc.listRelatives('{}'.format(jnt[0])) par = mc.listRelatives('{}'.format(jnt[0]), p=True) mc.addAttr(ln='bendH', sn='bh', at='doubleAngle') mc.addAttr(ln='bendV', sn='bv', at='doubleAngle') mc.addAttr(ln='aimVector', nc=3, at='double3') for i in range(3): mc.addAttr(ln='aimVector{}'.format(xyz[i]), at='double', p='aimVector') spc = mc.group(em=True, n='{}_driver'.format(jnt[0])) mc.parent(spc, jnt[0]) for i in range(3): mc.setAttr('{0}.translate{1}'.format(spc, xyz[i]), 0) mc.setAttr('{0}.rotate{1}'.format(spc, xyz[i]), 0) #createNode vep = mc.createNode('vectorProduct', n='{}_vectorProduct'.format(jnt[0])) exp = mc.expression(n='{}_Exp'.format(jnt[0]), o='{}'.format(jnt[0])) mc.expression(exp, e=True, uc='none', ae=0) #setAttr mc.setAttr('{}.input1X'.format(vep), 1.0) mc.setAttr('{}.operation'.format(vep), 3) mc.setAttr('{}.normalizeOutput'.format(vep), True) #connectAttr mc.connectAttr('{}.matrix'.format(spc), '{}.matrix'.format(vep)) mc.connectAttr('{0}.output[0]'.format(exp), '{}.bendH'.format(jnt[0])) mc.connectAttr('{0}.output[1]'.format(exp), '{}.bendV'.format(jnt[0])) for i in range(3): mc.connectAttr('{0}.output{1}'.format(vep, xyz[i]), '{0}.aimVector{1}'.format(jnt[0], xyz[i])) mc.connectAttr('{0}.aimVector{1}'.format(jnt[0], xyz[i]), '{0}.input[{1}]'.format(exp, i)) mc.connectAttr('{0}.translate{1}'.format(jnt[0], xyz[i]), '{0}.translate{1}'.format(spc, xyz[i])) mc.connectAttr('{0}.rotate{1}'.format(jnt[0], xyz[i]), '{0}.rotate{1}'.format(spc, xyz[i])) mc.connectAttr('{0}.scale{1}'.format(jnt[0], xyz[i]), '{0}.scale{1}'.format(spc, xyz[i])) mc.connectAttr('{0}.shear{1}'.format(jnt[0], xyz[i]), '{0}.shear{1}'.format(spc, xyz[i])) #expression exps.append('vector $x_vec = <<1., .0, .0>>;') exps.append('vector $y_vec = <<.0, 1., .0>>;') exps.append('vector $z_vec = <<.0, .0, 1.>>;') exps.append('vector $vec = <<' + jnt[0] + '.aimVectorX, ') exps.append(jnt[0] + '.aimVectorY, ' + jnt[0] + '.aimVectorZ>>;') exps.append('float $aim = dot($x_vec, $vec) + 1;') exps.append(jnt[0] + '.bendH = atan2(dot($z_vec, $vec), $aim) * -2.;') exps.append(jnt[0] + '.bendV = atan2(dot($y_vec, $vec), $aim) * 2.;') imp = ''.join(exps) mc.expression(exp, e=True, s='{}'.format(imp))
def _create_FOAM_FluidTexture(oceanShader = '', size = '', pathToPreset = '', foamFluidShapeName = CONST.FOAM_FLUID_SHAPENODE): """ create a 3d fluid texture for FOAM, make it a 2d simulation and texture the foamOffset of the ocean shader with it's outAlpha. """ debug(None, method = 'fluids_lib._create_FOAM_FluidTexture', message = 'Building fluid %s' % foamFluidShapeName, verbose = False) fluidShape = cmds.shadingNode('fluidTexture3D', asTexture = True, name = foamFluidShapeName) # Get parent of shape and set attrs fluid = cmds.listRelatives(fluidShape, parent= True) _setBaseFluidAttrs(fluid) ## Connect to time cmds.connectAttr ("time1.outTime",(fluidShape + ".currentTime")) debug(None, method = 'fluids_lib._create_FOAM_FluidTexture', message = '%s connected to time1' % fluidShape, verbose = False) ## Apply foam preset mel.eval("""applyPresetToNode " """+fluidShape+""" " "" "" "%s" 1;""" % pathToPreset) debug(None, method = 'fluids_lib._create_FOAM_FluidTexture', message = 'Mel preset applied: %s' % pathToPreset, verbose = False) #add expression to texture expStringList = [ "float $foamSpeed = 1.0;\n", "%s.textureTime = time * $foamSpeed;\n" % fluidShape ] utils.checkExpressionExists('s_foamTexture_Speed') cmds.expression(n = '%s_foamTexture_Speed' % fluidShape, string = utils.processExpressionString(expStringList)) expStringList = [ 'int $width = %s.dimensionsW;\r\n' % fluidShape, 'int $height = %s.dimensionsH;\r\n' % fluidShape, 'if ($width>= $height)\r\n', '{\r\n', '%s.baseResolution = $width*2;\r\n' % fluidShape, '}\r\n', 'else\r\n', '{\r\n', '%s.baseResolution = $height*2;\r\n' % fluidShape, '}' ] #expression to maintain resolution/container size relationship cmds.expression(n = '%s_foamTexture_ContainerSize' % fluidShape, string = utils.processExpressionString(expStringList)) debug(None, method = 'fluids_lib._create_FOAM_FluidTexture', message = ' Expression %s_foamTexture_ContainerSize built' % fluidShape, verbose = False) baseTextureName = fluidShape.split('Shape')[0] cmds.rename(fluid[0], '%s' % baseTextureName) utils.createTypeTag(obj = '%s' % baseTextureName, typeName = '%s' % baseTextureName) debug(None, method = 'fluids_lib._create_FOAM_FluidTexture', message = ' Rename and Tag successful..', verbose = False) ## Connect fluid to ocean shader cmds.connectAttr("%s.outAlpha" % fluidShape, "%s.foamOffset" % oceanShader, force = True) debug(None, method = 'fluids_lib._create_FOAM_FluidTexture', message = ' Returning %s:' % fluidShape, verbose = False) return fluidShape
def animerDeformation(lenteur, nomDeform): nom = str(nomDeform) + "_Expression" if (not cmds.objExists(nom)): cmds.expression(n=nom, s=nomDeform + ".offset = time1.outTime/" + str(lenteur)) else: cmds.expression(nom, e=True, s=nomDeform + ".offset = time1.outTime/" + str(lenteur))
def _misss_fast_skin_maya(self): node = cmds.shadingNode('misss_fast_skin_maya', asShader=True) tex = cmds.shadingNode('mentalrayTexture', asTexture=True) cmds.expression(string="%s.miWidth = defaultResolution.width * 2" % tex) cmds.expression(string="%s.miHeight = defaultResolution.height" % tex) cmds.setAttr(tex + ".miWritable", 1) cmds.setAttr(tex + ".miDepth", 4) lmap = cmds.shadingNode('misss_fast_lmap_maya', asUtility=True) cmds.connectAttr(tex + '.message', node + '.lightmap') cmds.connectAttr(tex + '.message', lmap + '.lightmap')
def _misss_fast_skin_maya(self): node = cmds.shadingNode('misss_fast_skin_maya', asShader=True) tex = cmds.shadingNode('mentalrayTexture', asTexture=True) cmds.expression( string="%s.miWidth = defaultResolution.width * 2" % tex) cmds.expression(string="%s.miHeight = defaultResolution.height" % tex) cmds.setAttr(tex + ".miWritable", 1) cmds.setAttr(tex + ".miDepth", 4) lmap = cmds.shadingNode('misss_fast_lmap_maya', asUtility=True) cmds.connectAttr(tex + '.message', node + '.lightmap') cmds.connectAttr(tex + '.message', lmap + '.lightmap')
def createMainExpression(objectNameEmitter=""): """ creating main expression for the scene @param objectNameEmitter: Name of objectNameEmitter @type objectNameEmitter: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "////////////////////////////// Main Expression //////////////////////////////\n\n" cmds.expression (o=objectNameEmitter, string=newExp, alwaysEvaluate=1, unitConversion="all", name = "ocean_MainExpression") return newExp
def createGCTRL(self, *args): if cmds.objExists('gravCTRL'): cmds.error('请勿重复创建') cmds.select('gravCTRL') else: cmds.curve(n='pvGravArrow', d=1, p=[(0, 15, 0), (-4, 4, -4), (4, 4, -4), (0, 15, 0), (4, 4, 4), (-4, 4, 4), (0, 15, 0), (4, 4, -4), (2, 4, -2), (3, -15, -3), (-3, -15, -3), (-2, 4, -2), (-4, 4, -4), (-4, 4, 4), (-2, 4, 2), (-3, -15, 3), (3, -15, 3), (2, 4, 2), (4, 4, 4), (4, 4, -4), (2, 4, -2), (-2, 4, -2), (-2, 4, 2), (2, 4, 2), (2, 4, -2), (2, 4, -2), (3, -15, -3), (3, -15, 3), (-3, -15, 3), (-3, -15, -3)], k=range(30)) cmds.rotate(180, 0, 0) cmds.makeIdentity(apply=True, t=True, r=True, s=True, n=True) getShape = cmds.listRelatives(s=True, pa=True)[0] cmds.rename(getShape, 'pvGravArrowShape') cmds.spaceLocator(n='pvGravOrigin') cmds.setAttr('pvGravOrigin.visibility', 0) cmds.spaceLocator(n='pvGravAim') cmds.setAttr('pvGravAim.visibility', 0) cmds.group('pvGravAim', n='pvGravAim_Null') cmds.setAttr('pvGravAim.translateY', -1) cmds.aimConstraint('pvGravAim', 'pvGravOrigin') cmds.group('pvGravArrow', n='gravCTRL') cmds.parentConstraint('gravCTRL', 'pvGravAim_Null') cmds.select('pvGravArrowShape', 'gravCTRL') cmds.parent(r=True, s=True) cmds.delete('pvGravArrow') cmds.pointConstraint('gravCTRL', 'pvGravOrigin') cmds.pickWalk(direction="up") cmds.addAttr(ln='dynamicAmplitude', nn='Dynamic Amplitude', at='float', dv=1); cmds.setAttr('gravCTRL.dynamicAmplitude', k=True) cmds.expression(s='pvGravAim.translateY=gravCTRL.dynamicAmplitude*-1') cmds.setAttr('pvGravArrowShape.overrideEnabled', 1) cmds.setAttr('pvGravArrowShape.overrideColor', 6) cmds.group('pvGravOrigin', 'pvGravAim_Null', 'gravCTRL', n='gravCTRL_GRP') cmds.setAttr('gravCTRL_GRP.translateX', k=False, l=True) cmds.setAttr('gravCTRL_GRP.translateY', k=False, l=True) cmds.setAttr('gravCTRL_GRP.translateZ', k=False, l=True) cmds.setAttr('gravCTRL_GRP.rotateX', k=False, l=True) cmds.setAttr('gravCTRL_GRP.rotateY', k=False, l=True) cmds.setAttr('gravCTRL_GRP.rotateZ', k=False, l=True) cmds.setAttr('gravCTRL_GRP.scaleX', k=False, l=True) cmds.setAttr('gravCTRL_GRP.scaleY', k=False, l=True) cmds.setAttr('gravCTRL_GRP.scaleZ', k=False, l=True) cmds.setAttr('gravCTRL_GRP.visibility', k=False, l=True) for eachNucleus in cmds.ls(type='nucleus'): cmds.connectAttr('pvGravOrigin_aimConstraint1.constraintVectorX', '%s.gravityDirectionX' % eachNucleus) cmds.connectAttr('pvGravOrigin_aimConstraint1.constraintVectorY', '%s.gravityDirectionY' % eachNucleus) cmds.connectAttr('pvGravOrigin_aimConstraint1.constraintVectorZ', '%s.gravityDirectionZ' % eachNucleus) cmds.select('gravCTRL');
def constrain_locator_to_vertex (): # _camera = Camera() _vertex = cmds.ls (selection = True)[0] _geo = _vertex[:_vertex.rfind('.')] _locator = cmds.createNode ('locator') _locator = cmds.pickWalk (direction = 'up')[0] # cmds.aimConstraint (_camera.transform, _locator, worldUpType = 'objectrotation', worldUpObject = _camera.transform) cmds.expression (string =''' float $BBoxSize = ''' + _geo + '''.boundingBoxMinX;\n float $vertexWorldPos[3] = `pointPosition -world ''' + _vertex + '''`;\n''' + _locator + '''.translateX = $vertexWorldPos[0];\n''' + _locator + '''.translateY = $vertexWorldPos[1];\n''' + _locator + '''.translateZ = $vertexWorldPos[2];''' )
def constrain_locator_to_vertex (): vertex = cmds.ls (selection = True)[0] geo = vertex[:vertex.rfind('.')] locator = cmds.createNode ('locator') locator = cmds.listRelatives (locator, parent = True)[0] locator = cmds.rename (locator, 'locator_vertexConstrained') #locator = cmds.pickWalk (direction = 'up')[0] cmds.expression (name = locator, string =''' float $BBoxSize = ''' + geo + '''.boundingBoxMinX;\n float $vertexWorldPos[3] = `pointPosition -world ''' + vertex + '''`;\n''' + locator + '''.translateX = $vertexWorldPos[0];\n''' + locator + '''.translateY = $vertexWorldPos[1];\n''' + locator + '''.translateZ = $vertexWorldPos[2];''' )
def createBtnCmd(self, *args): # Creates a function for the radio button group. self.objIndAsCmd = {1:mc.polyCube, 2:mc.polyCone, 3:mc.polyCylinder, 4:mc.polySphere} # Creates the object variable for the create function. objIndex = mc.radioButtonGrp(self.objType, query = True, select = True) # Creates a variable for the new object to be created based on the above array and objIndex variable. newObject = self.objIndAsCmd[objIndex]() # Following section creates necessary variables for the expression. # Creates a variable to select the previously created object. sel = mc.ls(sl=True) # Creates the attribute variable using the user input from the GUI. att = mc.textField(self.attribute, query = True, text = True) # Creates the minimum value variable using the user input from the GUI. minimum = mc.floatField(self.min, query = True, value = True) # Creates the maximum value variable using the user input from the GUI. maximum = mc.floatField(self.max, query = True, value = True) # Creates the time period variable using the user input from the GUI. period = mc.floatField(self.time, query = True, value = True) # Creates the variable for the type of oscillation radio group. oscType = mc.radioButtonGrp(self.oscillate, query = True, select = True) # Creates the speed variable for which the created object will travel at. speed = 6.28/period # Creates the random variable. It is created as 'ran' because random is a pre-defined function in python. ran = (maximum - minimum)/2.0 # Creates the start variable. start = minimum + ran # Creates the expression that will drive the script. # objectName.attributeName = sin(time*speed) * range + start. # Creates the expression for the cos oscillation. expressionTextCos = (sel[0] + "." + str(att) + " = cos(time * " + str(speed) + " ) * " + str(ran) + " + " + str(start) + ";") # Creates the expression for sin expressionTextSin = (sel[0] + "." + str(att) + " = sin(time * " + str(speed) + " ) * " + str(ran) + " + " + str(start) + ";") # Calls the expression. if oscType == 1: mc.expression(string=expressionTextSin) print "ExpressionSin has sucessfully run." elif oscType == 2: mc.expression(string=expressionTextCos) print "ExpressionCos has successfully run." else: print "Expression didn't properly execute."
def createHipsIndicator(trackway): hips, shape = cmds.polyCube(name='hips', width=20, height=20, depth=20) cmds.move(0, 100, 0, hips) references.append(hips) shoulders, shape = cmds.polyCube(name='shoulders_locked', width=15, height=15, depth=15) cmds.move(0, 115, trackway.spineLength, shoulders) cmds.parent(shoulders, hips, absolute=True) pes = trackway.pes cmds.expression("%s.z = 0.5*abs(%s.z - %s.z) + min(%s.z, %s.z)" % ( hips, pes.left, pes.right, pes.left, pes.right)) return hips
def CreateSine(self , tailName , Envelope , Amplitude , Wavelength , WaveFollow , StartingPosition , objList,Axial): objNum = len(objList) averageNum = 1.000/(objNum - 1) expressionStr = '' for x in range(objNum): StartingPosition_PMA01 = mc.shadingNode('plusMinusAverage',asUtility = True,name = tailName + '_' + Axial + '_StartingPosition0' + str(x) + '_PMA01') mc.setAttr(StartingPosition_PMA01 + '.operation',1) mc.setAttr(StartingPosition_PMA01 + '.input2D[0].input2Dx',objNum-1-x) mc.connectAttr(StartingPosition,StartingPosition_PMA01 + '.input2D[1].input2Dx') StartingPosition_SR = mc.shadingNode('setRange',asUtility = True,name = tailName + '_' + Axial + '_StartingPosition0' + str(x) + '_setRange') mc.setAttr(StartingPosition_SR + '.maxX',1) mc.setAttr(StartingPosition_SR + '.oldMaxX',objNum) mc.connectAttr(StartingPosition_PMA01 + '.output2Dx',StartingPosition_SR + '.valueX') StartingPosition_PMA02 = mc.shadingNode('plusMinusAverage',asUtility = True,name = tailName + '_' + Axial + '_StartingPosition0' + str(x) + '_PMA02') mc.setAttr(StartingPosition_PMA02 + '.operation',2) mc.setAttr(StartingPosition_PMA02 + '.input2D[0].input2Dx',1) mc.connectAttr(StartingPosition_SR + '.outValueX',StartingPosition_PMA02 + '.input2D[1].input2Dx') Envelope_MD = mc.shadingNode('multiplyDivide',asUtility = True,name = tailName + '_' + Axial + '_Envelope0' + str(x) + '_MD') mc.connectAttr(Envelope,Envelope_MD + '.input1X') mc.connectAttr(StartingPosition_PMA02 + '.output2Dx',Envelope_MD + '.input2X') Amplitude_MD = mc.shadingNode('multiplyDivide',asUtility = True,name = tailName + '_' + Axial + '_Amplitude0' + str(x) + '_MD') mc.connectAttr(Amplitude,Amplitude_MD + '.input1X') mc.connectAttr(Envelope_MD + '.outputX',Amplitude_MD + '.input2X') result_MD = mc.shadingNode('multiplyDivide',asUtility = True,name = tailName + '_' + Axial + '_result0' + str(x) + '_MD') mc.connectAttr(Amplitude_MD + '.outputX',result_MD + '.input1X') mc.connectAttr(result_MD + '.outputX',objList[x] + '.translate' + Axial) Wavelength_MD = mc.shadingNode('multiplyDivide',asUtility = True,name = tailName + '_' + Axial + '_Wavelength0' + str(x) + '_MD') mc.connectAttr(Wavelength,Wavelength_MD + '.input1.input1X') WavelengthMulriple = averageNum * x mc.setAttr(Wavelength_MD + '.input2X',WavelengthMulriple) WaveFollow_MD = mc.shadingNode('multiplyDivide',asUtility = True,name = tailName + '_' + Axial + '_WaveFollow0' + str(x) + '_MD') mc.connectAttr(WaveFollow,WaveFollow_MD + '.input1.input1X') mc.setAttr(WaveFollow_MD + '.input2X',-1) sine_PMA = mc.shadingNode('plusMinusAverage',asUtility = True,name = tailName + '_' + Axial + '_sine0' + str(x) + '_PMA') mc.connectAttr(Wavelength_MD + '.outputX',sine_PMA + '.input2D[0].input2Dx') mc.connectAttr(WaveFollow_MD + '.outputX',sine_PMA + '.input2D[1].input2Dx') expressionStr01 = result_MD + '.input2X' + ' = ' + 'sin(' + sine_PMA + '.output2Dx);' + '\n' expressionStr = expressionStr + expressionStr01 mc.expression(s = expressionStr,name = 'sine' + '_' + Axial,ae = True,uc = all)
def makeChild(parentObj,makeCon): # DUPLICATE newObj = cmds.duplicate(parentObj,rr=True,ilf=True,rc=True)[0] # PARENT cmds.parent(newObj,parentObj) # CONNECT XFORM ATTRS if makeCon: for attr in attrs: cmds.expression(s = newObj+'.' +attr+ ' = ' + parentObj+'.' +attr) return newObj