Flattening unwanted bones

Originally posted to Shawn Hargreaves Blog on MSDN, Wednesday, November 22, 2006

Sometimes it is useful to have multiple bones and meshes inside a single model (see my previous post), but other times this just causes needless complexity. All that messing around with Model.CopyAbsoluteBoneTransformsTo and setting the effect World matrix is important if you want to do things like making your car wheels spin and the doors open, but it's a waste of time if you just want to draw a single static object without any internal animation.

If you happen to know that your source artwork does not contain any nested meshes with local transforms, you obviously don't need to bother looking up or setting the bone transforms. 

Often, though, you will find that the source artwork contains many unnecessary local transforms, just because that's the way the artist happened to build it. You could go back and tell them to change their data, but it is probably easier to fix this automatically using a custom content pipeline processor.

This example derives from the built-in ModelProcessor, overrides the main Process method, and uses the MeshHelper.TransformScene method to flatten out any local transform matrices in the input data: 

    [ContentProcessor]
    class FlattenTransformsProcessor : ModelProcessor
    {
        public override ModelContent Process(NodeContent input, ContentProcessorContext context)
        {
            FlattenTransforms(input);
         
            return base.Process(input, context);
        }


        static void FlattenTransforms(NodeContent node)
        {
            MeshHelper.TransformScene(node, node.Transform);

            node.Transform = Matrix.Identity;

            foreach (NodeContent child in node.Children)
            {
                FlattenTransforms(child);
            }
        }
    }

After running your model through this custom processor, all the bone matrices will be set to identity, so you can happily ignore them in your rendering code.

Blog index   -   Back to my homepage