my formulas are sometimes a bit longer and i wonder how you guys enter or edit values there? are you all tapping ctrl-space to maximize the window and then enlarge the panel with mouse? Or is there somewhere a magic shortcut where i can e.g. edit the formula in a text editor?
1 Answer
Recently there has been a question, to which my answer had a long, unreadable driver, that is also hard to modify. (you don't have to go there and read it)
How to use driver for multiple objects
Working on that example, we have a driver with expression: max(pi / 2 + (abs(distance/15) < 0.8) * (pi * 3/4 - abs(distance / 5)), pi / 2 + (abs(distance2/15) < 0.8) * (pi * 3/4 - abs(distance2 / 5)))
We can go to the scripting tab, and create a new script:
Then in the area below, we can write Python code to assign a new expression to the driver:
import bpy
bpy.data.objects['Cylinder'].animation_data.drivers[0].driver.expression = """
max(
pi / 2
+ (
abs(distance / 15) < 0.8
)
* (
pi * 3/4
- abs(distance / 5)
)
,
pi / 2
+ (
abs(distance2 / 15) < 0.8
)
* (
pi * 3/4
- abs(distance2 / 5)
)
)
"""
Now clicking on the Play button will run the script:
On 2nd line ['Cylinder']
points to the object with a driver, by its name. drivers[0]
points to the 1st driver (drivers[1]
would point to the 2nd driver and so on). Keep this in mind, as when you add another driver before this one, this driver's index will increase, so the next time you modify it using this script, you will have to update its index (or you will modify another driver by accident). This could be fixed by creating a driver in code, assigning it to a variable and saving this variable for further access, but it's outside of the scope of this question.
You can also see that now the driver has weird rectangle characters:
Those are newline characters, which this input field doesn't support. The driver works, but its expression is ugly. We can fix it, and also remove excess whitespace (tabs, spaces), by changing our code to:
import bpy
expression = """
max(
pi / 2
+ (
abs(distance / 15) < 0.8
)
* (
pi * 3/4
- abs(distance / 5)
)
,
pi / 2
+ (
abs(distance2 / 15) < 0.8
)
* (
pi * 3/4
- abs(distance2 / 5)
)
)
"""
driver = bpy.data.objects['Cylinder'].animation_data.drivers[0].driver
driver.expression = ''.join(line.strip() for line in expression.splitlines())
splitlines()
divides a multiline string into a list of single line strings. ''.join
joins this list back to a single string, but uses an empty string as a separator, so effectively we replace newline characters with nothing. line.strip()
removes whitespace on the beginning and end of every line (whitespace inside the line are kept).
End result:
-
1$\begingroup$ And yes, you could just CTRL+C, CTRL+V. :D $\endgroup$ Feb 7, 2021 at 11:51