Utils

Application

saveCurrentScene()

Save current scene

Checks if the file has already been saved. Returns “save”, “discard” or “cancel”.

If not saved opens “save”, “discard” or “cancel” window. Returns the button pressed if “discard” or “cancel”

If “save” is clicked it will try to save the current file, if cancelled will return “cancel”

Returns:

The button clicked returned as a lower case string “save”, “discard” or “cancel”

Return type:

str

restartMaya(force=False, delay=3)

Restarts maya with the same environment.

Add delay in case maya takes a while to close and save.

Returns:

Env

getMayaLocation(mayaVersion)

Gets the generic maya location where maya is installed

Parameters:

mayaVersion (int) – The version of maya to find

Returns:

The folder path to the maya install folder

Return type:

str

mayaScriptPaths()

Returns a list of maya script paths, received from the MAYA_SCRIPT_PATH environment

Return type:

list(str)

mayaModulePaths()

Returns a list of maya module paths, received from the MAYA_MODULE_PATH environment

Return type:

list(str)

mayaPluginPaths()

Returns a list of maya plugin paths, received from the MAYA_PLUG_IN_PATH environment

Return type:

list(str)

pythonPath()

Return a list of paths, received from the PYTHONPATH evironment

Returns:

a list of paths

Return type:

list(str)

mayaIconPath()

Returns the xbmlangpath environment as a list of path

Return type:

list(str)

getEnvironment()

Gets maya main environment variable and returns as a dict

Returns:

dict

printEnvironment()

logs the maya environment to the logger

mayapy(mayaVersion)

Returns the location of the mayapy exe path from the mayaversion

Parameters:

mayaVersion (int) – the maya version the workwith

Returns:

the mayapy exe file path

Return type:

str

isMayapy()

Returns True if the current executable is mayapy

Returns:

bool

isMayaBatch()
isInteractive()
mayaVersion()

Returns maya’s currently active maya version ie. 2016

Returns:

maya version as an int with no updates (decimals) ie. 2016

Return type:

int

apiVersion()

Returns maya’s currently active maya api version ie. 201610 as an int

Returns:

Maya api version as an int ie. 201610

Return type:

int

mayaVersionNiceName()

Returns maya’s currently active version and api (update) as a str for users ie. “2016.1”

Uses two strings to create the version number including the update (API version) as a float:

“2016” and “20160100” = 2016.1

Accounts up to update 29 eg “2016.29”

Returns:

Maya api version in nice name form ie. 2016.1 that can be converted to float

Return type:

str

globalWidthHeight()

Returns the Scene global render width and height

Returns:

The width and height values returns from the “defaultResolution” node

Return type:

tuple(int, int)

Fbx

Utilities for handling FBX related operations

availableFbxVersions(ignoreBeforeVersion=None)

Returns the current available fbx versions in the form of [(“FBX202000”, “FBX 2020”)].

Parameters:

ignoreBeforeVersion (str) – If provided then any version before the specified will be ignore ie. if in 2020 provide ignoreBeforeVersion=”2018” will ignore 2017 below.

Returns:

zip object contain a tuple of (version,version label)

Return type:

zip[tuple[str, str]]

currentFbxExportVersion()

Files

exportContext(rootNode)
exportMultiContext(nodes)
newScene(force=True)

Creates a new maya scene.

Parameters:

force (bool) – Whether to force the creation of a new scene.

Returns:

The name of the new scene usually “untitled”.

Return type:

str

saveScene(path, removeUnknownPlugins=False)
openFile(path, selectivePreload=False, force=True, modified=False)

Opens the maya file.

Parameters:
  • path (str) – The absolute path to the maya file

  • selectivePreload (bool) – If True the preload reference dialog will be shown if there’s references

  • force (bool) – Force’s a new scene

  • modified (bool) – If True then the scene state will be set to True, this is the same as cmds.file(modified=True)

importScene(filePath, force=True)
referenceFile(filePath, namespace=None)
exportSceneAsFbx(filePath, skeletonDefinition=False, constraints=False)
exportAbc(filePath, objectRootList=None, frameRange='1 1', visibility=True, creases=True, uvSets=True, autoSubd=True, dataFormat='ogawa', userAttr=None, userAttrPrefix=None, stripNamespaces=False, selection=False)
Exports and alembic file from multiple objects/transform nodes, could be multiple selected hierarchies for

example objectRootList is the list of objects who’s hierarchy is to be exported.

Note

Since the cmds.AbcExport does not support spaces in filepaths, this function saves in temp and then moves the file to the correct location.

Parameters:
  • filePath (str) – the full file path to save to.

  • objectRootList (list) – a list of objects that are the root object, under each transform gets exported, None is scene.

  • frameRange (str) – frame range (to and from) separated by a space.

  • visibility (bool) – export visibility state?

  • creases (bool) – export creases? autoSubd needs to be on.

  • uvSets (bool) – export with uv sets?.

  • creases – export creases? autoSubd needs to be on.

  • autoSubd (str) – Must be on for crease edges, crease vertices or holes, mesh is written out as an OSubD.

  • userAttr (tuple) – will export including Maya attributes with these custom strings in a list.

  • userAttrPrefix (tuple) – will export including Maya attributes with these prefix’s, custom strings in a list.

  • stripNamespaces (bool) – will strip the namespaces on export, if duplicated names it will fail.

  • selection (bool) – will export selected nodes only, given they are under the root list.

getCamGeoRootsFromScene(exportGeo=True, exportCams=True, returnWorldRoots=True)

Returns the root objects of ge and cams (so that objects can’t be doubled) top most node/s in a scene. This is for .abc exporting where the root nodes need to be given and not doubled

Parameters:
  • exportGeo (bool) – find roots of all geo in the scene?

  • exportCams (bool) – find roots of all cameras in the scene?

  • returnWorldRoots (bool) – instead of returning the object roots, return the full scene roots, bottom of hierarchy

Return objectRootList:

all root object names (objects can’t be doubled) of the scene with cams or geo

Rtype objectRootList:

list

exportAbcSceneFilters(filePath, frameRange='1 1', visibility=True, creases=True, uvSets=True, dataFormat='ogawa', noMayaDefaultCams=True, exportGeo=True, exportCams=True, exportAll=True, userAttr=None, userAttrPrefix=None)

Export alembic whole scene settings

Parameters:
  • filePath (str) – the full file path to save to

  • frameRange (str) – frame range (to and from) separated by a space

  • visibility (bool) – export visibility state?

  • creases (bool) – export creases? autoSubd needs to be on

  • uvSets (bool) – export with uv sets?

  • dataFormat (str) – Alembic can save is a variety of formats, most commonly “ogawa”

  • noMayaDefaultCams (bool) – If True don’t export Maya’s default cams such as persp, top, side, front etc

  • exportGeo (bool) – Export geometry?

  • exportCams (bool) – Export cameras?

  • exportAll (bool) – exports everything in the scene

  • userAttr (tuple) – will export including Maya attributes with these custom strings in a list

  • userAttrPrefix (tuple) – will export including Maya attributes with these prefix’s, custom strings in a list

Return filePath:

the full file path to save the alembic

Rtype filePath:

str

Return objectRootList:

list of the root object to export, alembic requires root objects/transforms to export

Rtype objectRootList:

list(str)

exportAbcSelected(filePath, frameRange='1 1', visibility=True, creases=True, uvSets=True, dataFormat='ogawa', userAttr=None, userAttrPrefix=None)

Exports selected objects as alembic filetype .ABC and will auto load the plugin/s if not loaded Alembics export from the root, so filter the root of each selection hierarchy

Parameters:
  • filePath (str) – the full file path to save to

  • frameRange (str) – frame range (to and from) separated by a space

  • visibility (bool) – export visibility state?

  • creases (bool) – export creases?

  • uvSets – export with uv sets?

  • dataFormat (str) – abc format type, usually “ogawa”

Returns:

the full file path to saved.

Return type:

str

exportObj(filePath, sceneNode)
loadAbcPlugin(message=True)

Loads the AbcImport and AbcExport plugins, also autoloads the alembic plugins

Parameters:

message (bool) – Report the message to the user?

importAlembic(filePath, message=False)

Loads an alembic file (.ABC) and will auto load the plugin/s if not loaded

Parameters:
  • filePath (str) – The full filepath to the file

  • message (bool) – Report the message to the user?

Returns:

the filepath loaded

Return type:

str

importObj(filePath)
importFbx(filepath, cameras=False, lights=False, skeletonDefinition=True, constraints=True)
exportFbx(filePath, exportNodes, skeletonDefinition=False, constraints=False, **kwargs)
Parameters:
  • filePath (str) – The absolute file path

  • exportNodes (list or str) –

  • skeletonDefinition (bool) –

  • constraints (bool) –

  • kwargs (dict) –

Returns:

Return type:

class ModFile(path)

Bases: object

pluginPath = ''
version = ''
pluginName = ''
scriptsPath = ''
property resolvedScriptsPath
mayaFileType(message=True)

Returns the current Maya file type

Returns:

General

General maya functions

Example use:

from zoo.libs.maya.utils import general
lockSelectedNodes(unlock=False, message=True)
isSafeName(name)

Determines if the provided name is safe for use as a node name.

A name isn’t valid if it doesn’t start with a letter, or contains any invalid characters.

Parameters:

name (str) – The name to check

Returns:

True if the name is valid, False otherwise

Return type:

bool

mayaUpVector()

Gets the current world up vector

Return type:

om1.MVector

upAxis()

Returns the current world up axis in str form.

Returns:

returns x,y or z

Return type:

str

isYAxisUp()

Returns True if y is world up

Returns:

bool

isZAxisUp()

Returns True if Z is world up

Returns:

bool

isXAxisUp()

Returns True if x is world up

Returns:

bool

loadPlugin(pluginPath)

Loads the given maya plugin path can be .mll or .py

Parameters:

pluginPath (str) – the absolute fullpath file path to the plugin

Return type:

bool

unloadPlugin(pluginPath)

unLoads the given maya plugin name can be .mll or .py

Parameters:

pluginPath (str) – Maya plugin name

Return type:

bool

isPluginLoaded(pluginPath)

Returns True if the given plugin name is loaded

getMayaPlugins()
loadAllMayaPlugins()
unLoadMayaPlugins()
removeUnknownPlugins(message=True)

Removes unknown plugins from the scene.

Parameters:

message (bool) – report the message to the user

Returns:

A set of the removed plugins

Return type:

set[str]

deleteUnknownNodes(message=True)

Deletes nodes of unknown type, usually plugins that are missing or not installed.

Also see removeUnknownPlugins()

Parameters:

message (bool) – Report a message to the user?

Returns:

Unknown nodes that were deleted and not deleted.

Return type:

tuple[[str], [str]]

deleteTurtlePluginScene(removeShelf=True, message=True)

Removes Turtle from the scene, unloads the plugin and deletes the shelf too.

Parameters:
  • removeShelf (bool) – If True delete the Turtle shelf

  • message (bool) – report a message to the user?

Returns:

If True Turtle was removed

Return type:

bool

deleteShelf(name)

Deletes maya shelf

Parameters:

name (str) – Name of shelf

Returns:

Returns true if deleted, False otherwise

lockSelectedNodes(unlock=False, message=True)

Locks or unlocks the selected nodes, Maya locked nodes are nodes that can’t be deleted.

Parameters:
  • unlock (bool) – unlock the nodes instead of locking?

  • message (bool) – Report a message to the user?

Returns:

nodes that were unlocked

Return type:

list(str)

namespaceContext(namespace)

Context manager which temporarily sets the current namespace, if the namespace doesn’t exist it will be created.

Parameters:

namespace (str) – The maya Namespace to use, ie. “MyNamespace” or “:MyNamespace”

tempNamespaceContext(namespace)

Creates a temporary namespace that only lives for the life time of the scope

Parameters:

namespace (str) – The Temporary maya Namespace to use, ie. “tempNamespace” or “:tempNamespace”

generateUniqueNamespace(name)

Generates a unique namespace based on the current scene state in the form of name, name01, name02.

If the provided namespace is already unique it will be returned as is.

Parameters:

name (str) – The prefix for the namespace

Returns:

The unique name.

Return type:

str

isolatedNodes(nodes, panel)

Context manager for isolating nodes in maya model panel

Parameters:
  • nodes (seq(str)) – A list of node fullpaths to isolate

  • panel (str) – The maya model panel

maintainSelectionContext()

Context manager which maintains the current selection

maintainSelectionDecorator(func)

Decorator to maintain the current selection.

undoDecorator(func)

Allows all cmds, mel commands perform by the the func into a single undo operation.

@undoDecorator
def myoperationFunc():
    pass
undoContext(name=None)

Context manager for maya undo.

with undoContext:
    cmds.polyCube()
    cmds.sphere()
openUndoChunk(name=None)

Opens a Maya undo chunk

closeUndoChunk(name=None)

Opens a Maya undo chunk

createRepeatCommandForFunc(func, *args, **kwargs)

Function which updates mayas repeat last command with the provide function.

Note

Only functions/staticmethods/classmethods are supported.

def testFunction(argOne, keyword=None):
    print(argOne, keyword)

createRepeatCommandForFunc(testFunction, "helloworld", keyword=0)
Parameters:
  • func (callable) – The function for the user repeat(hotkey: g or editMenu: repeat Last)

  • args (tuple) – The arguments to pass to the repeat function

  • kwargs (dict) – The keyword arguments to pass to the repeat function.

createRepeatLastCommandDecorator(function)

Decorator function which updates the maya repeat command with the decorated function.

Note

All args/kwargs of the decorated function will be passed to the repeat command

Note

Only functions/staticmethods/classmethods are supported.

@createRepeatLastCommandDecorator
def testFunction():
    print("test function")
userShelfDir()

Path to shelf

Returns:

mayaAppDir()

The Maya preference folder

Windows Vista, Windows 7, and Windows 8

Users<username>DocumentsMaya Mac OS X

~<username>/Library/Preferences/Autodesk/Maya Linux (64-bit)

~<username>/Maya

Returns:

Gui

inViewMessage(header, message, type_=0, fadeStayTime=1000)

Smaller wrapper function for nicely formatting maya inview message, INFO,WARNING,ERROR message types supported. Each message type will have a set color.

Parameters:
  • header (str) – The main header title for the message , ideally one word

  • message (str) – The message to display

  • type (int) – gui.INFO,gui.WARNING, gui.ERROR

  • fadeStayTime (int) – the fade time

refreshContext()
selectedChannelboxAttributes()
swapOutgoingConnectionsOnSelectedAttrs()

Mayamath

axisVectorByIdx(index)

Returns the axis vector by index

Parameters:

index (int) – The index of the axis between 0-2

Returns:

The Axis Vector eg. om2.MVector(1,0,0) for 0 index.

Return type:

om2.MVector

aimToNode(source, target, aimVector=None, upVector=None, worldUpVector=None, constrainAxis=MockExt.OpenMaya.MVector)

Function to aim one node at another using quaternions.

Parameters:
  • source (om2.MObject) – node to aim towards the target node

  • target (om2.MObject) – the node which the source will aim at

  • aimVector (om2.MVector) – the om2.MVector for the aim axis defaults to om2.MVector(1.0,0.0,0.0)

  • upVector (om2.MVector) – the om2.MVector for the upVector axis defaults to om2.MVector(0.0,1.0,0.0)

  • worldUpVector (om2.MVector) – Alternative World Up Vector.

  • constrainAxis (om2.MVector) – The axis vector to constrain the aim on. ie. om2.MVector(0,1,1) will set X rotation to 0.0. Same deal as mayas aim constraint.

lookAt(sourcePosition, aimPosition, aimVector=None, upVector=None, worldUpVector=None, constrainAxis=MockExt.OpenMaya.MVector)

Function to aim one node at another using quaternions.

Parameters:
  • sourcePosition (om2.MVector) – source position which acts as the eye.

  • aimPosition (om2.MVector) – The target position to aim at.

  • aimVector (om2.MVector) – the om2.MVector for the aim axis defaults to om2.MVector(1.0,0.0,0.0)

  • upVector (om2.MVector) – the om2.MVector for the upVector axis defaults to om2.MVector(0.0,1.0,0.0)

  • worldUpVector (om2.MVector) – Alternative World Up Vector.

  • constrainAxis (om2.MVector) – The axis vector to constrain the aim on. ie. om2.MVector(0,1,1) will set X rotation to 0.0. Same deal as mayas aim constraint.

Return type:

om2.MQuaternion

Scene Node Structure:

             + (upVector)
           /
          /
(sourcePosition) o------ + (aimVector) (aimPosition)
                             +
quaterionDot(qa, qb)

Computes the dot product of two quaternions.

Parameters:
  • qa (om2.Quaternion) – The first quaternion.

  • qb (om2.Quaternion) – The second quaternion.

Returns:

The dot product of the two quaternions.

Return type:

float

slerp(qa, qb, weight)

Interpolates between two quaternions using a spherical linear interpolation.

Parameters:
  • qa (om2.Quaternion) – The starting quaternion.

  • qb (om2.Quaternion) – The ending quaternion.

  • weight (float) – the weight of the second quaternion in the interpolation

Returns:

The interpolated quaternion.

Return type:

om2.Quaternion

toEulerXYZ(rotMatrix, degrees=False)

Convert rotation matrix to Euler XYZ angles.

Parameters:
  • rotMatrix (om2.MMatrix) – The rotation matrix to convert.

  • degrees (bool) – A flag to indicate if the output angles should be in degrees or radians

Returns:

The converted Euler XYZ angles

Return type:

om2.MEulerRotation

toEulerXZY(rotMatrix, degrees=False)

Convert rotation matrix to Euler XZY angles.

Parameters:
  • rotMatrix (om2.MMatrix) – The rotation matrix to convert.

  • degrees (bool) – A flag to indicate if the output angles should be in degrees or radians

Returns:

The converted Euler XZY angles

Return type:

om2.MEulerRotation

toEulerYXZ(rotMatrix, degrees=False)

Convert rotation matrix to Euler XZY angles.

Parameters:
  • rotMatrix (om2.MMatrix) – The rotation matrix to convert.

  • degrees (bool) – A flag to indicate if the output angles should be in degrees or radians

Returns:

The converted Euler XZY angles

Return type:

om2.MEulerRotation

toEulerYZX(rotMatrix, degrees=False)

Convert rotation matrix to Euler YZX angles.

Parameters:
  • rotMatrix (om2.MMatrix) – The rotation matrix to convert.

  • degrees (bool) – A flag to indicate if the output angles should be in degrees or radians

Returns:

The converted Euler YZX angles

Return type:

om2.MEulerRotation

toEulerZXY(rotMatrix, degrees=False)

Convert rotation matrix to Euler ZXY angles.

Parameters:
  • rotMatrix (om2.MMatrix) – The rotation matrix to convert.

  • degrees (bool) – A flag to indicate if the output angles should be in degrees or radians

Returns:

The converted Euler ZXY angles

Return type:

om2.MEulerRotation

toEulerZYX(rotMatrix, degrees=False)

Convert rotation matrix to Euler ZYX angles.

Parameters:
  • rotMatrix (om2.MMatrix) – The rotation matrix to convert.

  • degrees (bool) – A flag to indicate if the output angles should be in degrees or radians

Returns:

The converted Euler ZYX angles

Return type:

om2.MEulerRotation

toEulerFactory(rotMatrix, rotateOrder, degrees=False)

A factory function that returns the corresponding euler angles based on the provided rotate order.

Parameters:
  • rotMatrix (om2.MMatrix) – The rotation matrix to convert.

  • rotateOrder (om2.MTransformationMatrix.kXYZ) – The order of rotation for the euler angles. Can be one of (kXYZ, kXZY, kYXZ, kYZX, kZXY, kZYX)

  • degrees (bool) – A flag to indicate if the output angles should be in degrees or radians

Returns:

The converted Euler angles

Return type:

om2.MEulerRotation

mirrorXY(rotationMatrix)

Mirror a rotation matrix on the XY plane.

Parameters:

rotationMatrix (om2.MMatrix) – the rotation matrix to mirror

Returns:

the mirrored rotation matrix

Return type:

om2.MMatrix

mirrorYZ(rotationMatrix)

Mirror a rotation matrix on the YZ plane.

Parameters:

rotationMatrix (om2.MMatrix) – the rotation matrix to mirror

Returns:

the mirrored rotation matrix

Return type:

om2.MMatrix

mirrorXZ(rotationMatrix)

Mirror a rotation matrix on the XZ plane.

Parameters:

rotationMatrix (om2.MMatrix) – the rotation matrix to mirror

Returns:

the mirrored rotation matrix

Return type:

om2.MMatrix

angleBetween3Points(a, b, c)

Compute the angle between three points in degrees.

Parameters:
  • a (om2.Vector) – The first point

  • b (om2.Vector) – The second point

  • c (om2.Vector) – The third point

Returns:

The angle between the three points

Return type:

float

angleBetween3PointsRadians(a, b, c)

Compute the angle between three points in radians.

Parameters:
  • a (om2.Vector) – The first point

  • b (om2.Vector) – The second point

  • c (om2.Vector) – The third point

Returns:

The angle between the three points

Return type:

float

weightedPositionFromTriangle(start, mid, end)

Returns the weighted position between the start and end points using a triangle. This accounts for the rotation of the start by using a lookat function to generate a Plane normal before computing the closest point on the plane.

Parameters:
  • start (om2.MVector) – The start vector eg.start of triangle(uprLeg/arm etc)

  • mid (om2.MVector) – The mid vector eg. middle of triangle(knee/elbow etc)

  • end (om2.MVector) – The end vector eg. end of triangle(ankle/wrist etc)

Returns:

The weighted position between the start and end points and the weight value between 0-1.

Return type:

tuple[om2.MVector, float]

evenLinearPointDistribution(start, end, count)

Generator function which evenly distributes points along a straight line.

Each returned point is the vector.

Parameters:
  • start (zapi.Vector) – The start vector

  • end (zapi.Vector) – The end vector

  • count (int) – the number of points to distribute

Returns:

The distributed vector

Return type:

zapi.Vector

firstLastOffsetLinearPointDistribution(start, end, count, offset)

Same behaviour as evenLinearPointDistribution() but offsets the first and last point by the ‘offset value’

Each returned point is the vector.

Parameters:
  • start (zapi.Vector) – The start vector

  • end (zapi.Vector) – The end vector

  • count (int) – the number of points to distribute

  • offset – The value to offset the first and last points. The offset is calculated from the fraction(direction*(fraction*offset))

Returns:

The distributed vector

Return type:

tuple[zapi.Vector, float]

averagePosition(nodes)

Returns the average position on all provided nodes in workspace.

Parameters:

nodes (list[zapi.DagNode]) –

Returns:

Return type:

om2.MVector

averageNormalVector(nodes, axis)

Computes and returns the averaged normal based on the provided nodes rotations.

Parameters:
  • nodes (list[zoo.libs.maya.zapi.DagNode]) – The nodes to average

  • axis (om2.MVector) – The axis to rotate around ie. om2.MVector(1,0,0)

Returns:

The normalized averaged rotations as a vector.

Return type:

om2.MVector

twoPointNormal(pointA, pointB, normal)

Based on two points and an additional normal vector return the plane normal.

Parameters:
  • pointA (om2.MVector) – First Vector

  • pointB (om2.MVector) – Second Vector

  • normal (om2.MVector) – Additional normal which will be crossed with the distance vector

Returns:

Plane Normal

Return type:

om2.MVector

threePointNormal(pointA, pointB, pointC)

Same As twoPointNormal() but for three points.

Parameters:
  • pointA (om2.MVector) – First Vector

  • pointB (om2.MVector) – Second Vector

  • pointC (om2.MVector) – Third Vector

Returns:

Normalized vector from three points

Return type:

om2.MVector

closestPointOnPlane(point, plane)

Returns the closet point on the given Plane(projecting the point on the plane).

Parameters:
  • point (om2.MVector) – The point to project on to the plane.

  • plane (om2.MPlane) – The plane instance to get the closest point.

Returns:

The closest point.

Return type:

om2.MVector

indexOfLargest(iterable)

Returns the index of the largest absolute valued component in an iterable.

Parameters:

iterable (iterable) – An iterable of floating point values to search.

Return type:

int

axisInDirection(matrix, compareVector, defaultAxis)

Returns the axis in integer form 0, 1, 2, 3, 4, 5

0-2 is positive x,y,z while 3,4,5 is negative x,y,z

The defaultAxis is returned if the compareVector is zero or too small to provide meaningful directionality.

Parameters:
  • matrix (om2.MMatrix) – The source matrix

  • compareVector (om2.MVector) – the direction vector to compare the matrix to. ie. zapi.Vector(0,0,1)

  • defaultAxis (int) – The default axis index to use when ZeroDivisionError is raised

Return type:

int

basisVectorsFromMatrix(matrix)

Returns 3 orthonormal basis vectors that represent the orientation of the given object.

Parameters:

matrix (om2.MMatrix) – The matrix to return the orthonormal basis from

Rtype matrix:

tuple[om2.MVector, om2.MVector, om2.MVector]

basisXVectorFromMatrix(matrix)

Returns X orthonormal basis vectors that represent the X rotation axis vector.

Parameters:

matrix (om2.MMatrix) – The matrix to return the orthonormal basis from

Rtype matrix:

om2.MVector

basisYVectorFromMatrix(matrix)

Returns Y orthonormal basis vectors that represent the X rotation axis vector.

Parameters:

matrix (om2.MMatrix) – The matrix to return the orthonormal basis from

Rtype matrix:

om2.MVector

basisZVectorFromMatrix(matrix)

Returns Z orthonormal basis vectors that represent the X rotation axis vector.

Parameters:

matrix (om2.MMatrix) – The matrix to return the orthonormal basis from

Rtype matrix:

om2.MVector

alignToWorldAxis(matrix, rotationAxis=1, forwardAxis=MockExt.OpenMaya.MVector, defaultAxisDirection=2)

Returns the minimal viable single axis rotation to align to the forward axis.

Parameters:
  • matrix (om2.MMatrix) – The reference Matrix to pull the rotation from commonly this is the worldMatrix

  • rotationAxis (int) – The axis to rotate on. Defaults to YAXIS

  • forwardAxis (om2.MVector) – The forward vector representing the axis, defaults to ZAXIS_VECTOR

  • defaultAxisDirection (int) – The default forwardAxis to use when a ZeroDivisionError occurs.

Return type:

:class:` om2.MEulerRotation`

perpendicularAxisFromAlignVectors(aimVector, upVector)

Given an aim and up vector return which axis isn’t being used and determine whether to get positive values from an incoming attribute whether it needs to be negated.

result = driverAxisFromAimUpVectors(om2.MVector(1,0,0), om2.MVector(0,1,0))
# (2, True)  # 2 is the axis number therefore Z
Parameters:
  • aimVector

  • upVector

Returns:

Return type:

tuple[int, bool]

isVectorNegative(vector)

Whether the sum of the vector(x+y+z) is less then 0.0 :param vector: :return:

primaryAxisNameFromVector(vector)

Internal function which returns the string name of the vector ie. X,Y,Z

Parameters:

vector (zapi.Vector or tuple) – The vector to check

Returns:

Vector Axis Name ie . X, Y or Z

Return type:

str

primaryAxisIndexFromVector(vector)

Internal function which returns the string name of the vector ie. X,Y,Z

Parameters:

vector (zapi.Vector or tuple) – The vector to check

Returns:

Vector Axis index

Return type:

int

nonPrimaryAxisNamesFromVector(vector)

Given a vector, returns a list of the non-primary axes. The primary axis is the one with the largest absolute value.

Parameters:

vector (om2.MVector) – The input vector.

Returns:

List of non-primary axis names

Return type:

list

convertToSceneUnits(value)

Converts the value to the current maya scene UI unit. ie. meters, inches.

Note

Only current supports meters, inches and feet

Parameters:

value (float or int or om2.MVector) – value to convert to the scene units.

Returns:

The newly converted value.

Return type:

float or int or om2.MVector

convertFromSceneUnits(value)

Converts the value from the current maya scene UI unit back to centimeters. ie. meters to cms, inches.

Note

Only current supports meters, inches and feet

Parameters:

value (float or int or om2.MVector) – value to convert to the scene units.

Returns:

The newly converted value.

Return type:

float or int or om2.MVector

bezierGroups(values)

Groups a list of values into bezier chunks where the first and last tangents are two points and the middles are three points.

Parameters:

values (list[list[]]) –

my_list = [0, 1, 2, 3, 4, 5, 6] my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8] result = bezierChunks(my_list) print(result) #[[0, 1], [2, 3, 4], [5, 6, 7], [7, 8]]

bezierSections(values)

Groups a list of values into bezier chunks where the first and last tangents are two points and the middles are three points.

Parameters:

values (list[list[]]) –

my_list = [0, 1, 2, 3, 4, 5, 6] my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8] result = bezierChunks(my_list) print(result) #[[0, 1], [2, 3, 4], [5, 6, 7], [7, 8]]

bezierSegments(points)

Splits the points into bezier segments of 4 points each.

Parameters:

points (list[any]) – List of values which represent cv points, this function only operates on the length on the list provided and the values are returned.

Returns:

List of curve segments formed by the Bezier curve. Each segment is represented as a list of control points.

Return type:

list[list[any]]

Scene

findAdditionalSceneDependencies(references=True, textures=True)

Find additional dependencies from the scene by looking at the file references and texture paths

findSceneTextures()
findTextureNodePairs()
iterTextureNodePairs(includeReferences=False)
findSceneReferences()
isolatedNodes(nodes, panel)

Context manager for isolating nodes in maya model panel

hasUnknownNodes()

Checks to see if there are any unknown nodes

Type:

bool

hasUnknownPlugins()

Checks to see if there are any unknown plugins

Return type:

bool

isCentimeters()

Returns True if the current scene is in centimeters.

Return type:

bool

isFeet()

Returns True if the current scene is in centimeters.

Return type:

bool

isInches()

Returns True if the current scene is in inches.

Return type:

bool

isKilometers()

Returns True if the current scene is in kilometers.

Return type:

bool

isLast()

Returns True if the current scene is in last.

Return type:

bool

isMeters()

Returns True if the current scene is in meters.

Return type:

bool

isMiles()

Returns True if the current scene is in miles.

Return type:

bool

isMillimeters()

Returns True if the current scene is in millimeters.

Return type:

bool

isYards()

Returns True if the current scene is in yards.

Return type:

bool

Shelves

class Shelf(name='Animation')

Bases: object

A simple class to build shelves in maya. Since the build method is empty, it should be extended by the derived class to build the necessary shelf elements. By default, it creates an empty shelf called “customShelf”.

Parameters:

name (str) – Name of the shelf

setAsActive()

Set the shelf as active in maya

shortName()

The shelf name without the full path.

Return type:

str

createShelf()

Create the shelf in maya

addButton(label, tooltip=None, icon='commandButton.png', command=None, doubleCommand=None, Type='python', style='iconOnly')

Adds a shelf button with the specified label, command, double click command and image.

Parameters:
  • label (str) – label of the button

  • tooltip (str) – tooltip text to display when hovering over the button

  • icon (str) – file path to image file for button icon

  • command (str) – command to execute on button press

  • doubleCommand (str) – command to execute on button double-press

  • Type (str) – type of command (python or mel)

  • style (str) – the layout of the button (iconOnly, textOnly, or iconAndText)

Returns:

The shelfButton UI path

Return type:

str

static addMenuItem(parent, label, command='', icon='')

Adds a menu item with the specified label, command, and image. :param parent: The parent menu where the item should be added. :type parent: str :param label: The label of the menu item. :type label: str :param command: The command that should be executed when the menu item is clicked. :type command: str :param icon: The path to the icon that should be used for the menu item. :type icon: str :return: The menu item that has been created. :rtype: str

static addSubMenu(parent, label, icon=None)

Adds a sub menu item with the specified label and icon to the specified parent popup menu.

Parameters:
  • parent (str) – The parent menu where the sub menu should be added.

  • label (str) – The label of the sub menu.

  • icon (str) – The path to the icon that should be used for the sub menu.

Returns:

The sub menu that has been created.

Return type:

str

static addMenuSeparator(parent, **kwargs)

Adds a separator(line) on the parent menu.

This uses the cmds.menuItem to create the separator

Parameters:

parent (str) – The full UI path to the parent menu

addSeparator()

Adds a maya shelf separator to the parent shelf

Returns:

The full path to the separator

Return type:

str

filePath()

Returns the appropriate path for the shelf file.

Return type:

str

clear(deleteShelf=True)

Checks if the shelf exists and empties it if it does or creates it if it does not.

shelfExists(shelfName)

Checks if a shelf exists in maya

Parameters:

shelfName (str) – The name of the shelf

Returns:

True if the shelf exists, False if it does not

Return type:

bool

cleanOldShelf(shelfName, deleteShelf=True)

Checks if the shelf exists and empties it if it does

primaryShelfLayout()

Returns the main maya shelf layer path.

Have to mel globals here, the hell?

Returns:

The shelf layout path

Return type:

str

activeShelf()

Returns the currently active maya shelf as a Shelf object.

Returns:

Return type:

Shelf

MayaColors

Functions and constants related directly to Maya’s color handling.

Example use:

from zoo.libs.maya.utils import mayacolors
mayacolors.setColorSpaceAces()
renderSpaceColor = mayacolors.displayColorToCurrentRenderingSpace(displaySpaceColor)
displaySpaceColor = mayacolors.renderingColorToDisplaySpace(renderingSpaceColor)
setColorSpaceLinear(message=True)

Sets color space color management settings to be linear as per older versions of Maya in 2022 and above

setColorSpaceAces(message=True)

Sets color space color management settings to be ACES as per the new defaults in Maya in 2022 and above

setColorSpaceAcesNoTone(message=True)

Sets color space color management settings to be ACES (no tone map) in Maya in 2022 and above

setRenderingSpace(renderSpace='linear', message=True)

Sets the renderspace for Maya, use only in 2022 and above.

Parameters:
  • renderSpace (str) – linear or aces

  • message (bool) – Report a message to the user?

setViewTransform(view='noToneMap', message=True)

Sets the view transform (grade/tone-map) inside Maya.

Parameters:
  • view (str) – “noToneMap” or “sdrVideo”

  • message (bool) – Report a message to the user?

displayColorToCurrentRenderingSpace(displayColor, setCurrentViewSpace=False, viewSpace='Un-tone-mapped')

Converts display space color to the current rendering space using Maya’s API

The Maya commands function cmds.colorManagementConvert() is useless.

Only works in Maya 2023 and above. Issues in 2022 unfortunately.

If lower than 2023 will return the color linearized instead.

viewSpace should be “Un-tone-mapped” if importing in JSON data, also for conversions to figure render space color.

Parameters:
  • displayColor (list(float)) – display color (usually srgb color) as a float [0.1, 0.4, 0.6]

  • setCurrentViewSpace (str) – Sets the viewspace as the current viewspace. If True kwarg viewSpace is ignored.

  • viewSpace (str) – What view to output? ‘ACES 1.0 SDR-video’, ‘Un-tone-mapped’, ‘Unity neutral tone-map’, ‘Raw’ etc

Return color:

color in maya’s native rendering space as a float

Rtype color:

list(float)

renderingColorToDisplaySpace(renderColor, setCurrentViewSpace=False, viewSpace='Un-tone-mapped')

Converts rendering space color to the current display space using Maya’s API

The Maya commands function cmds.colorManagementConvert() is useless.

Only works in Maya 2023 and above. Display colors are Un-tone-mapped. Issues in 2022 unfortunately.

If lower than 2023 will return the color linear to srgb instead.

viewSpace should be “Un-tone-mapped” if importing in JSON data, also for conversions to figure render space color.

Parameters:
  • displayColor (list(float)) – display color (usually srgb color) as a float [0.1, 0.4, 0.6]

  • viewSpace (str) – what grade to output? ‘ACES 1.0 SDR-video’, ‘Un-tone-mapped’, ‘Unity neutral tone-map’, ‘Raw’ etc

Return color:

color in maya’s native rendering space as a float

Rtype color:

list(float)

renderingColorToDisplaySpaceLegacy(renderingSpaceColor)

Converts rendering space color to the current display space color using cmds.colorManagementConvert (not great)

This is depreciated, use renderingColorToDisplaySpace() as it supports the viewspace.

Parameters:

renderingSpaceColor (list(float)) – color in maya’s native rendering space as a float [0.1, 0.4, 0.6]

Return displayColor:

display color (usually srgb color) as a float [0.1, 0.4, 0.6]

Rtype displayColor:

list(float)

Maya Test Utils

class BaseMayaTest(methodName='runTest')

Bases: BaseUnitest

Base class for all maya based unitests, provides helper methods for loading and loading plugins

keepPluginsLoaded = False
loadedPlugins = {}
application = 'maya'
newSceneAfterTest = False
newSceneAfterTearDownCls = True
classmethod loadPlugin(pluginName)

Loads a given plugin and stores it on the class :param pluginName: str, the plugin to load

classmethod unloadPlugins()

Unload all the currently loaded plugins

tearDown(**kw)

Hook method for deconstructing the test fixture after testing it.

classmethod tearDownClass()

Calls on cls.unloadPlugins()

Tooltips

tooltipState()

Get the maya tooltip state

Returns:

Return type:

bool

setMayaTooltipState(state)

Set the maya state to show the tooltips or not.

Parameters:

state – bool

Returns: