Blender: Long-running Python scripts

Standard

Blender provides a Python API for extending the editor. It allows us to write operators that apply instantaneous changes to the scene (e.g. generate procedural meshes or spawn objects in a given pattern). However, those operators are synchronous by default and will block the editor while they run. So if you want to do some processing over several frames and use Blender simultaneously, you’re in a bit of a pickle.

In my case, I wanted to animate models with various 3D input devices (think Razer Hydra or Leap Motion) so retrieving their tracking data and updating the scene in real-time was essential.

One intuitive way to make this possible would be to write a minimalist operator that only starts a thread. The thread then handles the connection to the device, the data retrieval and the scene updates. Sadly, Blender is not thread-safe and the editor is doomed to crash as soon as the thread modifies the content of the scene.

A better solution is to use modal operators which modal() method is continuously called as long as it returns {'PASS_THROUGH'} (instead of {'CANCELLED'} or {'FINISHED'}). You could do all your processing in modal() but the frequency of its calls is unclear. I found that the most flexible option is to do the heavy lifting in a thread, at the speed of your choice, while modal() safely updates the scene.

Here is an excerpt from the script that was used in the final implementation to control a hand model with a Razer Hydra, a data glove and a multi-touch tablet (video).

Leave a Reply