Reader small image

You're reading from  Maya Programming with Python Cookbook

Product typeBook
Published inJul 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781785283987
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Adrian Herbez
Adrian Herbez
author image
Adrian Herbez

Adrian Herbez is an accomplished software engineer and educator with a background in virtual worlds and gaming. He has worked as a web developer at Linden Lab (the creators of Second Life) and a senior software engineer at Sony Computer Entertainment, America, where he developed games and interactive content for PlayStation Home. He also served as the lead gameplay engineer for KIXEYE's War Commander. Adrian has also taught at the Academy of Art University in San Francisco in a number of different departments over the years, covering Maya, web development, and game programming. He is currently the cofounder and president of Jamwix, a game and media start-up. So far, Jamwix has released CineMagic: Hollywood Madness, a mobile game for iOS and Android as well as the first feature-length movie for virtual reality (The Banshee Chapter: Oculus Rift Edition). Adrian holds a master's degree in Fine Arts from the University of California, Irvine, from the Arts, Computation, and Engineering department, and has served as a juror for IndieCade, the international festival of independent gaming, for a number of years.
Read more about Adrian Herbez

Right arrow

Chapter 3. Working with Geometry

In this chapter, we'll be looking at ways to create and manipulate geometry with scripting. The following topics will be covered:

  • Working with selected objects and checking node type

  • Accessing geometric data in polygonal models

  • Accessing geometric data in NURBS objects

  • Creating curves

  • Creating new polygonal faces

  • Creating new modifiers (noise)

  • Creating novel primitives (tetrahedron)

Introduction


In this chapter, we'll be looking at how to manipulate geometry within Maya via scripting. First off, we'll look at how to make sure that we have the right kind of object selected. From there, we'll look at how to retrieve information about particular kinds of geometry (both polygonal and NURBS).

We'll also be looking at how to create new geometry (both single faces and entire objects) and how to create per-vertex modifications to existing objects.

Working with selected objects and checking node type


Very often, you will want to make a script that only works on certain kinds of objects and the objects that already exist before the user invokes your script. In this case, you'll want to be able to not only determine what object(s) are currently selected but also to verify that the selected object(s) are of the appropriate type. In this example, we'll be creating a script that will verify that the currently selected object is, in fact, an instance of polygonal geometry and altering the user if it isn't.

How to do it...

Create a new script and add the following code:

import maya.cmds as cmds

def currentSelectionPolygonal(obj):

    shapeNode = cmds.listRelatives(obj, shapes=True)
    nodeType = cmds.nodeType(shapeNode)

    if nodeType == "mesh":
        return True

    return False

def checkSelection():
    selectedObjs = cmds.ls(selection=True)

    if (len(selectedObjs) < 1):
        cmds.error('Please select an object')

    lastSelected...

Accessing geometric data in polygonal models


In this example, we'll be looking at how to get information about polygonal geometry, which will form the basis for more complex scripts.

Getting ready

Create a new scene and make sure that it contains one or more polygonal objects.

How to do it...

Create a new script, name it polyStats.py, and add the following code:

import maya.cmds as cmds

# examine data for a currently-selected polygonal object
def getPolyData():
    selectedObjects = cmds.ls(selection=True)
    obj = selectedObjects[-1]

    vertNum = cmds.polyEvaluate(obj, vertex=True)
    print('Vertex Number: ',vertNum)

    edgeNum = cmds.polyEvaluate(obj, edge=True)
    print('Edge Number: ', edgeNum)

    faceNum = cmds.polyEvaluate(obj, face=True)
    print('Face Number: ',faceNum)

getPolyData()

Running the preceding code will result in information about the currently selected polygonal object being printed.

How it works...

The polyEvaluate command is pretty straightforward and can be used...

Accessing geometric data in NURBS objects


In this example, we'll be looking at how to retrieve information about NURBS surfaces, starting with the number of control vertices (CVs) they contain.

However, the number of CVs in a NURBS object isn't quite as straightforward as the number of vertices in a polygonal object. Although polygonal objects are relatively simple, with their shape determined directly by the position of the vertices, the curvature at any given point of a NURBS object is influenced by multiple points. The exact number of points that influence a given area depends on the degree of the surface.

To see how this works, we'll create a script that will determine the total number of CVs in each direction (U and V) of a NURBS surface, and we'll look at how to select a particular CV.

Getting ready

Make sure that you have a scene containing at least one NURBS surface.

How to do it...

Create a new file, name it getNURBSinfo.py (or similar), and add the following code:

import maya.cmds as...

Creating curves


In this example, we'll be looking at how to create curves with code. This can be used for a number of different purposes, such as forming the basis for further modeling operation or creating custom controls for complex rigs.

We'll actually be making two curves in this example—a simple one that we create directly and a more complex one that we create one point at a time.

Here's what we'll end up with as our output and moving both curves away from the origin.

How to do it...

Create a new file and name it makeCurves.py or similar. Add the following code:

import maya.cmds as cmds
import math

def makeCurve():
    theCurve = cmds.curve(degree=1, p=[(-0.5,-0.5,0),(0.5,- 0.5,0),(0.5,0.5,0), (-0.5,0.5,0), (-0.5, -0.5, 0)])

def curveFunction(i):
    x = math.sin(i)
    y = math.cos(i)
    x = math.pow(x, 3)
    y = math.pow(y, 3)
    return (x,y)

def complexCurve():
    theCurve = cmds.curve(degree=3, p=[(0,0,0)])

    for i in range(0, 32):
        val = (math.pi * 2)/32 * i
      ...

Creating new polygonal faces


In this example, we'll be looking at how to create new polygonal faces with code, both a simple quad and a more complex example that incorporates an internal hole.

How to do it...

Create a new file, name it polyCreate.py (or similar), and add the following code:

import maya.cmds as cmds
import math

def makeFace():

    newFace = cmds.polyCreateFacet(p=[(-1,-1,0),(1,- 1,0),(1,1,0),(-1,1,0)])

def makeFaceWithHole():
    points = []

    # create the inital square
    points.append((-5, -5, 0))
    points.append(( 5, -5, 0))
    points.append(( 5, 5, 0))
    points.append((-5, 5, 0))

    # add empty point to start a hole
    points.append(())

    for i in range(32):
        theta = (math.pi * 2) / 32 * i
        x = math.cos(theta) * 2
        y = math.sin(theta) * 2
        points.append((x, y, 0))

    newFace = cmds.polyCreateFacet(p=points)

makeFace()
makeFaceWithHole()

If you run the preceding script, you'll see two new objects created, both in the XY plane...

Creating new modifiers (noise)


Many 3D modeling and animation packages provide a way to add a bit of random noise to the vertices of an object, but Maya does not. This may seem like an oversight, but it also provides us with a great example project.

In this example, we'll write a script to step through all of the vertices of a polygonal object and move each of them slightly. Here's an example of what a simple polygonal sphere looks like both before and after applying the script that we'll be developing:

How to do it...

Create a new script, name it addNoise.py, and add the following code:

import maya.cmds as cmds
import random

def addNoise(amt):

    selectedObjs = cmds.ls(selection=True)
    obj = selectedObjs[-1]

    shapeNode = cmds.listRelatives(obj, shapes=True)

    if (cmds.nodeType(shapeNode) != 'mesh'):
        cmds.error('Select a mesh')
        return

    numVerts = cmds.polyEvaluate(obj, vertex=True)

    randAmt = [0, 0, 0]
    for i in range(0, numVerts):

        for j in range...

Creating novel primitives (tetrahedron)


In this example, we'll be creating a brand new (to Maya) geometric primitive—a tetrahedron. Tetrahedrons are simple in principle, but would require numerous steps to create using Maya's interface. As such, they make a great candidate for scripting.

We'll be creating a script that will create a tetrahedron of a given edge width as a polygonal mesh.

Getting ready

Before we start writing code, we'll want to make sure that we have a good grasp on the math behind tetrahedrons. A tetrahedron is the simplest regular polyhedron that consists of four faces, each of which is an equilateral triangle.

Each tetrahedron consists of only four points. For convenience, we'll name the three around the base A, B, and C, and the point at the tip D, as in the following illustration:

To make the math easier, we'll set point A to the origin ([0,0,0]). Because every side of the base is of the same length, we can find point B by simply moving along the x axis by the desired edge...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Maya Programming with Python Cookbook
Published in: Jul 2016Publisher: PacktISBN-13: 9781785283987
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Adrian Herbez

Adrian Herbez is an accomplished software engineer and educator with a background in virtual worlds and gaming. He has worked as a web developer at Linden Lab (the creators of Second Life) and a senior software engineer at Sony Computer Entertainment, America, where he developed games and interactive content for PlayStation Home. He also served as the lead gameplay engineer for KIXEYE's War Commander. Adrian has also taught at the Academy of Art University in San Francisco in a number of different departments over the years, covering Maya, web development, and game programming. He is currently the cofounder and president of Jamwix, a game and media start-up. So far, Jamwix has released CineMagic: Hollywood Madness, a mobile game for iOS and Android as well as the first feature-length movie for virtual reality (The Banshee Chapter: Oculus Rift Edition). Adrian holds a master's degree in Fine Arts from the University of California, Irvine, from the Arts, Computation, and Engineering department, and has served as a juror for IndieCade, the international festival of independent gaming, for a number of years.
Read more about Adrian Herbez