Blender: Exporting Keyframe-based Animations
Just got asked how to export animations from within Blender. While collecting the essential snippets, I though, I might as well put it in a short post in case it can help somebody else. Note that this post assumes that you are familiar with Blender’s Python API and thus only gives the most essential information to get you started. I.e. what are the main data-paths to get animation data. More specifically, how to export the transformed vertices for every frame of the animation.
Let’s assume you have defined an animation on some object in blender. E.g. by manually setting keyframes on some object or by recording some physics-based animation with the Blender Game Engine. Let’s also assume the object is currently selected and active. The essential steps to access the transformed vertices are as follows:
# Get the active object o = bpy.context.active_object # Get index of the first and last frame of the animation (start_frame, end_frame) = o.animation_data.action.frame_range # Iterate over each frame for f in range(int(start_frame), int(end_frame) + 1): # Set the current frame of the scene bpy.context.scene.frame_set(f) # Iterate over vertices for v in o.data.vertices: # Transform each vertex with the current world-matrix print(o.matrix_world * v.co)
Note: the world-matrix of the object contains the current rotation, scaling and translation transforms due to the active frame of the animation sequence.
Obviously, this script is only to show how to get to the relevant information. In a real exporter, you might not iterator over the vertices directly, but over the faces; but I assume, you know these things and only the animation-related part is new to you.
Just one final note: If you have a lot of frames, the amount of vertex data in your final model file might get very large as you export O(numVertices * numFrames) many elements. And often animations, especially skeletal-based ones, can be exported more efficiently by only exporting the transforms to be applied to each part of the model (think torso, upper leg, lower leg, tows…). The transforms can then be nicely applied and interpolated in code with glTransform, glRotate, glScale and friends (yes, deprecated, but good to make the point) assuming you are using OpenGL for rendering.