38,39 €
Master complex workflows and conquer the world with Python and Maya
This book is for Python developers who have just started scripting with Maya.
Maya is a 3D graphics and animation software, used to develop interactive 3D applications and games with stupendous visual effects. The Maya Programming with Python Cookbook is all about creating fast, powerful automation systems with minimum coding using Maya Python. With the help of insightful and essential recipes, this book will help you improve your modelling skills. Expand your development options and overcome scripting problems encountered whilst developing code in Maya. Right from the beginning, get solutions to complex development concerns faced when implementing as parts of build.
This book is comprised of a set of practical recipes, grouped under specific topics, which can be referred to independently or in sequence. These recipes provide quick solutions to common problems, and cover most of the real-world scenarios that developers are likely to face when working with Maya.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 347
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2016
Production reference: 1260716
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-398-7
www.packtpub.com
Author
Adrian Herbez
Reviewer
Brian Escribano
Acquisition Editor
Subho Gupta
Content Development Editor
Rashmi Suvarna
Technical Editors
Pramod Kumavat
Gaurav Suri
Copy Editor
Dipti Mankame
Project Coordinator
Judie Jose
Proofreader
Safis Editing
Indexer
Hemangini Bari
Graphics
Kirk D'Penha
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
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.
I would like to thank my students for spurring me on to seek out the heart of every topic, and for always inspiring me with their enthusiasm and creativity. I have also been fortunate enough to benefit from a number of wonderful teachers, including Terry Calais, Randy Pausch, and Simon Penny, as well as my longtime friend and mentor, Frank Garvey. I've learned a great deal from each of them, and my life would be much diminished without their guidance and insight.
I'd also like to thank my business partners, Bill Booth and Blair Erickson, for jumping into the deep end with me in starting our company, and for being patient with me on those days when I came into the office bleary-eyed after a long night of writing.
And most of all, I'd like to thank my wonderful partner, Carrie, for being so supportive and for always helping me to go farther and to achieve more in everything I do.
Brian Escribano has over 13 years of experience working in Education, TV, and Games. He builds world class character rigs and animation pipelines for companies such as Nickelodeon, Mirada, Spark Unlimited, and Bioware. With his deep scripting knowledge of Python and MEL, Brian brings a wealth of expertise and experience to any team that he works with.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
This book is a guide to using the Python scripting language to automate tasks in, and build tools for, Maya. The first two chapters provide an overview of Python scripting in Maya and the basics of UI creation. From there, chapters three through seven each cover a different problem domain, in roughly the same order that they are encountered in real-world projects. We start with modeling, moving through texturing, rigging, animation, and rendering. The last three chapters cover topics needed to flesh out scripts into full tool pipelines, including file input and output and communicating with the world outside of Maya via the Web. In the last chapter, we'll cover a few more advanced topics, such as script nodes and script jobs.
Each chapter provides several examples of how to achieve specific tasks in that domain, will full code listing and explanation. Each example stands on its own, and the reader should feel free to move around within the book as needed.
Chapter 1, Getting Started with Maya, covers the basics of using Maya's script editor and getting set up to write scripts of your own. It also covers the differences between Maya Embedded Language (MEL) and Python. The basic parts of Maya's built-in commands are covered, along with the different modes (create, query, and edit) in which they can be invoked.
Chapter 2, Creating User Interfaces, introduces the reader to creating user interfaces for their scripts. It covers creating windows, adding layouts, and filling them with controls. Nested layouts and custom menus are also explained.
Chapter 3, Working with Geometry, covers using Python to work with geometric data. It starts with how to retrieve information about models, both polygonal and NURBS. It also covers creating new curves and new faces, as well as manipulating existing data to deform a model.
Chapter 4, Giving Things a Coat of Paint – UVs and Materials, deals with getting models ready for rendering, both working with UV data as well as creating and applying shading networks.
Chapter 5, Adding Controls – Scripting for Rigging, covers topics related to using scripting for rigging, including how to create bones and edit their properties. It also covers how to create set-driven key relationships and how to set up inverse kinematics (IK).
Chapter 6, Making Things Move – Scripting for Animation, deals with querying and setting keyframe data to create and modify animation. It also covers copying keyframes from one object to another and using code to create custom expressions.
Chapter 7, Scripting for Rendering, covers topics related to actually generating frames. The examples show how to create lights and cameras, and how to render images. It also covers using the Python Imaging Library (PIL) to combine images after they've been rendered.
Chapter 8, Working with File Input/Output, covers the topics needed to build larger toolchains by importing and exporting custom data. Reading and writing both text-based and binary formats is covered.
Chapter 9, Communicating with the Web, covers how to retrieve information from the Web for use in Maya. The parsing of both XML and JSON data is covered, as well as sending POST data to a website.
Chapter 10, Advanced Topics, covers several more advanced topics, including script jobs and script nodes. It also covers how to create a custom context to make scripts that work more like Maya's built-in tools.
To get the most out of this book, you'll need a copy of Maya and a programmer-friendly text editor. There are a great number of text editors out there, and many people have strong opinions on which they prefer. At a minimum, you'll want an editor that saves in plain text and offers the option to display line numbers. You'll also likely want an editor that offers syntax highlighting for Python.
All of the code for this book was written using Sublime Text (https://www.sublimetext.com/), an excellent and low-cost text editor that is great for Python, as well as many other tasks. You don't have to use that though; any text editor that allows you to edit plain text will work just fine.
Almost all of the examples in the book rely on nothing more than Python and Maya, but there is one example that uses PIL. To install PIL, you'll likely want to use PIP, a package manager that makes installing Python packages easy. You can get that at https://pip.pypa.io/en/stable/.
This book is for anyone that wants to use Python to get more out of Maya. It's expected that you have a decent familiarity with Maya's interface and toolset. Knowledge of Python or other programming languages is helpful, but not required.
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Open the script editor by going to Windows | General Editors | Script Editor."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Maya-Programming-with-Python-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/MayaProgrammingwithPythonCookbook_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
This chapter will cover everything you need to get the most out of the rest of the book, as well as give you a feel for the differences between MEL and Python, as follows:
In this chapter, we'll cover the basics of scripting with Maya and Python. If you've been scripting for Maya for a while, a lot of what's covered will likely be familiar. If you're new to Maya scripting, this chapter will get you set up with everything you'll need to know to get the most out of the rest of the book.
The script editor is your primary tool in order to learn about Maya's script-based functionality, as well as a great place to test small snippets of code outside a full script. One of the most useful aspects of the script editor is that it will show you the commands that correspond to the actions that you take within Maya's interface.
This is one of the best ways to learn about the commands involved in your day-to-day Maya tasks. For example, let's use it to find out how to make a polygonal cube with Maya Embedded Language (MEL):
The output that Maya provides is presented as the MEL commands that correspond to the action that you've just taken. That can be a great way to find out which commands you'll need to use in your own scripts. In this case, it's the polyCube command, which will create a polygonal cube. Every command in Maya comes in two flavors—the MEL version and the corresponding Python command.
The script editor shows you commands in MEL syntax, which tends to take the form of:
The MEL syntax borrows a lot from batch scripting wherein it relies on strings of option names (generally referred to as "flags") and corresponding values. The corresponding Python command generally has the following syntax:
As you can see, the MEL and Python versions are fairly similar, but with some key differences:
Another big difference between MEL and Python is how they treat whitespace characters (spaces, tabs, and newlines). MEL, like most languages, doesn't care about whitespace; statements are terminated with semicolons, and blocks of code are defined with matched sets of curly brackets.
Python, however, uses whitespace characters to control program flow. This is often one of the strangest things about Python to people who are new to the language, but not to programming. In Python, blocks of code are defined by indentation. You can use either tabs or spaces, but the key thing is that you're consistent. In Python, every time you increase the number of tabs (or spaces) at the start of a line, it's equivalent to adding an opening curly bracket, and every time you decrease that number, it's equivalent to a closing curly bracket. This can often be confusing, as the structure of your program is defined by characters that may not actually be visible. If you're new to Python and having trouble keeping track of your whitespace, you might want to change your editor settings to display whitespace characters. Most programmer-friendly text editors include such an option, and it can be a big help.
The specific list of options for each command can be found in the built-in Python documentation, accessible from within Maya by going to Help | Python Command Reference. For most commands, you'll find a long list of options.
To make things even more complicated, every option has both a short name and a long name. For example, the polyCube allows you to specify the number of subdivisions along the X axis. You can use either the long name, "subdivisionsX" or the short name, "sx" to set it.
For example, all of the following will result in the creation of a 1x1x1 polygonal cube with five subdivisions along the X-axis.
The MEL versions are:
The Python versions are:
Feel free to use either the short or long version for your arguments. You can also mix and match, using short names for some arguments and long names for others.
In practice, it's generally best to use short names for common arguments (ones that you're likely to remember) and long names for more obscure / more rarely used arguments. Remember that just because your code seems completely sensible to you right now, it may look confusing when you revisit it 6 months (or 6 years!) from now. Make it easy for your future self by using long names (and including comments) when necessary.
You may be wondering why Maya offers two different methods for scripting, MEL and Python. That's a simple case of backwards compatibility. MEL came first and was available in Maya long before Python support was added. Back then, you had to use MEL for day-to-day tasks, and if that couldn't provide you with what you needed, you had to dive into the C++ API (which was quite involved and hard to work with on non-Windows systems). Python unites both approaches, but MEL is still supported to allow older scripts to work. It's also possible that you might get better performance with MEL than with Python, as the Python functionality is a wrapper around MEL. Python is a much nicer language to work with though, so it's generally a worthwhile trade-off.
Note that the script editor doesn't (by default) show you everything that you do. Under normal circumstances, Maya shows you a slightly filtered output based on what you are most likely to be interested in. This is usually a good thing, but there are times when you'll want to disable it. To show all the output, go to the script editor and select History | Echo all Commands. This will cause Maya to output everything to the script editor. This generally means much, much more output than you want, but can sometimes be helpful. In practice, you'll generally want to leave that option off except when you're trying to replicate a given piece of functionality in a script, and the default output isn't giving you any insight into what Maya is doing.
If you have Maya setup to use interactive mode for the creation of primitive shapes, you must have seen the following in the output presented in the Script Editor:
Contexts are an alternative way of getting input from the user, and we'll have more to say about them in Chapter 10, Advanced Topics.
Not only is the Script Editor a great way to see which commands correspond to the actions you take in Maya's UI, but it is also a convenient way to write small bits of code. While you will certainly want to use a text editor to write your scripts, it is still important to be comfortable using the script editor to run small sections of code, either to test it out before inclusion in a larger script or to get more information about the current scene.
Make sure that you have the script editor open and that you've switched to the Python tab in the input (bottom) section.
Type the following into the input section:
Once you've done that, execute it by either pressing the Execute button at the top of the Script Editor or just by pressing Control + Enter.
Your code will disappear from the input section, a new polygon cube will be created, and the results will be pasted into the output ("History") section of the script editor.
To keep your code from disappearing automatically, highlight it first with Command-A (to select everything), then press Command + Enter. This will cause Maya to run just the selected code without clearing out the input section.
Although the polyCube command does the actual work, we have to first import the Maya library for Python before we can use it. To do this, we have to first use import maya.cmds.
The script editor is a great way to try out small snippets of code, but the fact that successful code is deleted can get rather frustrating. For any real script development, you'll want to use a programmer-friendly text editor.
One handy thing about the script editor is that you can save code from the editor to the shelf. To do this, enter some code into the input section, then go to File | Save Script to Shelf... from the Script Editor menu. Maya will ask you to provide a name for the script and then (after a bit of time), a new button will appear in the "Custom" shelf. Pressing that button will execute the corresponding code.
Although most of your scripting work will involve writing separate scripts, it can sometimes be useful to copy-paste commands from the history (top) section of the Script Editor to the input (bottom) section and save it all to the shelf. This is a bit like recording an action in Photoshop and can be a quick and dirty way to create a new shortcut for commonly used functionality.
Maya is a complex tool, and it offers a wide range of functionality, all of it with corresponding commands that can be invoked via scripts. Each command has its own set of arguments, ranging from easily understood to quite cryptic.
When writing scripts for Maya (and as with any other kind of programming), it is vital to be able to find the appropriate documentation and to understand how to make sense of it.
Let's say that we want more information on a specific command, say the command to create a polygonal cube.
One way to view the help for the command is to use Maya's web-based command help, available by going to Help | Python Command Reference from within Maya. From there, you can either click on the "Polygons" subsection or use the search box.
There are a couple of other ways to get to the documentation for a command, though. You can also go directly to the documentation for a command from the Script Editor window. First, execute the corresponding action using Maya's interface, such as invoking the hotbox and choosing Create | Polygon Primitives | Cube.
That will cause the corresponding MEL command to be displayed in the output section of the Script Editor, in this case, "polyCube". From within the script editor, highlight the relevant line, and go to Help | Help on Selected Command. This will bring up a browser window with the documentation for that command. Note that it will default to the MEL version of the command; for the Python version, click on the "Python" link in the top-right corner of the window.
Finally, you can retrieve information about a command via Python directly using the help command. Try running the following:
This will result in a list of the flags available for the given command, as well as the type of value that Maya expects for each, such as:
This means that there is a flag named "sx" or "subdivisionsX" that expects an integer value.
For the most part, you'll want just the Python command reference open in a browser window while you work on developing your scripts. Good reference documents are key to writing good software, and you should get used to just keeping the references close at hand.
You can also use the help command to invoke the web-based documentation for a given command directly, such as:
This would bring up the web page containing the documentation for the Python version of the polyCube command. That's definitely a clunky way to access the help, but might be useful if you wanted to give the users of your script an easy way to refer to relevant documentation directly from your script's user interface.
