Archive for category programming

Grim IK binaries

Been a while since I posted. I recently dusted off my Grim IK maya plugin (two-bone solver with Soft IK, reversals, and FK blending built in), and built binaries for 2017 and 2018, Windows and Mac.  It’s here:

I figure it didn’t get much traction for two reasons: no binaries, and no documentation.  Binaries are done, and documentation will come in time, including a better example file.  If you end up using this plugin, please let me know!

surface pro and sdl 2.0

I’ve been working on a game in my spare time, which has led me to look for easy ways to create pixel art. So far my running favorite is grafx2, which is one of the few that runs almost perfectly with pen and touch (many pixel editors don’t like the newfangled bits of Windows 8).

However, grafx2 has a few oddities, which has kept pushing me on my search. Eventually I came across the SDL site after a loooong time not looking at it, and discovered that v2.0 has finally been released. It’s a modern update, and I figured I might have a go at writing a very simple pixel art editor in all the spare time I don’t have.

Anyway, since I want to edit the art on my Surface Pro, I downloaded the latest version of MinGW and set about building a testbed using SDL 2.0. First few things went well, but then it crashed when I attempted to create an accelerated SDL_Renderer.

The culprit seems to be the Intel Graphics driver that’s on the Surface Pro by default. After installing the new version from this link, I’m able to create the accelerated renderer and the program does not crash.

If you’re wondering if your own crashes are related, and they occur around program startup or just after the first real window has been opened, look in the crash log for mentions of ig7icd32.dll — that’s part of the Intel driver.

Interestingly, this update has also made Analogue: A Hate Story work on my Surface Pro again! And I’ve heard that this fixes the crash on startup experienced by some players of FTL.

Tags: , , ,

fun with python modules

New scripters I speak with don’t often know how to easily load code from external folders / modules in Python scripts. Today’s post will give you a few pointers in both Cinema 4D and Maya.

Setting Your Script Paths

Python’s import command should be no stranger to you if this topic interests you– it was probably the second thing most people learn in Python, after writing “Hello, World!” to the console. Import allows you to bring in code from libraries external to the source file in which you’re currently working. For example:

# commonly seen in Cinema 4D
import c4d
from c4d import *

# commonly seen in Maya
import maya
from maya import cmds as mc
import pymel.all as pm

These statements bring whatever module you specify into the current namespace, or bring in functions, classes, and variables. But where are the libraries that the import method references? Where do they live on disk?

The easiest way to find out is to list Python’s sys.path:

import sys

In my case, in Maya, it outputs the following:




Looking in the folders that are listed, you may find any number of Python source files and Python object files (*.pyc). sys.path is great because it’s just a regular Python list, which means it’s editable. You can append any number of paths that you like to it, and when import is called it will look through each and every path for the name specified.

Let’s try this in Cinema 4D. First, make a folder somewhere on your machine. I’m going to use /Users/Carney/Desktop/scripts for this example (I’m on a Mac.) In that folder, create a new file called and add the following text:

# simple utility functions

def ut_log(*args):
    msg =''
    for arg in args:
        msg += ' ' + str(arg)

Now back in Cinema 4D, open the Console and the Script Manager from the Scripts menu. In the Script Manager, paste the following and hit Execute, replacing the path with the folder you chose above:

import sys

import util
util.ut_log('Fun', 'Bunnies', 'are', 'fun.')

If all’s well, you should get a single sentence printed to the console output. If you made a mistake, you may get an error about not being able to import the util file. Check your path and try again.

With this setup, you can write scripts in your application that reference lengthy libraries of external code or other utility functions that you’ve created. At the moment I’m organizing code into single files with multiple functions for shorter utilities. Any function that’s more complex gets it’s own file and a class to contain it. This leads to funny lines like the following:

import module_generic
mod = module_generic.GenericModule()

But the organization and the ability to quickly update code without having to sift through a monolithic file inside the C4D Script Manager is worth the headache.

Automatically Adding Python Search Paths in Maya

The only thing to remember about this setup is that you have to make sure you add that folder you created to sys.path every time your application starts. In Maya this is a simple and well-known trick, but I had to do some digging to find out the same for Cinema 4D.

In both applications there’s a special Python file that gets loaded every time the Python VM restarts. In Maya, the file is called

Automatically Adding Search Paths in Maya

and it must live in one of three places:

  • ~/Library/Preferences/Autodesk/maya/2012-x64/prefs/scripts
  • ~/Library/Preferences/Autodesk/maya/2012-x64/scripts
  • ~/Library/Preferences/Autodesk/maya/scripts

You may notice that these are listed in the above printout of sys.path. When Maya starts it will execute files it finds. If you put the file in a folder that has the version of Maya specified (for example, in maya/2012-x64/scripts), then only that version will load the userSetup. If you place it in the general scripts folder — the last folder listed above — then it will be loaded by all Maya versions that support Python.

You can also use the MEL command internalVar -usd to find a folder that will work.

The userSetup file can execute any code you like when Maya loads, allowing you to have custom menus auto-created or to modify your sys.path variable so that you can access your code at any time. Try this: save a file into , and make sure it contains the following (after modifying the path to point to where you saved your file):

import sys

Now in Maya, open the script editor and copy, paste, and run the following:

import util
util.ut_log('Fun', 'Bunnies', 'are', 'funner.')

If all worked, you’ll see a line printed from your file letting you know that the custom setup succeeded on Maya startup, and you’ll see the proper output from this file.

Automatically Adding Python Search Paths in Cinema 4D

The way to do the above in Cinema 4D seems to be less well-known: you have to find the folder that is appropriate for your particular version of Cinema 4D and copy in a file called

The easiest way to find this folder is to go to the Scripts menu and choose User Scripts > Script Folder. This is the folder where scripts you’ve edited and saved through the Script Manager live. Now, go up one folder to Library, then go up again. This is the main folder for your version of Cinema 4D; it may have an oddly long name, but it contains your prefs and libraries. The file belongs in prefs/python. As an example, my folder is:

  • /Users/Carney/Library/MAXON/Cinema 4D R13/prefs/python/

Final Notes

This is just the start of organizing your code. If you want to know more, I recommend reading the official documentation on Python modules.

Tags: , , ,

batch wrangling part 2 – Maya 2012 Human IK

The second half of the work I did was to automate the process of moving data around between Motion Builder and Maya, and to make tools for the animators that lightened their loads when it came to exporting and retargeting animations. I was also responsible for a batch conversion pipeline.

On the project there were animations in Motion Builder FBX files that were intended for reuse, which meant loading and retargeting multiple animations across multiple characters. This is a case (if only minimal edits are required) where the HIK system in Maya can be used to blast through conversions and free up animators for other work. Also, as many of the original animations were in single FBX files as Takes and the new decision was to have one file per animation (allowing multiple animators to work on the same character without file collisions in the version repository), the multi-take Motion Builder FBX files would need to be split in batch.

The Maya Human IK system as of Maya 2012 is usable and has a lot of good benefits. Much of what they say works out of the box really does, provided you stick within the system: the ability to retarget animations between characters of differing sizes and joint placements works very well, and the fidelity of those animations stays high. If you rename or reorient bones but still have a Characterization in place for both characters, the transfer will still work out. However, there were also significant downsides:

  • The Motion Builder to Maya one-click scene send did not work as expected 100% of the time. When transferring from Motion Builder to Maya, I often found that while the Characterization would transfer over the rig itself would not be properly connected, and many times did not even come in at the right position in the Maya scene. Baking the keys down to the skeleton, transferring, and regenerating the rig on the Maya side does work. You lose the editability of having less keys, but you get a one-to-one transfer between the two programs this way and the Characterization makes rebuilding and rebaking the keys to the rig a one-click process.

  • On the Maya side you lose a lot of the features you’d expect. For example, the animators complained about not having foot roll controls. Regular Maya constraints don’t behave the same way you’d expect, and adding onto an HIK rig can be trickier than building on top of a regular Maya rig. The strangest thing was that you can’t zero controls. If you want to return to the “stance” pose, you have to change the input to the skeleton, then key the rig at the frame you want to have zero’d, and finally go back to having the rig control the skeleton. Editing curves on the HIK rig can be frustrating, as both the FK and IK objects are used to control the final position of joints and the different Human IK modes for posing and interaction pull at the body parts in different ways; often animators were baffled about which controls were causing jitters or other issues, and it was usually a control for a body part much higher up the hierarchy. Lastly, the HIK controls and skeleton don’t have the same orientations as the bones they’re based upon. If you’ve set up your skeleton in Maya properly with behaviour-mirrored arms and legs, you’ll find that you have to pose HIK-rigged characters’ limbs separately anyway. (I only had time to look into these issues for a moment, as I had a lot on my plate; if there are easy solutions that were overlooked I’d love to know what they are.)

  • I had a look at the system and the commands it used when I walked through the Characterization and retargeting processes, and determined at the time that Python was not the way to go for the retargeting pipeline itself. I found in tests that it was more work to get the MEL functions behind the HIK system working from Python than it was to write MEL wrapper functions and call out to them from Python when necessary. It was also more efficient to use the MEL functions as they were, as opposed to pulling them apart to find the necessary node connections to set up the system on my own.

    There’re a few lists of functions available online already (as I discovered on [insert blog link]). Here’re the ones I ended up using.

  • HIKCharacterizationTool, HIKCharacterControlsTool — These bring up their respective windows / docked panels. I found that not having the relevant window open made the functions that depended on the window being open fail, so keep that in mind when running HIK commands in batch.

  • getCurrentCharacter() — Returns the name of the current character as a string.

  • hikBakeToSkeleton — Bakes the keys from the rig or from another character being used as a retargeting source to the skeleton. I used this function when exporting from Maya to the game engine.

  • characterizationControlRigDelete() — Completely removes the control rig from the scene and sets the source for the character back to its skeleton.

  • setRigLookAndFeel(name, look number) — There are a few different looks for HIK rigs. In batch I found it nice to set the one I preferred before saving files out for animation fixes.

  • mayaHIKgetInputType — Returns 0 if input type is Stance Pose, 1 if input type is skeleton or control rig (I guess this means “self”), and 2 if input is another character.

  • mayaHIKsetCharacterInput(character, input character) — For retargeting, allows you to set the input of one character to be another in the scene.

  • characterizationCreate() — Creates a new Characterization node. You can rename the node and then make the UI recognize the new name with the following command.

  • characterizationToolUICmd — Useful for setting the current character name: characterizationToolUICmd -edit -setcurrentcharname [name]

  • setCharacterObject(object name, character name, characterization number, 0) — I don’t think I’ve seen this documented elsewhere, but this does the connecting during the Characterization phase from your joints into the character node. It appears the connections are specific and need to be fit into particular indices in a message attribute array, so the “characterization number” is something you need to figure out ahead of time if you’re doing a large number of these in batch. Some important numbers:

    Ground 0
    Left Thigh 2
    Left Calf 3
    Left Foot 4
    Left Toe 118
    Right Foot 7
    Right Toe 142
    Right Calf 6
    Right Thigh 5
    Pelvis / Center of Motion 1
    Left Clavicle 18
    Right Clavicle 19
    Left UpperArm 9
    Left Forearm 10
    Left Hand 11
    Right UpperArm 12
    Right Forearm 13
    Right Hand 14
    Neck Base 20
    Head 15

    The nice thing about this is that once you know all the numbers, you can slide them into attributes on the joints in your skeleton and use that data to apply characterizations later on.

  • Going forwards, if I were to use the same tools again in another production (and in cases where animation needs to be transferred between two differing skeletal hierarchies, it would make sense), I think I’d pull the code apart a bit more and have a look at how the connections are made at the lowest level, then rewrite a chunk of this code in Python.

    One more thing: using the standard functions, sometimes the UI will take a bit to catch up. Unfortunately, this means that functions which take inputs from the relevant UI will fail in situations where running them manually will work fine. EvalDeferred didn’t fix this issue for me every time, possibly because of how Qt and Maya are connected together and how they both do lazy updates at different times. I haven’t delved much into PyQt and Maya’s Qt underpinnings just yet, but the updating behavior is something for further study. In the interim, I found that using the maya.utils.processIdleEvents function to make sure all events were taken care of after doing major steps in the characterization or baking processes helped the UI catch up.

    Tags: , , , , ,

    batch wrangling – FBX

    At work we’re moving from a MotionBuilder pipeline to Maya, which I’m responsible for creating. One of the tasks on the list I was handed was to move animated takes out of MB and into Maya so that all exported files can be run through the same export steps, and also so that moving forwards animators would have the same tools for working on older animations as they will on files using my new rig.

    I have Maya Creation Suite 2012 on my work machine, which is touted as being able to seamlessly transfer data between the included apps– Maya, MotionBuilder, and Mudbox. I haven’t had need to open Mudbox yet, but in my limited testing so far the Human IK rigs never come through properly from MB to Maya and on the Maya side the HIK characterization gets broken. This means that to do any animation fixes or retargeting inside Maya, the characterization needs to be deleted and rebuilt. Also funny: the automatic naming templates in Maya don’t always work, making recharacterization a tedious manual process. Keyed transforms (joints, etc.) and meshes come through just fine, however, with all skinning and materials in tact. Updating previously-sent objects did not.

    Apart from all that, the first file I’ve been working on has 50 animations in it. I didn’t relish the idea of converting all of them by hand, so I set about seeing what’s possible on the scripting side.

    The FBX import/export plugin comes with a number of commands for massaging how files are read in. A full list of the commands is on Autodesk’s site. Note that the Python versions of these functions fail; I think they’re being generated improperly at plugin load. Could be that I’m just not calling them properly; I didn’t bug-hunt because I found doing the HIK post-import steps didn’t work in Python, either.

    I’ve written more MEL in the last two days than I have in the last four years, not that it’s a lot of code!

    The important commands for what I needed are:

    FBXRead -f [filename] — Doesn’t do any loading. Instead, it sets the specified file as the source for all queries.

    FBXGetTakeCount — Self-explanatory; on the file I was editing it returned 50.

    FBXGetTakeName [index]: returns the name of the take for a specified index. The indices are 1-based. I saved all of these in a string array.

    FBXImportSetMayaFrameRate -v [true|false] — Important in my case because the animation was all at 30 frames per second, while Maya is usually set to 24.

    FBXImportFillTimeline -v [true|false] — Makes sure the timeline length matches the length of the imported animation (although see below for a gotcha)

    FBXImport -file "c:/myfile.fbx" -t [take index] — Does the actual loading of the scene. By specifying a take index, you can be sure to get only the animation you want.

    With this information, I was able to loop through the animations in the FBX and, after a bit of post-import processing, spit out a series of .ma files.

    There were few gotchas. One problem was that while the script was running, sometimes the setting for having the FBX file’s time length override the same in Maya would get truncated– the animation length got set but the [bar that shortens the animation] would get set to half the length. I couldn’t replicate the issue running the MEL script in small chunks. A call to playbackOptions in my loop fixed this, but it’s still weird.

    Part two of this discussion will be about man-handling Maya’s Human IK in a batch process.

    Tags: , , , ,

    quick tip #1

    It’s been a while since I’ve done anything in MEL. I try to avoid MEL when I can; after two years of doing the majority of my Maya tools and scripts in Python (with the last year being pure Python), switching gears to work in MEL and losing the object-oriented nature of Python (along with its wonderful string and array manipulation tools) makes me feel like I’ve got a hand tied behind my back.

    Still, MEL’s importance will continue for some time and there will be times when it’s necessary to hack out a bit MEL code. I wanted to make a quick tip note about something I’m embarrassed to say I didn’t know until a few days ago that might help you with your MEL scripts.

    I use the whatIs command often to track down the source of built-in scripted functionality. Calling it on a function that exists in default MEL scripts will tell you in which script that function lives and where to find it; afterwards, you can break it apart and use the pertinent parts in your own script.

    However, what I did not know is that whatIs can also tell you about in-memory variables. Here’s an example:

    string $value = "Bunnies";
    int $intArray[] = { 1,2,3,4,5 };

    whatIs "$value"; // Result: string variable //
    whatIs "$intArray"; // Result: int[] variable //

    If you run the code you’ll see that it returns a string with the type of the variable you checked. Quite handy, since you can use it to check types of default global variables. But even handier is what happens when you use it on a variable that has not yet been created:

    whatIs "$someWonderfulVariable";

    This will return the string “Unknown”. If you, not unlike my recent self, are trying to determine in your or someone else’s code whether a required variable has been created, this is the way to check.

    In other news, my new job begins on Tuesday. I’m extremely excited and I’ll post more about it once I’ve gotten situated there.

    Also, if you’re Canadian, elections are happening on Monday! An interesting notion is the thought of voting for a non-Reform party candidate in your riding whose projections are highest instead of voting for the party or a leader you’re usually inclined to do, with an eye towards unseating the current Reform government and getting Harper out of there. Two websites on this very thing:

    Don’t worry– I won’t be mixing political messages with code tips in the future.

    Tags: , ,

    first steps in openCL

    I’m going to post something about my trip to Italy in a bit, after I get my pics uploaded properly to Flickr. But I wanted to put this up so I don’t forget about it later.

    A conversation at work got me interested enough in GPGPU calculations to start doing a bit of research into the topic. Seems that at a base level both the ATI and NVidia APIs behave similarly, and that OpenCL is a nice, understandable alternative if you don’t want to be locked in to a single vendor. (Not that I use ATI cards.) I tried getting CUDA working on my Mac, but between weirdness caused by the drivers and the fact that it doesn’t support 64-bit on OSX, I’ve decided to go with OpenCL instead for my tests. Functionally everything will be the same, and after a nice tutorial on ATI’s site detailing some introductory points I have code that compiles and does what I want it to do, which is more than I can say for CUDA.

    Anyway, here’s my first test. I wanted something simple for getting device information off my laptop.

    #include <iostream>
    using namespace std;

    #include <stdio.h>
    #include <stdlib.h>

    #include <OpenGL/gl.h>
    #include <OpenGL/CGLDevice.h>
    #include <OpenCL/cl.h>
    #include <OpenCL/cl_gl.h>
    #include <OpenCL/cl_gl_ext.h>
    #include <OpenCL/cl_ext.h>
    #define MSG_SIZE 4096
    #define MAX_DEVICE_IDS 16

    #define RT_STRING       0
    #define RT_UINT         1
    #define RT_BOOL         2
    #define RT_PLATFORMID   3
    #define RT_SIZET        5
    #define RT_SIZET_ARR    6

    void printDeviceInfo(cl_device_id deviceID) {
        cl_device_info param_list[] = {
        int param_return_types[] = {
        char *param_strings[] = {
            "Device Name", "Vendor", "Driver Version", "Device Version",
            "Device Profile", "Device Platform", "Device Vendor ID",
            "Max Compute Units", "Max Work Item Dimensions",
            "Max Work Item Sizes", "Max Work Group Size",
        int i = 0;
        int maxWorkItemDimensions = 3;
        while(param_strings[i] != NULL) {
            char    msg[MSG_SIZE];
            size_t  param_sizeT;
            size_t  param_sizeT_array[MSG_SIZE];
            cl_uint param_uint;
            cl_bool param_bool;
            size_t  param_value_ret;
            cl_platform_id param_platformID;
            cl_int error;
            switch (param_return_types[i]) {
                case RT_STRING:
                    error = clGetDeviceInfo(deviceID,

                    cout << param_strings[i] << ": " << msg << "\n";

                case RT_UINT:
                    error = clGetDeviceInfo(deviceID,

                    cout << param_strings[i] << ": " << param_uint << "\n";
                case RT_BOOL:
                    error = clGetDeviceInfo(deviceID,

                    cout << param_strings[i] << ": " << (param_bool ? "True" : "False") << "\n";
                case RT_PLATFORMID:
                    error = clGetDeviceInfo(deviceID,

                    cout << param_strings[i] << ": " << param_platformID << "\n";
                case RT_SIZET:
                    error = clGetDeviceInfo(deviceID,

                    cout << param_strings[i] << ": " << param_sizeT << "\n";
                case RT_SIZET_ARR:
                    error = clGetDeviceInfo(deviceID,
                                            sizeof(size_t) * maxWorkItemDimensions,

                    cout << param_strings[i] << ": " << param_sizeT_array[0] << ", "
                        << param_sizeT_array[1] << ", "
                        << param_sizeT_array[2] << "\n";

    int main(int argc, char **argv) {
        cl_device_id deviceID;
        cl_uint numDevices;

        cl_uint err = clGetDeviceIDs(
        cout << "Number of CPU devices: " << numDevices << "\n";
        for (int i = 0; i < numDevices; i++) {

        cout << "\n\n";


        err = clGetDeviceIDs(
        cout << "Number of GPU devices: " << numDevices << "\n";
        for (int i = 0; i < numDevices; i++) {
        cout << "\n\n";

    (Hope that copy-and-pasted correctly.) To compile it on your Mac:

    g++ test2.cpp -o test2 -framework OpenCL

    Here are the results on my laptop, a 2010 Core i7 MacBook Pro 15″:

    Number of CPU devices: 1
    Device Name: Intel(R) Core(TM) i7 CPU       M 620  @ 2.67GHz
    Vendor: Intel
    Driver Version: 1.0
    Device Version: OpenCL 1.0
    Device Profile: FULL_PROFILE
    Device Platform: 0
    Device Vendor ID: 16909312
    Max Compute Units: 4
    Max Work Item Dimensions: 3
    Max Work Item Sizes: 1, 1, 1
    Max Work Group Size: 1

    Number of GPU devices: 1 Device Name: GeForce GT 330M Vendor: NVIDIA Driver Version: CLH 1.0 Device Version: OpenCL 1.0 Device Profile: FULL_PROFILE Device Platform: 0 Device Vendor ID: 16918016 Max Compute Units: 6 Max Work Item Dimensions: 3 Max Work Item Sizes: 512, 512, 64 Max Work Group Size: 512

    Next step: getting the GPU to do some calculations.

    Tags: ,

    funhouse and the big top

    As I type this I’m over at FUNHouse central with Dimos. It’s been a while since we were able to work on things together, in person. Usually we work a lot over email and lunchtime talks; it’ll be good to sit and jam together.

    It’s been an interesting week. I’ve been tasked with doing research on cloth simming, or rather not simming, which is about all I can say. However, I can say that it’s been an interesting challenge and has helped me to better understand some of the more esoteric corners of Maya Dynamics.

    Work aside, the G20 meet up has the entire city by the balls. The trains are shutting down due to bomb threats, and a number of people at the office have been ID’d on the way in by the some of the hundreds of cops patrolling the downtown core. The whole thing is a mess. Lots of downtown businesses are losing money because of forced shutdowns. Even my office is shutting for friday because the building is getting boarded up.

    It’s strange to me… I can’t quite follow the logic on violent protests for something like this. Regardless of what’s being discussed, I can’t imagine any topics are worthy of that kind of response.

    Anyway, to work with us!

    Tags: , ,

    new yaaaawk, baybee!

    Dimos and I headed out over the weekend to see Mike in New York. The title of this post is what Dimos screamed, cheerleader-on-prom-night-in-the-back-of-a-volkswagen style, every five minutes. Somehow it never got old.

    There are amazing pictures taken by Mike of both Dimos and myself on Facebook; hopefully I’ll find some time this weekend to get the pics of my own camera and Flickrize them.

    I might talk a bit more about the trip in a few days, but what I actually wanted to write is this:

    To project a worldspace point into camera space, you need to multiply the camera’s view matrix by its projection matrix. The projection matrix is grabbable through the OpenMaya API (there’s a function for it on MFnCamera). The view matrix is simply the inverse of the worldspace transform matrix.

    Needed to get that out of my head and into a place I wouldn’t lose it. If that makes no sense to you, just pretend it wasn’t there. 🙂

    playing in coffee

    I’m slowly coming out of the fog of Maya, now that I’m done with using it for Animation Mentor, and I’ve been trying to get back into Cinema 4D. I just wanted to post this short COFFEE script snippet. This looks through all the animation curves on an object and spits out information on them.

    var op = doc->GetActiveObject();
    var curTime = doc->GetTime();
    println("\nKey dump for ", op->GetName(), ":\n");
    var t = op->GetFirstCTrack();
    if (t == NULL)
    var i = 0;
    var j = 0;
    var k;
    var c;
    while (t != NULL) {
    	c = t->GetCurve();
    	println("\tTrack ", i, ": ", t->GetName(), " -- ",
    	c->GetKeyCount(), " keys.");
    	for (j = 0; j < c->GetKeyCount(); j++) {
    		k = c->GetKey(j);
    		var bt = k->GetTime();
    		println("\t\t", j, ": v", k->GetValue(), ", t:", bt->GetFrame(30));
    	t = t->GetNext();
    println("Number of tracks: ", i);

    The sad part is this: you can’t add new keys to curves in COFFEE; you can only read what’s there. (EPIC FAIL, Maxon.) At least now I know how to get keys and how the BaseTime class works.