I am new to blender coding and I made a script to calculate a complex bone rotation. The script is intended to run like a constraint in the sense that it will execute only when the "target" object is transformed. As I am still learning blender API I would like to know which is the best way to implement this.
1 Answers
Driver
It should update if one of the variables changes:
Rotate N objects identically, but with unique variations
Consider using the driver interface even if you do something more elaborate, just in order to communicate the dependency in the depsgraph, as done here, where the solution was to add a driver using a particular variable (meaning not a variable in Python function, but a variable visible in the driver popup in the graphic interface), and therefore guaranteeing that by the time the driver is being evaluated, the variable has already been evaluated.
Msgbus
As in the comments in the code, not all changes will send a message through the bus...
Example of persistent usage of «bpy.msgbus» and how to manage it?
Depsgraph update handler
Here's a nice technique by Martynas Žiemys:
Operator that runs when a value input is changed
Frame change handler or 3D view draw handler
Just keep running a function on each frame change or even each draw call and check if properties of interest changed before running CPU intensive code:
Use a driver to programmatically set the positions of many vertices
You can even cache calculated data similarly to Physics simulation, as in this Q&A:
Distributed interaction visualization
Consider how updating values may require you to update the view layer, and therefore refresh the viewport by... Redrawing it, which should trigger the function again. Beware of accidentally making an infinite loop if your own function changes a state in such a manner, that on the next redraw it changes the state again…
Which is the best?
3d view draw handler will be constantly run, so it will always work. However, it's a script that needs to be run every time you open your project. You can enable auto-execute, but it requires some security consideration I explain here:
How to randomise any value every frame between specific interval?
That makes the project harder to share.
The driver, on the other hand, if not used in a hacky way as above, works out of the box, but its functionality is limited.
- 36,563
- 3
- 30
- 99
-
2Nice collection.. which kind of reminds me.. haven't seen @batFINGER for a bit..... – Robin Betts Jan 10 '22 at 22:37
-
2@RobinBetts I hope he's either enjoying well deserved vacation, or hacking at the problems deserving his time. – Markus von Broady Jan 10 '22 at 22:39