Importing Expressions in Maya
April 24th, 2011Writing expressions in Maya is a huge pain. The error messages are vague, there’s no stack trace, and the editor is a text entry field with no line numbers, syntax highlighting, or line wraps. And Maya forbid you try to write a script with a dynamically-generated expression in it — then everything has to be a giant encoded string. And when you try to run it, it squirts venom at you from its eyeballs.
However, it’s possible to write and edit your expression in the text editor of your choice, save it to a file, and import that file into your script at runtime. This is much, much nicer, and comes with less venom.
There’s a way using fread to put the entire contents of a file into a string at once, but I had trouble with it — this way, reading a line at a time, seems to work better. [Based on this tutorial from Jay Grenier's Script Swell.]
Code follows:
// procedure to put the contents of a file into a string
global proc string textFileToString (string $filePath) {
// open file
$fileId = `fopen $filePath "r"`;
// define string
string $data;
// get the first line
string $nextLine = `fgetline $fileId`;
// loop until the string size is zero (no data on that line)
while (size($nextLine) > 0) {
// add to string
$data += $nextLine;
// get next line and continue
$nextLine = `fgetline $fileId`;
}
// return string
return $data;
}
// example, in this case writing a particle expression:
string $particleExp;
$particleExp = textFileToString("C:/scripts/myScript.mel");
dynExpression -s $particleExp -rbd particleShape1;
« previously: Voxatron | Home | next: Thursday »