Category Archives: Scripting (Mel/Python)

linkedChainPreview

Autogenerate Chainlinks Along Curve

Well modeling chains can be tedious, so here we go, a small script that creates a chained link for a provided curve

'''
Linked Chain

Creates a Torus like object, links them together as linked Chain and positions the chain along a curve

Example:
1. Select a curve in Maya
2. Execute command:

Poly_Linked_Chain(radius = 1, sectionradius =0.1, extrude = 1, variation = 20, name="chain").createChainForSelectedCurve()

Created on May 7, 2013

@author: Neal Buerger www.nealbuerger.com
'''
import pymel.core as pm
import random

class Poly_Linked_Chain:
    
    def __init__(self, **kwargs):
        """
        Accepts following Keywords:
        radius: of the Torus created (Default 1)
        sectionradius: of the Torus (Default 0.1)
        extrude: length of the torus extrusion (Default 0)
        variation: along the rotation of the linked elements (Default 0)
        name: name of the chain (Default chain)
        """
        
        self.radius = kwargs.get("radius" ,1)
        self.sectionradius = kwargs.get("sectionradius" ,0.1)
        self.extrude = kwargs.get("extrude" ,0)
        self.variation = kwargs.get("variation" ,0)
        if self.variation < 0:
            self.variation = abs(self.variation)
        if  self.variation > 45:
            self.variation = 45
        
        self.name = kwargs.get("name" , "chain")
        self.name = self.name + str(len(pm.ls(regex= "%s\d*" % self.name))+1)
        
  
   
    def createLink(self):
        """
        creates a Torus and extrudes half of it
        To be used as alternative to a provided geometry
        
        """
        basechain = pm.polyTorus(radius = self.radius, sr = self.sectionradius, tw= 0, sx = 20, sy = 20, ax = (0,1,0), ch = 1)[0]    
        if self.extrude is not 0:
            faces = []
            for j in basechain.vtx:
                if j.getPosition()[0] > 0:
                    faces.append(j.connectedFaces())
            pm.polyExtrudeFacet(faces, translateX=self.extrude)
        return basechain
        
    
    def makeChain(self, obj, linklenght, chainlenght, preserveObj = False):
        """
        Uses provided geometry to create a straight chain
        
        obj: object to be used for the chain
        linklenght: lenght of the obj
        chainlenght: number of links that are created
        """
        if preserveObj:
            obj = pm.duplicate(obj, un=True)[0]
        pm.move(obj, 0,0,0)
        chain = [obj]
            
        rotValue = 0
        for i in range(1, chainlenght):
            obj = pm.duplicate(chain[0])[0]
            rotValue += 90 + random.randint(-self.variation, self.variation)
            if rotValue >= 360:
                rotValue -= 360
            pm.rotate(obj, [rotValue, 0, 0])        
            distance = linklenght * i
            pm.move(obj, distance,0,0)
            chain.append(obj)
        return chain
    
    def rigChain(self, chain):
        """
        takes chain and adds joints and a smooth bind to rig it
        
        chain: list of objects 
        """
        pm.select(deselect = True)
        jnts = []
        for obj in chain:
            pos = obj.translateX.get(), obj.translateY.get(), obj.translateZ.get()
            jnt =  pm.joint(p = pos)
            jnts.append(jnt)
            pm.rename(jnt, self.name + "_joint%d" % len(jnts))
        linked = pm.polyUnite(chain, ch = 0)[0]
        self.name = pm.rename(linked, self.name)
        pm.skinCluster(linked, jnts[0])
        return jnts
    
    def addClusterHandles(self, crv):
        """
        Adds Cluster Handles to Curve for every cv
        """
        for i in crv.cv:
            pm.parent(pm.cluster(i), crv)
    
    def createChainForCurve(self, crv, obj = None, linklenght = 1):
        """
        Uses the Curve and creates a chain based on the object that is passed into the function
        
        crv = curve to be used
        obj = object to be used
        linklength = lenght of the obj
        """
                
        if obj is None:
            obj = self.createLink()
            linklenght = (2*(self.radius - self.sectionradius*2)+self.extrude)
        chainlenght = int(pm.PyNode(crv).length()/linklenght)
        chain = self.makeChain(obj = obj, linklenght = linklenght, chainlenght = chainlenght)
        jnts = self.rigChain(chain)
        
        ik = pm.ikHandle( startJoint=jnts[0], endEffector=jnts[-1], solver='ikSplineSolver', createCurve=False, curve=crv)[0]
        pm.rename(ik, self.name + "_ikHandle")
            
        ctrlgrp = pm.group(jnts[0], ik, n = "%sctrl_grp" % self.name)
        ctrlgrp.v.set(False)
        pm.group(crv, self.name, ctrlgrp, n = "%s_grp" % self.name)
        
        self.addClusterHandles(crv)
        pm.select(deselect = True)
        
        return self.name
    
    
    def createChainForSelectedCurve(self):
        """
        Creates Chains for selected curves
        """
        return [self.createChainForCurve(i) for i in pm.ls(sl =True, tr=True) if pm.nodeType(i.getShape()) == "nurbsCurve"]
        
    
    def deleteRig(self, name):
        """
        Removes Rig from geometry
        
        name: name of geometry
        """
        parent = pm.PyNode(name).getParent()
        pm.delete(name, ch = True)
        pm.parent(name, w = True)
        pm.delete(parent)
        
        
BevelHardEdges

Polygon Bevel Hard Edges Script

When working with polygons, it is helpful to bevel all hard edges to have a non-CG look.

This basic script bevels the hard edges on all selected objects.

import pymel.core as pm

def obj_is_poly(obj):
    #Evaluates if Object is Polygon
    return pm.nodeType(obj) is "mesh"

def bevelHardEdges(obj, offset = 0.5, segments = 1):
    if obj_is_poly(obj):
        pm.select(obj)
        pm.polySelectConstraint( m=3, t=0x8000, sm=1 ) # to get hard edges
        pm.polyBevel(offset = offset, segments = segments,autoFit = True, offsetAsFraction = True, fillNgons = True)

def bevelHardEdgesOnSelected():
    for item in pm.selected():
        bevelHardEdges(item.getShape())

bevelHardEdgesOnSelected()
ao_exclude

Snippets: Ambient Occlusion exclude Objects

While using mia_amb_occlusion strange effects can happen when rendering transparent objects. (left glass with AO, right glass eliminated from AO)

To eliminate this effect from an object an extra attribute named  “MI Label “. This short snippet adds the attribute to the selected objects and sets it to the value of 5.

import pymel.core as pm

selection = pm.ls( selection=True )
for item in selection :
   pm.addAttr(item, ln="miLabel", at="short", dv=5)

In the mia_amb_occlusion node the attribute  “Id Inclexcl” must be set to -5 (or negatate the value you set for the MI Label).

Screenshot - 8_28_2012 , 2_55_19 PM

Maya 2013 python: Batch File Converter 0.1

Here is a batch file converter from various formats to mayaAscii or mayaBinary

*Bonus Tools Required: http://www.the-area.com/bonus_tools

Running the script

  1. Download the Script from here
  2. Extract to your User\Documents\Maya\scripts directory
  3. Start Maya, open the script editor and type or copy the following text into the Python window:
    import BatchConverter
    BatchConverter.BatchConverter()
    
  4. Use the “Execute All” button in the script editor OR make a shelf button by selecting the text in the Python window and going to File -> Save Script to Shelf

Jeremy Ernst: Building Maya Interfaces with Python

Jeremy Ernst has created a very good introduction series to Maya UI creation with Python on vimeo:

Video 1:https://vimeo.com/42848594
Video 2:https://vimeo.com/43167571
Video 3: https://vimeo.com/43948657
Video 4: https://vimeo.com/44707576
Video 5:https://vimeo.com/45590131
Video 6: https://vimeo.com/45980607
Video 7: https://vimeo.com/46452342

Eclipse as Python Editor for Maya 2013

Under Resources is the original tutorial, this is a shorter compact Version

 Downloads

Programs:

http://www.eclipse.org

Pydev:

In Eclipse install using Help > Install New Software add new Site.

http://pydev.org/updates

Eclipse – Maya Plugin:

http://www.creativecrash.com/maya/downloads/applications/c/eclipse-maya-editor

Extract to any folder

Install via Help > Install New Software . Click on “Add” and then “Local” and navigate to the directory

Eclipse Configuration

Python Interpreter

  1. Under Window > Preferences – configure “Interpreter- Python”:
  2. Click on “New and select as Interpreter “C:\Program Files\Autodesk\Maya2013\bin\mayapy.exe”
  3. Include all folders

Autocomplete

  1.  In the same window
  2. Open the tab called “Predefined”
  3. Click on “New” and navigate  to C:\Program Files\Autodesk\Maya2013\devkit\other\pymel\extras\completion\pypredef (or whatever directory with the proper .pypredef files)
  4. Click “Apply”

 Maya Confguration

In Maya, create a new shelf button with the following code

import maya.cmds as cmds
if cmds.commandPort(':7720', q=True) !=1:
     cmds.commandPort(n=':7720', eo = False, nr = True)

Alternative in the folder:

Users\Username\Documents\maya\2013-x64\scripts

Create the a text file with the code userSetup.py

Conclusion

You can now use Eclipse and  with Strg-Enter send the code to Maya

In addition by clicking the “Connect to Maya” button (strg + ]) you can see all consoleoutput directly in Eclipse.

Resources:

http://www.creativecrash.com/tutorials/using-eclipse-as-a-maya-ide