New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Programming Concepts for Visual Effects

by: Myrtie Schaefer

Programming Concepts for Visual Effects VSFX 705

Marketplace > Savannah College of Art and Design > Film and Digital Media > VSFX 705 > Programming Concepts for Visual Effects
Myrtie Schaefer

GPA 3.67

Malcolm Kesson

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Malcolm Kesson
Class Notes
25 ?




Popular in Course

Popular in Film and Digital Media

This 21 page Class Notes was uploaded by Myrtie Schaefer on Tuesday October 20, 2015. The Class Notes belongs to VSFX 705 at Savannah College of Art and Design taught by Malcolm Kesson in Fall. Since its upload, it has received 24 views. For similar materials see /class/225347/vsfx-705-savannah-college-of-art-and-design in Film and Digital Media at Savannah College of Art and Design.

Popular in Film and Digital Media


Reviews for Programming Concepts for Visual Effects


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/20/15
when 0 Using Python thev are used m MEL GWEN that the anguaues are SD dwfferent Here are the basms tD getth started thh Pvthnn m Mava Entering Python commands in Maya There are severa wavs cf antenna Pvthnn m Mava Script Editor tabbed Wmduw arE Drucessed bv Pvthnn Fur m are Warm atmn 522 5 m m 2mm Command line and Shelf ether MEL m Pvthnn cummands n u Wan anwnanw HV Mm m askmg WHEther vuur smut s a Pvthnn m MEL scHDt Maya Python module m each 5255er mm Maya and This allows you to use Maya commands For example maya cmds ls maya cmds sphere radius4 You can import Maya commands to a different and shorter namespace import mayacmds as cmd cmd sphere Tip You can import maya cmds automatically in the userSetuppy file You can modify this to use your preferred prefix for example import mayacmd5 a5 mc mc Sphere For more information see Initializing the Maya Environment in and for Python Note Alternatively you can import the Maya commands into the top level namespace using from mayacmd5 import after which you can use a briefer way to reference Maya commands 150 5phere radiu54 WARNING Importing to the top level namespace overrides definitions from Python built in and other modules For example Python has its own help system and a call to the Python version of help produces output that is specific to Python A call to maya cmd5help provides help about Maya commands Importing mayacmd5 into the top level namespace would result in not being able to access Python help Flags named arguments Flags are handled differently in Python than they are in MEL MEL was designed with a shell command style syntax For Maya commands in Python the command argument syntax has been adapted in a way that is natural for Python As a result flags both long and short forms are passed to commands as named arguments The name of the argument is the flag name and the flag s arguments are passed to the named argument Single arguments The MEL sphere command is sphere radius 4 In the Python version the flag radius is referenced as a named argument and since there is a single argument the value is passed as follows mayacmdssphere radius4 Multiple arguments If the flag has multiple arguments then the arguments need to be packed into a list or a tuple Here is an example of a command with a flag that has three arguments with a tuple mayacmdsambientLight rgb 02 03 04 With a list mayacmdsambientLight rgb 02 03 04 Required arguments TrueFalse Named arguments must have a value associated with them However not all Maya flags require a value for example 15 71 In order to maintain a consistent syntax the Autodesk Maya Python implementation requires you to assign a boolean argument to those flags that do not normally take any arguments If the boolean value is False then the flag is ignored if it is True the flag is used For example ass selection fla mayacmds s selectionTrue Selection flag Ls ignored here mayacmdsls selectionFalse Multiple named arguments Some flags may be used multiple times in one command call For example in MEL ls type nurbsSurface type transform In Python you would use the named argument type and pass the values in a list or a tuple mayacmds ls type 39nurbsSurface39 39transform39 In the case where a flag is used multiple times and has multiple arguments the value is a list of lists Tuples may be used instead of lists so you may use a tuple of lists a list of tuples or a tuple of tuples For example the curveonsurface command in MEL curveOnSurface d 3 uv 0 0 uv 03 05 uv 05 06 uv 09 10 sur acel In Python mayacmdscurveOnSurface 39surfacel39 d3 uv00030505060910 If you use more than one argument flag Python returns an error Duplicate keyword argument Ranges There are three types of ranges in Maya commands time index and float All ranges must be specified using tuples in Python Any tuple may have either one or two values A tuple with one value is specified as a value in brackets with a single comma multiple single valued tuples are specified using set notation see Multiple named arguments As well time ranges support units To specify units you must use strings You can mix units as each value is parsed separately These are valid time ranges 1 110 391sec393910sec39 391min2min39 The following table uses the cutKey command as an example of specifying time and index ranges MEL range Meaning Python range time 10pal Cut the key at frame 10 PAL format time3910pal39 time 10sec Cut the keys at time 10 second frame time3910sec39 time 15ntsc 15 in NTSC format and time 20 in 3915ntsc39 20 time 20 the currently defined global time unit time quot1020quot Cut all keys in the range from 10 to 20 time1020 inclusive in the current time unit time quot10quot Cut all keys from time 10 in the current time391039 time unit onwards time quot10quot Cut all keys up to and including time time391039 10 in the current time unit time quotquot Cut all keys time3939 index 0 Cut the first key of each animation index0 curve Indices are O based index 2 Cut the 3rd 6th and 8th keys index257 index 5 index 7 index quot15quot Cut the 2nd 3rd 4th 5th and 6th indexquot15quot keys of each animation curve Changes to certain command flags Certain flag changes to Maya commands are necessary because the arguments for multi use flags in Python must be passed as a list to the flag This causes a problem for commands in which different multi use flags must be mixed and matched Since each multi use flag s arguments are provided in a separate list in Python there is no way to intermix them The few commands which relied on this have been extended so that a single multi use flag handles the job of the individual multi use flags These commands include o polyAppendVertex new append flag which can be used in place of the point vertex and hole flags 0 polyAppend new append flag which can be used in place of the point edge and hole flags 0 polySplit new insertpoint flag which can be used in place of the facepoint and edgepoint flags 0 polyCreateFacet the existing point flag as been modified so that it may be also used to specify holes I roundConstantRadius a new Side flag replaces the use of Sidea and Sideb that are supposed to be intermixed The use of all of these flags is documented in the CommandsPython reference documentation In all cases the flags are backwards compatible All old flags have been left in place Arguments and objects The curveOnSurface example above also illustrates another Python syntax requirement Besides flags Maya commands may also take arguments and objects Arguments are values of a fixed type that are required by a command For example the move command takes three arguments representing the x y and 2 values for the move Objects a l e the entities upon which a command operates for example an object in a scene or a U1 element There can be a variable number of objects for a command and sometimes they are implicit based on the current selection list Objects and arguments are passed to commands as they would be in MEL but they must be passed in the following order command arguments object flagsnamed arguments This is different from MEL where the ordering requires that objects appear at the end of the argument list However Python requires that named arguments come after all other arguments Summary of argument types The following table shows a summary of the flag named argument types you can use in the Maya Python module Flag type Example Comment plain flag MEL Flags with no ls selection arguments get a boolean TrueFalse P tho Y 1 switch mayacmdss selectionTrue flag with single MEL argument sphere radius 10 Python mayacmdssphere radius10 flag with multiple MEL use a tuple to arguments ambientLight rgb 02 03 04 Python mayacmdsambientLight rgb 02 03 04 specify multiple arguments multi use flags MEL ls type nurbsSurface type transform Python mayacmdsls type39nurbsSphere3939transform39 Use a list to hold the multiple flag values multi use flags with multiple arguments MEL curveOnSurface d 3 uv 0 0 uv 03 05 uv 05 06 surfacel Python mayacmdscurveOnSurface 39surfacel39 degree uv0003050506 Use list of tuples You can also use a tuple or tuples a list of lists or a tuple of lists command MEL The same as MEL arguments move 20 10 10 except arguments must come first Python mayacmdsmove 20 10 10 command MEL arguments with flags move objectSpace 20 10 10 Python mayacmdsmove 20 10 10 objectSpaceTrue command objects MEL select nurbsSpherel Python mayacmdsselect 39nurbsSpherel39 Same as MEL command objects with arguments and flags MEL move objectSpace 20 10 10 nurbsSpherel Python mayacmdsmove 20 10 10 Objects must come before flags hurhsSpherer DbJEEtSDaceTruE query Were a MEL agargument skwnc uster nu rmfr takes a Mame Querv ag ream res a human True Pvmun maVa Emds skmC ustEr uTrue WTru2 query Were a MEL agargument dues skmC ustEr w Jmnt nu 7dr ndt take a Mame amt Pvmun skmC ustEr mam m drTruE Standard Input stdln implementation v e M n1 M r h h bv reemrrg rrarh Syssdn Dr aner tangnpu Men Mava rs ruhhmg m cu made as mama bnx WHErE vnu can WEE vnur mDut x M H abject vuu can de se by referencmg sys7scdn7 MEL Python communication h MF upyeha pychan cummand attempts tn canvert the resmt mm a MEL type them may pmnm mm was pmnm Nate rrhpesed bv Pvthun r h hewte herrme Fur the rest rt requests a strmg representetmh er the Dblect and returhsthet Thefn mwmuteb e shews the curreer suppnrted rheumhgs Python Return Value MEL Conversion string string unicode string int int float float list containing numbers including at least one float float list containing only integers or longs int list containing a non number string anything else string Calling MEL from Python To call MEL from Python use the maya meleval function It can do a better job of conversion than the MEL python command since Python has more flexible type support You must import the mayamel module to use this command that is import mayamel as mm mm eval polySphere quot Here is a table of the supported conversions MEL Return Python Conversion Value string string int int float float vector 3 tuple of values matrix list of lists where each sub list in the list contains one row of the matrix string list of strings int list of ints float list of floats vector list of 3 tuples Positional arguments Positional arguments refer to the arguments that UI elements pass to their callback scripts For example the callback MEL script for a float slider control could contain 1 The value of the float slider is substituted for this positional argument when the callback is run For Python two different ways of substituting values from controls in callbacks are supported If the callback is a string which is to be evaluated then Maya does string substitution as in MEL However Python s format operator is used to do the substitutions The format operation is passed a dictionary of items for the substitution where the names of the values are 1 2 and so on For example maya cmds floatslider ccquot print 39 1 s 39 quot The dictionary is applied to the string later before it is executed The floatSlider command formats the string with the current slider value before executing the script You provide the format string and the UI element provides the dictionary for the format operation The second style of Python callback uses a compiled function where Maya passes the values as arguments to the function def doPrint arg print arg cmdsfloatslider ccdoPrint With callback functions you get an error message if your callback does not take the correct number of arguments def badstuf39 rlnt quotbadquot cmdsfloatslider ccbadstuff When you move the slider you see this error TypeError badstuf takes no arguments 1 given If you want to create a callback that works with any number of arguments use a variable argument list def genericcallback args print quotargs quot str args cmds button commandgenericcallback ADI Gulde 0 Uslng the Maya Python API the Mava ADI l e h SEHUCS slung Wlth standalnrle scrlms As thls ls a Pvthnn based ADI knnwledge Bf Pvthnn ls rEuulred Importing modules m l pace the fullnwlnu them mayaDPemvtaya Help on a module or class Fur example lf vuu Wlsh tn dlsulav the class Manhatth fur meccax use help lmaya Dpen aya velraxl lt l5 alsu Dusslbletu dlsulav the Manhatth cf ah EntlrE mudule helplmayaup nu yal Thls uperanurl WlH take a whlle tn return slhee the ODEHMava mudule l5 verv large 9 Scripts uraarahhhe tn slurllfv melr assnclatlnrl Classes lnclude m a la l u MIK l MFhNurhscurvecv Dr lteratwelv an all the CVs Bf a curve MPx p create vuur awn DbJELttVDEs M classes Most although not all of these classes are Wrappers Examples of this class are MVector MIntArray and so forth We can use wrapper and function set classes to write scripts such as the following import mayaOpenMaya vectorl ve aya OpenMayaMVector002 newVector vec 1 ve ector3 print quotDevVector f f f quot Q5 newVectorx newVectory DevVector 2 It is possible to shorten the symbol names used by modifying the import command import maya OpenMaya as OpenMaya vectorl OpenMaya MVector 0 1 0 Scripts can access dependency graph information using the Maya Python API classes The following is a script that finds the persp node and prints out its translatex attribute value import the OpenMaya module import mayaOpenMaya as OpenMa a function that returns a node object given a name def nameToNode name selectionList OpenMayaMSelectionList selectionListadd name selectionListgetDependNode 0 node return no e function that finds a lug given a node object and plug name def nameToNodePlug attrName nodeObject FnDependencyNode nodeObject attrObject de Nodanattribute attrName plug OpenMayaMPlug nodeObject attrObject eturn l g Find the persp camera node rint quotFind the persp cameraquot perspNo e nameToNo e quotperspquot print quotAPItype dquot perspNodeapiType print quotAPItype string squot perspNodeapiTypeStr Pr39 t the translateX value translate ug nameToNodePlug quottranslateXquot perspNode print quotPlug name squot translatePlugname print quotPlug value gquot translatePlugasDouble n m n to Hi 1 I 39u m 1 3 m k m 3 The example above demonstrates the following a To instantiate a class use the fn OpenMayaMFnFunctionSet notation 0 MObjects can be created using node OpenMayaMObject 0 Although Python is a typeless language you must instantiate the correct type in order to pass it as a parameter of the class 0 Python strings are passed and returned in place of the MString wrapper class Note For the sake of clarity the example above has omitted error checking Scripted plugins Scripted plug ins allow a developer to create a solution that is tightly coupled with Maya Scripted plug ins allow a developer to support functionality such as the undoing of commands and the building of appropriate requires lines into the Maya scene file Another advantage of using a scripted plug in is that its functionality is available in both MEL and Python Using a scripted plugrin P UQEWS iDlua nan uInn39rlnlAmn AansmIMmhaw quotteam ma rum y mm m M the smuted ameth ane A thnuuh t S passmxeta have a HUN sc nted emeth py sehpt ah the mmiuueimgm these tEmS Mu hatmau Wammgs Wm be ssued that ertrv pmhts EannDt be fuund The Mugth an ether be Leaded fmm the P uusm Manager Dr fmm the MEL Dr Pvtheh cummand tabs 1h MEL use the laadPlugan EDmmand 1h Pvtheh use the mayaamaa1aaamuemu EDmmand Emter tab upon miya me was prellxl x Invukmu tth Pvthun sehpt dues the annwmg xmuert the Mava mudme se that the sums mudme became ava ab e make the cusmm cummand spaenxu Nntes The sp WEN 5 used fur sc pted D ug39mquot Smarted pmer hs must be human usme the DadP uum cummand It Cannd be human bv mm the snurce cf a sehcrted Mueth Thws Mugth eah a sn be un uaded usme the Pvthun cummand mayaamaamxaaamugam henxmapy39w The mad and Execute StEDs eah a sn be nvnked thE MEL emter usme loadPlugin helimed py spHelix Writing a scripted plugin Writing a scripted plug in requires the definition of some specialized functions within the plug in The scripted plug in must 0 Define initializePlugin and uninitializePlugin entry points 0 Register and unregister the proxy class within these entry points a Implement creator and initialize methods as required which Maya calls to build the proxy class 0 Implement the required functionality of the proxy class This requires importing the necessary modules The following sections describe these pieces in more detail with examples Importing Python uses the import keyword to include functionality from a module into a script For example import mayaOpenMaya as OpenMaya import maya0penMayaMPx as OpenMayaMPx import sys It is possible for a scripted plug in to be split among several files The import command is used to load the functionality of the secondary file into the scripted plug in import polyModifier Any secondary scripts must be located in the same directory as the scripted plug in Scripted plugin initialization When a scripted plug in is loaded Maya searches for an initializePlugin function in its definition Within this function all proxy nodes are registered Initialize the script plug in def initializePluginmobject mplugin OpenMayaMPxMFnPluginmobject try mn39lnn39in 39 km except sysstderrwrite quotFailed to register command snquot kPluginCmdName raise If the initializePlugin function is not found the scripted plug in fails to load In addition during the load Maya searches for an uninitializePlugin function If this is not found then the scripted plug in fails to load Scripted plugin uninitialization When Maya is attempting to unload the plug in the previously found uninitializePlugin function is called to unload the resources of the plug in def uninitializePluginmobject mplugin OpenMayaMPxMFnPluginmobject try mpluginderegisterCommand kPluginCmdName except sysstderrwrite quotFailed to unregister command snquot kPluginCmdName raise Creator functions Creator functions are used to return a derived version of a proxy class to Maya Virtual methods are implemented on the derived class which are called from Maya An example of a class definition and a creator function is class 139 5 def cdereator turn MDVDtr 39 It is very important to call the OpenMayaMPx asMPthr on the newly created proxy object This call transfers ownership of the object from Python to Maya Program errors will occur if you do not make this call since Python can unreference this object and destroy it This will leave a dangling pointer in Maya Class implementation Implementing a proxy class requires deriving from the Maya Python API object class 139 5 def finiti self Op n ayaMPxMPxCommandiiniti self def doItselfargList int quotHello Worldquot The scriptedCommand class is derived from OpenMayaMPxMPxCommand The constructor or finiti method must call the parent class iinitf method All class methods require self as the first parameter followed by the normal argument list This command s doIt method simply prints out Hello World Initialization Functions Initialization functions are used within scripted plug ins that define new proxy nodes using the MPxNode class The following is an example that demonstrates how to create a simple scripted plug in node the output of which is the sine function import math y import mayaO enMaya as OpenMaya import maya0penMayaMPx as OpenMayaMPx kPluginNodeTypeName quots SineNodequot sineNodeId OpenMayaMTypeId0x8700 Node definition c ass sineNodeOpenMayaMPxMPxNode class variables input penMayaMObject output OpenMayaMObject def finiti self OpenMayaMPxMPxNodeiinitiself def compute selfplugdataBlock if plug 39neNodeoutput dataHandle dataBlockinputValue sineNodeinput inputFloat dataHandleasFloat esult mathsin inputFloat outputHandle dataBlockoutputValue sineNodeoutput outputHandlesetFloat result dataBlocksetClean plug creator def nodeCreator eturn OpenMayaMPxasMPthr sineNode initializer def nodeInitializer in ut nAttr OpenMayaMFnNumericAttribute sineNodeinput nAttrcreate quotinpu quot quotinquot OpenMayaMFnNumericDatakFloat 00 nAttr setstorable 1 output nAttr OpenMayaMFnNumericAttribute sineNodeoutput nAttrcreate quotoutputquot quotoutquot OpenMayaMFnNumericDatakFloat 00 sineNodeaddAttribute sineNodeinput sineNodeaddAttribute sineNodeout ut sineNodeattributeAffects sineNodeinput sineNodeoutput initialize the script plug in def initializePluginmobject mplugin OpenMayaMPxMFnPluginmobject try mn39lnn39in 39 kP39lnni nodeInitializer except sysstderrwrite quotFailed to register node squot kPluginNodeTypeName raise uninitialize the script plug in def uninitializePluginmobject 39n OpenMayaMPxMFnPluginmobject mpluginderegisterNode sineNodeId except sysstderrwrite quotFailed to register node squot kPluginNodeTypeName raise The nodelnitializer function is passed to registerNode in the initializePlugin function As the plug in loads Maya calls the nodelnitializer function to create the attributes of the node Error Conditions The Maya Python API uses Python exceptions for querying and setting error states in script In most cases exceptions are used even though the class documentation indicates that a method has a return value There are many situations where an exception can occur 1 A call fails and the failure state needs to be preserved def uninitializePluginmobject mplugin OpenMayaMPxMFnPluginmobject y mpluginderegisterNode sineNodeId except sysstderrwrite quotFailed to deregister node squot kPluginNodeTypeName raise In this example if the deregisterNode call failed the uninitializePlugin call passes the exception back to Maya and the plug in fails to unload 2 A call fails and the failure state needs to be cleared This code can be modified to catch the error and still allow the plug in to unload if the deregisterNode call fails def uninitializePluginmobject lugin OpenMayaMPxMFnPluginmobject mpluginderegisterNode sineNodeId except sysstderrwrite quotFailed to deregister node squot kPluginNodeTypeName pass The only change being that the raise keyword has been changed to pass This technique is useful for writing iterator code that may fail if incorrect objects are being examined 3 Unknown parameter return value In the Maya Python API an unknown parameter return value is used to indicate that a method cannot handle a specific case and it is up to the caller to take care of the operation One such method is MPxNode compute 0 In this situation the Python code would return Ope aya kUnknownParameter Classes support slicing All Of the number arrays MIntArray MUintArray MUint64Array MFloatArray and MDoubleArray support Python style slicing For example import mayaOpenMaya as OpenMaya array penMayaMU1ntArray for 1 1n range09 arrayappend 1 array282 Result2 4 6 Accessing static MObjects of an MPx class The proxy classes provide some standard information to a developer about the node that is being used This includes attribute objects that are used to define the node To access a static class MObject in the Maya Python API similar code can be used e nve lo pe Ope nMayaMPx cvar MPxDe formerNodeienvelo pe After making this call the envelope will be an MObject for MPxDeformerNode envelope Messages Message classes are supported in the Maya Python API A Python function is passed for the callback This function must have the exact number of parameters required by the callback message If it does not an exception will occur when the message is invoked and information will be written to the console Client data in the form of a python object can also be passed with most messages The following is an example of a message Message callback def dagParentAddedCallback child parent clientData 39 quotdagParentAddedCallback quot print quottchild squot childfullPathName print quottparent squot parentfu lPathName print quottclient data squot clientData Create the mesage def createParentAddedCallbackstringData try i a 39l 39lhar39kl dagParentAddedCallback stringData except s s stderr writ e quotFailed to install dag parent added callbacknquot messageIdSet False else messageIdSet True eturn id Call the message creator messageId createParentAddedCallback quotinoDataiquot Modify Parameter Values Instead of Using an Assignment In Python it is best to modify a parameter rather than using an assignment The code below contains an assignment and demonstrates how an error can occur import mayaOpenMaya as OpenMaya def vectorTestv lv OpenMayaMVector159 v rint quotg g gquot vxvyvz v O enMayaMVector vectorTestv print quotg g gquot vxvyvz The second print command will emit all zeroes In Python either modify the parameter value or write the code so that a new value is returned Rewrite the vectorTest function as follows def vectorTestv lv OpenMayaMVector159 vx x vy lvy v2 lvz print quotg g gquot vxvyvz References to Basic Types The Maya Python API contains many calls in which return values or parameters are references to basic types such as intamp charamp floatamp etc In the Maya Python API all references are treated as pointers As a result special calls are required to create set and access the values of these items A utility class called MScrithtil that exists in the OpenMayapy module is used to create get and set values of these types Commands with Arguments Commands with arguments must use the MSyntax and MArgParser classes within a scripted MPxCommand See the following code for an example import mayaOpenMaya as OpenMa ya import mayaOpenMayaMPx as OpenMayaMPx import s math kPitchLongFlag kRadiusFla 39 kRadiusLongFlag quot radiusquot enMayaMPx MPxCommand iiniti self def iinit self def doItself args deg ncvs 2 spans ncvs deg nknots spans2deg 1 radius 0 Parse the argume s argData Ope MayaMArgDatabaseselfsyntaxI args if argDataisFlagSetkPitchFlag p39tch g ata lagArgumentDoublekPitchFlag 0 if argDataisFlagSetkRadiusF 39 rad argDataflagArgumentDoublekRadiusFlag controlVertices 0 OpenMayaMPointArray OnanMava Set up cvs and knots for the helix for i in range0 ncvs controlVerticesappend O itch 39 dius ts penMayaMPoint radius mathcosi n knotSequencesappend i mathsini for i in range0 Now create the curve curvan OpenMayaMFnNurbsCurve nullObj OpenMayaMObject try This plugin normally creates the curve by passing in the cv39s unction to create curves by passing i he ep39 has been added et this to False to get that behaviour if True curvancreate controlVertices knotSequences deg OpenMaya MFnNurbsCurve kOpen O O nullObj else curvan createWithEditPoints co ntrolVertices 3 OpenMayaMFnNurbsCurvekOpen False False False except sysstderrwrite quotError creating curvenquot aise Cre tor def cdereator Create the command return MDVDtr 39 Syntax creator def syntaxCreator s x OpenMayaMSyntax syntaxaddFlagkPitchFlag kPitchLongFlag OpenMayaMSyntaxkDouble x1n v rum nllID Mn 11 in in 39 v w n openMayaMsyntaxkpouble return syntax Initialize the scri t plug in def initializePluginmobject mplugin OpenMayaMPxMFnPluginmobject quotAutodeskquot quot10quot quotAnyquot y mn39lnn39in 39 km 39 1 except sysstderrwrite quotFailed to register command snquot kPluginCmdName Uninitialize the scri t plug in def uninitializePluginmobject mplugin OpenMayaMPxMFnPluginmobject try mpluginderegisterCommand kPluginCmdName except sysstderrwrite quotFailed to unregister command snquot kPluginCmdName raise This example includes the syntax creator function along with parsing operations in the 101 method of the class Protected methods The Maya Python API contains several methods that should only be called from the class the method belongs to We follow the Python designation of using an 7 as the first letter of the method name to indicate that protection applies to this method Several examples of these methods exist in the MPxNode class iforceCache isetMPSafe Please respect the method usage requirements of protected methods in the Maya Python API Need self but only API object is available When implementing a proxy class in Python it is natural to define methods within the Python class for handling the getting and setting of state For example you wish to maintain a vector as a class variable Within the Maya Python API there are methods that are creators of classes that can exist outside of the class Often these methods return a pointer value In the Maya Python API these pointer values are not the same as the self of a Python class As a result there is no straight forward way to access the class variables defined on self A workaround using a dictionary and a special function OpenMayaMPxa5Ha5hable makes this possible Follow these steps 1 Declare a dictionary object kTrackingDictionary 2 In the initialization method of the object of interest use the OpenMayaMPxa5Ha5hable method to store self in the dictionary def iinit self OpenMayaMPx MPxToolCommand iiniti self selfsetCommandStringkPluginCmdName selfidelta OpenMayaMVector k39r39rarki 39 L39 self self 3 Retrieve self from the dictionary using the pointer Code is in a different class Pointer is returned neowd self7newToolCommand Use pointer to get to self of the command self cmd 39 39 39 1get 3939 L 1 neowd None Setithe class variable selficmdsetVector0 0 00 0 0 4 Clean up the tracking dictionary def del f i sel del k39T rar39ki n39 L39 self For examples that demonstrate these principles see the Development Kit Operating System Types There are some methods in the Maya Python API that require ltiosteamgt operating system types As these are not included in Python a MStreamUtils class is available for creating and using these type of objects Please check the Development kit for examples on how to use this class Calling into the Parent class Often when writing an MPx proxy class the scripts will require calling into the parent class This is done using notation such as the following matrix OpenMayaMPxMPxTransformationMatrixa5Matrix5elf Enum values Enum values are accessed using a moduleNameclassNamevaue notation such as OpenMayaMSyntaxkDouble Using OpenGL We have provided a wrapper class MGLFunctionTable for using OpenGL functionality in script on all of our support platforms To acquire a reference to this class use the following code glRenderer glFT glRendererglFunctionTable Standalone Scripts It is possible to write standalone scripts that make use of the wrapper classes and function sets to modify the Maya model These scripts are run from the command line A simple hello world standalone script follows import mayastandalone import mayaOpenMaya as OpenMaya import sys def main argv None try mayastandaloneinitialize name39python39 except sysstderrwrite quotFailed in initialize standalone applicationquot raise sysstderrwr1te quotHello worldl script outputnquot OpenMayaMGlobal executeCommand quotprint quotHello worldl command script outputnquotquot 1f name quotiimalniquot irinaln After the standalone is initialized function sets and wrapper classes can be used to create and modify a Maya model This script must be run using the Python executable that is supplied with Maya For example MAYA7LOCATIONbinmayapy helloWorldpy


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Kyle Maynard Purdue

"When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the I made $280 on my first study guide!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.