Quantcast
Channel: mel wiki
Viewing all 610 articles
Browse latest View live

If I use Maya at work, can I get a licence at home?

$
0
0
Amazingly, seemingly yes. It's called a "home use licence"
http://usa.autodesk.com/adsk/servlet/ps/dl/item?siteID=123112&id=13812813&linkID=9242258
From that page:
Home use license

Issue
How can I run Maya from home?

Solution
If you have a network license under subscription, you can apply for a "home use license".

A home use license is a stand-alone license based on a primary license. The primary license can be either a stand-alone or network license. A home use license based on a stand-alone primary license will have the same serial number as the primary license. A home use license based on a network primary license will have a different serial number, which you must obtain from Autodesk.

Subscription Contract Managers and Software Coordinators can log on to the Subscription Center to find more details on the Home Use benefit, and to apply for a home use license. To get your license:
  1. Log on to the subscription center
  2. Contract Administration.
  3. Click "Request Home" use.

How can I displace polygonal vertices based on their rendered surface color?

$
0
0
In years past I've had success with polyGeoSampler... but not lately.

You can also use this method:
  • Map a texture to the displacement channel of the mesh's materials shading engine (via the ui, so it creates the appropriate displacementShader node and connections in the process.
  • On the mesh's shape node, under the Displacement Map dropdown, set the initialSampleRate and extraSampleRate attrs to 1.
  • Modify -> Convert -> Displacement to polygons.
This will triangulate the mesh in the process, but shouldn't add any extra verts.

How can I refresh all the textures in the scene?

$
0
0
This implements what the "Reload" button on a file texture node does, but for all file nodes in the scene.
import maya.cmds as mc

print "\nRefreshing all textures in scene:"
files = mc.ls(type='file')
for f in files:
    pth = mc.getAttr('%s.fileTextureName'%f)
    mc.setAttr('%s.fileTextureName'%f, pth, type='string')
    print "\tRefreshed:", f, " : ", pth
print "Texture refresh complete"

Batching Maya Files via Python

$
0
0
This subject is about batching Maya files in a session of Maya other than the one that is currently open, via Python. It's one thing to (via the currently opened Maya) loop over a list of files opening them in succession and executing code. But if you want to launch external Maya's in batch mode (so as to not disturb your current Maya session), open a file, and execute code on that file (all in Python), it's a different story.

To batch file via Maya with mel, it's pretty straightforward via maya.exe:
> maya -batch -file someMayaFile.ma -command someMelProc
There is mayapy.exe as well, but this doesn't launch Maya: It launches Maya's version of Python. It is a Maya mirror of python.exe. However, once it has been launched, Maya itself can be imported in as a Python module, and then batching can take place. Method A explains this below.


Different methods below. I came up with Method C first, got suggested Method B, then sort of combined the two to come up with Method A.

Method A

The example below will batch over all the passed in Maya files, and saves a new group node in them as proof it worked. Some of the magic is using subprocess.call to call to mayapy.exe, and passing in an additional argument that is the name of the current file to work on. Another bit of trickery is having the module do double-duty: When executed in GUI Maya the user runs its main() function to start it up, but when it is called to via mayapy.exe putting it in 'batch mode', the top & bottom section 'if __name__ == "__main__":' are executed as well which both imports maya.standalone (thus now physically has Maya running inside of mayapy.exe) and calls to the batchOperation() function, which can then query, via sys.argv the command-line arguments passed in (which are the names of the files to batch over). I have a feeling that's not terribly clear. I hope the code makes more sense ;)

I'll label each thing has it's executed so you can see the data flow.
GUI mode starts with GUI A and ends with GUI D, which then starts BATCH A and ends with BATCH E.
# batchTest.py
import subprocess

if __name__ == "__main__":
    # If we're in 'batch' mode, it means that mayapy.exe is running,
    # so load maya.standalone into it:
    import maya.standalone
    maya.standalone.initialize(name='python')
    # If you have a userSetup.py that is needed for happy Maya execution, call
    # to it here:
    import userSetup
    userSetup.main()

import maya.cmds as mc

def main(paths):
    """
    Launched in the gui version of Maya, manually, or via some other script.

    Parameters :
    paths : string\list : Path(s) to Maya files to batch over.
    """
    if not isinstance(paths, list):
        paths = [paths]
    args = ['mayapy', __file__, '-']
    args.extend(paths)
    # This fires off another version of Maya in 'batch' mode, calling back to
    # this code, executing the 'batch only' parts.  Luckily, the current version
    # of Maya calling it waits for the other version to complete doing it's thing
    # before continuing on in this code...
    subprocess.call(args)

def batchOperation():
    """
    The work done by the batch:  This has been called to while Maya is in batch
    mode, via the subprocess.call() func in the main() function:  Because of this,
    we capture the incoming args via sys.argv.
    A single instance of Maya is launched, and then all the files are batched over
    in that instance, and processed
    """
    # The sys.argv vals match the subprocess call above
    # sys.argv[0] : The path to this module ( __file__ )
    # sys.argv[1] : '-'
    # sys.argv[2] + : Path(s) to the files to batch over
    paths = sys.argv[2:]

    # If there is an error, the shell will just disappear.  So we wrap it in a
    # try\except, allowing it to stay open to help track down bugs.
    try:
        mc.file(prompt=False)
        for fil in paths:
            mc.file(fil, force=True, open=True)
            mc.group(empty=True, name='I_was_made_in_batch_mode', world=True)
            mc.file(force=True, save=True)
    except Exception, e:
        print "Exception:", e
        raw_input("Encountered an exception, see above.  Press Enter to exit...")
    finally:
        mc.file(prompt=True)

# When called to via batch mode, run this code.  This line must come after the
# function it's calling.
if __name__ == "__main__":
    batchOperation()
To run in Maya:
import batchTest
batchTest.main(['c:/temp/myFileA.ma', 'c:/temp/myFileB.ma'])
You should see a shell pop up for the new instance of Maya that is launched (via mayapy.exe), and then each path is opened and batch processed in that shell. The gui version of Maya will wait until completion of the batch to continue on with its code.

Method B:

This example was given to me by Keir Rice. Thanks Keir!

Make a batch script: batchTest.bat . It runs mayapy.exe, which is Maya's version of Python.
REM Launcher batch file: batchTest.bat
"%ProgramFiles%\Autodesk\Maya2010\bin\mayapy.exe""c:\temp\test.py"
  • Add pause to the end of the batch script if you want the shell to stay open upon completion.
Then make the python module it calls to:
# python script to run: c:\temp\test.py
import maya.cmds

def TestFunction():
    print maya.cmds.about(version=True)

if __name__ == "__main__":
    import maya.standalone
    maya.standalone.initialize(name='python')
    TestFunction()
Finally, run the bat script. Results should be printed in the shell.

Method C:

This is one I came up with before I knew about Method A or B, above.
Key Components: (the file-names aren't important, just illustrating the example)
  • mainModule.py : This is the Python module that orchestrates the whole thing. It can be executed from Maya, or the command line.
  • melScript.mel : This is a 'wrapper' script that our batch operation will call to. It in turn, via the mel python command, will execute the Python code we want to have effect the scene files.
  • pythonModule.py : This is the Python module that our mel script calls to. In this example, it executes the main() function inside.

Here is a bit of code from mainModule.py. By calling to subprocess.call(), we're able to launch Maya in batch mode on a specific file, executing our wrapper mel command on it:
http://docs.python.org/library/subprocess.html
# mainModule.py
import subprocess
subprocess.call(['maya', '-batch', '-file', 'c:\\myFile.ma', '-command', 'melScript'])

This is the guts of our wrapper mel script. All it does is call to the Python code we care about:
// melScript.mel

global proc melScript(){
    python("import pythonModule");
    python("pythonModule.main()");
}

pythonModule.py and its main() function can prettymuch do whatever you'd like to that scene file:
# pythonModule.py
import maya.cmds as mc

def main():
    # do stuff!

Command: polyEvaluate

$
0
0
polyEvaluate is a really versatile command. Things it can do:
  • For a whole polygonal object, or just a component selection, return the number of:
    • vertex
    • edge
    • face
    • uv coordinate
    • triangle
    • shell
  • Bounding box data:
    • For the given object in 3d space, or it's uv's in 2d space.
    • For the selected components in 3d space, or for the selected uv's in 2d space.
    • The surface area of the faces in worldspace, or local space

Also see:




How can I find the uv shells for a mesh?

$
0
0
Given a polygonal object that has different UV shells (it's been mapped different ways), how can you get what uv's are in those contiguous shells?

Maybe there's a fancier way to do this, via some built-in command, but I couldn't find it. This tool will walk though each UV, expand the selection to the shell it lives in, and then compare the names of what is selected to a list of current shells (and a 'shell' is a sublist of uv's). If the current list finds no matching sublist, it adds itself in.
import maya.cmds as mc
import maya.mel as mm

def uvShellsFromSelection():
    sel = mc.ls(selection=True)
    shells = []
    uvs =  mc.ls(mc.polyListComponentConversion(sel, toUV=True), flatten=True)
    for uv in uvs:
        mc.select(uv)
        mm.eval('polySelectBorderShell 0')
        shell = mc.ls(selection=True)
        if shell not in shells:
            shells.append(shell)
    return shells

API: How can I get a screen-shot of the active view?

$
0
0
Wow, so easy:
# Python code
import maya.OpenMaya as om
import maya.OpenMayaUI as omui

fileType = 'jpg'
imageFile = 'c:/temp/mayaScreen.%s'%fileType
mimage = om.MImage()
view = omui.M3dView.active3dView()
view.readColorBuffer(mimage, True)
mimage.writeToFile(imageFile, fileType)
From the MImage docs, these image formats are supported for output:
  • iff, sgi, pic, tif, als, gif, rla, jpg
Docs:

How can I find all the dependencies in a scene: References, textures, etc?

$
0
0
file
  • Example:
string $alldependencies[] = `file -q -l`;
Also check out the filePathEditor command.

I should note that this tool only lists dependencies it can actually find. For example, if the user types in a path to a texture that's not on disk, this tool won't return that path, since the texture can't be found.


Also see:

How can I update maya's icon path?

$
0
0
You need to update the XBMLANGPATH environment variable. This is like MAYA_SCRIPT_PATH, but for icons used for such things as shelf buttons.
import os
os.environ["XBMLANGPATH"] = "%s;%s"%(os.getenv("XBMLANGPATH"), "c:/some/icon/path/")

How can I change if I'm using Maya 'Complete', or 'Unlimited'?

$
0
0
Presuming you have Maya Unlimited installed (and properly licensed), there are two ways to change what features are available to you.

One way is to add this line to your Maya.env file:
MAYA_LICENSE = complete
or
MAYA_LICENSE = unlimited
Every time you start Maya, it will run in the defined mode.

Another way allows you to launch Maya from the command line (probably with a .bat file) with the license defined. This allows you to say, run temporarily in unlimited when you normally only run in complete (via the Maya.env).
maya -lic=unlimited

How can I get Python code to execute during Maya startup?

$
0
0
Two ways that I know of:

Method #1 : userSetup.py:

  • Create a userSetup.py module here: (Windows)
<drive>:\Documents and Settings\<username>\My Documents\maya\<Version>\scripts\userSetup.py
  • And put whatever Python code you want to execute at startup in there. This is basically just like the userSetup.mel file, but for Python.

Method #2 : Update PYTHONSTARTUP:

  • If you add an environment variable with the above name, and point it to a valid python module, Python will execute the code in that module before the prompt is displayed in interactive mode.
PYTHONSTARTUP = c:/some/path/someModule.py
  • Note: I haven't tested this in Maya yet, but I know it works with Python outside of Maya. I use method #1.

Method #3 : Author a 'sitecustomize and\or usercustomize modules':

  • See notes on my Python wiki here.
  • These are Python's equivalent to Maya's userSetup.py module.

Also see:

How can I reference a file using a Windows Environment Variable as part of the path?

$
0
0
  • Example: Make an evn var with the path to the file, then reference it in:
// here we build the var in Maya, but it could be declared in Windows first:
putenv "MAYAFILES""c:/temp";  
file -r -type "mayaAscii" -gl -namespace "TEST" -options "v=0""$MAYAFILES/myFile.ma";
  • From now on, the scene will look to $MAYAFILES as the directory for the file. If at any point you need to move the file, move it to the new location, and then update the $MAYAFILES enviroment variable. The Maya scene file will automatically look to the new location.

How can I find out what environment variables Maya uses?

$
0
0
The documentation:
Example:
  • Essentials -> Basic Features -> Setting Environment Variables -> Standard Maya environment variables

How can I find out what a single environment variable is set to, in Maya?

$
0
0

Python:

import os
msp = os.getenv("MAYA_SCRIPT_PATH")

Mel:

getenv
  • Example:
string $msp = `getenv MAYA_SCRIPT_PATH`;

How can I 'reveal selected' in the Outliner?

$
0
0
fitPanel -selected;
I knew this worked for camera's, but didn't know it worked in an outlinerPanel\outlinerEditor as well.
It appears this is the default 'f' hotkey... went for many years without knowing this...

How can I use my own FK controllers on Maya's IK-FK system?

$
0
0
Maya lets you turn any IK chain into a switchable ik\fk system. Which seems neat at first, until you realize how limiting it is: You need to parent (for example) nurbs curves as a shape node to the joint to add a selection abstraction layer for the animators (so they're not picking the joints directly. But they're still keyframing directly on the joints in FK mode. And this makes you sad. So you don't use it, and end up rigging a system that has multiple IK\FK chains constrained together to pull this off.

Then, you figure out from the guy sitting next to you, in fact you can do this:
  • On the ikHandle node turn off"IK FK Control". Turn off "Snap enable".
  • Constrain the joints to your fk controllers.
  • Now, when switching back and forth between IK and FK, this is what you do:
    • ikBlend is used to switch back and forth between the ik solve, and the fk system.
    • Additionally, blend off the constraint weights on the joints.
Boom.
Thanks to for the info from Mason Sheffield.

How can I execute a scriptJob on an attribute change in a referenced scene?

$
0
0
Via Maya's scriptJob command, you can easily execute callbacks. And via Maya's scriptNode command, you can create 'script nodes' that can execute 'script jobs' when a scene opens.
Via this method, its fairly trivial to create a sciptJob that will cause a script to evaluate whenever a certain attribute on a certain node changes. But this all breaks down if that file is referenced: Since the name of the node has now changed (due to the namespace), the scriptJob no longer detects it.

Thanks to an undocumented tip from Mason Sheffield, you can actually put a wildcard (*:objName.attr) in front of the object name during the scriptJob authoring: It will now detect the namespace:obj.attr name in the reference. Awesome.

However, there are two problems with this system:
  • Upon open of the un-referenced scene, you'll get a RuntimeError saying (for example):
# RuntimeError: Could not find attribute named "*:mynode.tx" # 
  • If you reference the referenced scene (which can happen) : The scriptJob will no longer evaluate, since it's only looking 'one level deep' for the namespace. If you know this will be consistent, you can embed *:*: in front of your node, instead of just *:.

Here's an example of how to set it up:

Create this script, and save it as attrCallback.py. Save it in Maya's script path. What does this script do? A: It creates a scriptNode that lives in the current scene, that will execute a scriptJob when that scene is opened. B: Whenever the translateX attr on a node called mynode is modified (in a scene referenced one level deep), it will execute the attrCallbackfunction, which simply prints some text.
# attrCallback.py

import maya.cmds as mc

def attrCallback():
    print "mynode.tx changed!"

def makeScriptNode():
    scriptStr = 'import maya.cmds as mc\n'+\
        'import attrCallback\n'+\
        'mc.scriptJob(attributeChange=["*:mynode.tx", attrCallback.attrCallback])'
    mc.scriptNode( scriptType=2, beforeScript=scriptStr, name='myScriptNode', stp='python')
Make a new scene, and in it create a new node. Rename that node to mynode.
In the script editor, execute:
import attrCallback
attrCallback.makeScriptNode()
This will create the scriptNode. Save your scene as attrCallback.ma. If you modify mynode.translateX nothing will happen, since the scriptNode is searching for the node in a sub-namespace (and it currently lives in the root namespace).
Create a new scene. Reference in attrCallback.ma. Adjust the mynode.translateX : You should see the Script Editor starting printing the results from attrCallback().

MainMenu

SOuP: Basics

SOuP : Basic Voronoi Fracture

$
0
0
This is based on the set of SOuP tools.

I've always like the look of voronoi diagrams. They can be expressed in 2d, or 3d. Soup's 'shatter' node uses this system to 'fracture mesh into pieces'. What a great look. The below is a simple step-by-step to get this set up.

Soup nodes used:
  • scatter Used to populate points inside of a volume.
  • shatter Used to shatter a mesh based on a list of points.
Instructions:
  • Create the polygonal mesh you want fractured. Call it 'sourceMesh'.
  • Duplicate it, and call it 'finalMesh'.
  • Create a Soup scatter node.
  • Connect:
    • sourceMeshShape.outMesh -> scatterShape1.inGeometry
    • You should see a bunch of points appear inside the mesh.
  • Create a Soup shatter node. To start, you may want to turn down the "point density" to something lower, like 100.
  • Connect:
    • scatterShape1.outGeometry -> shatter1.inGeometry
    • scatterShape1.outPositionPP -> shatter.inPositionPP
  • Now hook up the shatter to the 'finalMesh'. Connect:
    • shatter1.outGeometry -> finalMeshShape.inMesh
  • You still won't see anything yet:
    • Hide the 'sourceMesh'
    • On the 'shatter' node, turn "auto evalute" on. After a pause, you should see the shattered mesh.
From this point, you can adjust the scatter "point density" to higher or lower values, and adjust the shatter "distance".
If you need to adjust the shape of your object, go unhide the 'sourceMesh', and make adjustments to it. To speed up evaluation, you should turn off "auto evaluate" on the shatter node.

Page 3 (currently) of the Soup examples shows many different uses for the shatter: http://www.soup-dev.com/examples2_3.htm
Viewing all 610 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>