File: bl_animation_bake.py

package info (click to toggle)
blender 5.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 329,128 kB
  • sloc: cpp: 2,489,823; python: 349,859; ansic: 261,364; xml: 2,103; sh: 999; javascript: 317; makefile: 193
file content (243 lines) | stat: -rw-r--r-- 11,023 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# SPDX-FileCopyrightText: 2025 Blender Authors
#
# SPDX-License-Identifier: GPL-2.0-or-later

import unittest
import sys
import pathlib

import bpy
from bpy_extras import anim_utils


"""
blender -b --factory-startup --python tests/python/bl_animation_bake.py
"""

OBJECT_BAKE_OPTIONS = anim_utils.BakeOptions(
    only_selected=False,
    do_pose=False,
    do_object=True,
    do_visual_keying=False,
    do_constraint_clear=False,
    do_parents_clear=False,
    do_clean=False,
    do_location=True,
    do_rotation=True,
    do_scale=True,
    do_bbone=False,
    do_custom_props=False,
)


class ObjectBakeTest(unittest.TestCase):
    """This tests the animation baking to document the current behavior without any attempt of declaring that behavior correct or good."""
    obj: bpy.types.Object

    def setUp(self) -> None:
        bpy.ops.wm.read_homefile(use_factory_startup=True)
        self.obj = bpy.data.objects.new("test_object", None)
        bpy.context.scene.collection.objects.link(self.obj)
        self.obj.animation_data_create()

    def test_bake_object_without_animation(self):
        self.assertEqual(self.obj.animation_data.action, None)

        anim_utils.bake_action_objects([(self.obj, None)], frames=range(0, 10), bake_options=OBJECT_BAKE_OPTIONS)

        action = self.obj.animation_data.action
        self.assertIsNotNone(action, "Baking without an existing action should create an action")
        self.assertEqual(len(action.slots), 1, "Baking should have created a slot")
        self.assertEqual(action.slots[0], self.obj.animation_data.action_slot)
        channelbag = anim_utils.action_get_channelbag_for_slot(action, action.slots[0])

        self.assertIsNotNone(channelbag)
        self.assertEqual(len(channelbag.fcurves), 9, "If no animation is present, FCurves are created for all channels")

        for fcurve in channelbag.fcurves:
            self.assertEqual(len(fcurve.keyframe_points), 10, f"Unexpected key count on {fcurve.data_path}")
            self.assertAlmostEqual(fcurve.keyframe_points[0].co.x, 0, 6,
                                   f"Unexpected key y position on {fcurve.data_path}")
            self.assertAlmostEqual(fcurve.keyframe_points[-1].co.x, 9, 6, "Baking range is exclusive for the end")

    def test_bake_object_animation_to_new_action(self):
        action = bpy.data.actions.new("test_action")
        self.obj.animation_data.action = action

        bpy.context.scene.frame_set(0)
        self.obj.keyframe_insert("location")
        bpy.context.scene.frame_set(15)
        self.obj.location = (1, 1, 1)
        self.obj.keyframe_insert("location")

        # Passing None here will create a new action.
        anim_utils.bake_action_objects([(self.obj, None)], frames=range(0, 10), bake_options=OBJECT_BAKE_OPTIONS)

        self.assertNotEqual(action, self.obj.animation_data.action, "Expected baking to result in a new action")
        baked_action = self.obj.animation_data.action
        self.assertEqual(len(baked_action.slots), 1)
        self.assertEqual(baked_action.slots[0].name_display, action.slots[0].name_display)
        channelbag = anim_utils.action_get_channelbag_for_slot(baked_action, self.obj.animation_data.action_slot)

        self.assertIsNotNone(channelbag)
        self.assertEqual(len(channelbag.fcurves), 9)

        for fcurve in channelbag.fcurves:
            self.assertEqual(len(fcurve.keyframe_points), 10, f"Unexpected key count on {fcurve.data_path}")
            self.assertAlmostEqual(fcurve.keyframe_points[-1].co.x, 9,
                                   6, f"Baking to a new action should delete all keys outside the given range ({fcurve.data_path})")

    def test_bake_object_animation_to_existing_action(self):
        action = bpy.data.actions.new("test_action")
        self.obj.animation_data.action = action

        bpy.context.scene.frame_set(0)
        self.obj.keyframe_insert("location")
        bpy.context.scene.frame_set(15)
        self.obj.location = (1, 1, 1)
        self.obj.keyframe_insert("location")

        # Passing the action as the second element of the tuple means that it will be written into.
        anim_utils.bake_action_objects([(self.obj, action)], frames=range(0, 10), bake_options=OBJECT_BAKE_OPTIONS)

        self.assertEqual(self.obj.animation_data.action, action)
        self.assertEqual(len(action.slots), 1)
        channelbag = anim_utils.action_get_channelbag_for_slot(action, self.obj.animation_data.action_slot)

        self.assertIsNotNone(channelbag)
        self.assertEqual(len(channelbag.fcurves), 9)

        for fcurve in channelbag.fcurves:
            if fcurve.data_path == "location":
                self.assertAlmostEqual(fcurve.keyframe_points[-1].co.x, 15,
                                       6, f"Baking over an existing action should preserve all keys even those out of range ({fcurve.data_path})")
                self.assertEqual(len(fcurve.keyframe_points), 11, f"Unexpected key count on {fcurve.data_path}")
            else:
                self.assertAlmostEqual(fcurve.keyframe_points[-1].co.x, 9,
                                       6, f"Unexpected key y position on {fcurve.data_path}")
                self.assertEqual(len(fcurve.keyframe_points), 10, f"Unexpected key count on {fcurve.data_path}")

    def test_bake_object_multi_slot_to_new_action(self):
        obj2 = bpy.data.objects.new("obj2", None)
        bpy.context.scene.collection.objects.link(obj2)
        action = bpy.data.actions.new("test_action")
        self.obj.animation_data.action = action
        obj2.animation_data_create().action = action

        bpy.context.scene.frame_set(0)
        self.obj.location = (0, 0, 0)
        self.obj.keyframe_insert("location")
        obj2.location = (0, 1, 0)
        obj2.keyframe_insert("location")

        bpy.context.scene.frame_set(9)
        self.obj.location = (2, 0, 0)
        self.obj.keyframe_insert("location")
        obj2.location = (2, 1, 0)
        obj2.keyframe_insert("location")

        self.assertIsNotNone(self.obj.animation_data.action_slot)
        self.assertIsNotNone(obj2.animation_data.action_slot)
        self.assertNotEqual(self.obj.animation_data.action_slot, obj2.animation_data.action_slot)
        original_slot = obj2.animation_data.action_slot
        anim_utils.bake_action_objects([(obj2, None)], frames=range(0, 10), bake_options=OBJECT_BAKE_OPTIONS)

        self.assertNotEqual(action, obj2.animation_data.action, "Expected baking to result in a new action")
        baked_action = obj2.animation_data.action
        self.assertEqual(len(baked_action.slots), 1)
        self.assertEqual(original_slot.name_display, baked_action.slots[0].name_display)
        channelbag = anim_utils.action_get_channelbag_for_slot(baked_action, baked_action.slots[0])

        for fcurve in channelbag.fcurves:
            if fcurve.data_path != "location":
                continue
            # The keyframes should match the animation of obj2, not self.obj.
            if fcurve.array_index == 0:
                self.assertAlmostEqual(fcurve.keyframe_points[0].co.y, 0,
                                       6, f"Unexpected key y position on {fcurve.data_path}")
                self.assertAlmostEqual(fcurve.keyframe_points[-1].co.y, 2,
                                       6, f"Unexpected key y position on {fcurve.data_path}")
            elif fcurve.array_index == 1:
                self.assertAlmostEqual(fcurve.keyframe_points[0].co.y, 1,
                                       6, f"Unexpected key y position on {fcurve.data_path}")
                self.assertAlmostEqual(fcurve.keyframe_points[-1].co.y, 1,
                                       6, f"Unexpected key y position on {fcurve.data_path}")

    def test_bake_object_multi_slot_to_existing_action(self):
        obj2 = bpy.data.objects.new("obj2", None)
        bpy.context.scene.collection.objects.link(obj2)
        action = bpy.data.actions.new("test_action")
        self.obj.animation_data.action = action
        obj2.animation_data_create().action = action

        bpy.context.scene.frame_set(0)
        self.obj.location = (0, 0, 0)
        self.obj.keyframe_insert("location")
        obj2.location = (0, 1, 0)
        obj2.keyframe_insert("location")

        bpy.context.scene.frame_set(15)
        self.obj.location = (2, 0, 0)
        self.obj.keyframe_insert("location")
        obj2.location = (2, 1, 0)
        obj2.keyframe_insert("location")

        self.assertEqual(len(action.slots), 2)

        self.assertIsNotNone(self.obj.animation_data.action_slot)
        self.assertIsNotNone(obj2.animation_data.action_slot)

        anim_utils.bake_action_objects([(obj2, action)], frames=range(0, 10), bake_options=OBJECT_BAKE_OPTIONS)

        self.assertEqual(action, obj2.animation_data.action)
        self.assertEqual(len(action.slots), 2, "Didn't expect baking to create a new slot")
        self.assertNotEqual(obj2.animation_data.action_slot, self.obj.animation_data.action_slot)

        channelbag = anim_utils.action_get_channelbag_for_slot(action, obj2.animation_data.action_slot)

        self.assertIsNotNone(channelbag)
        self.assertEqual(len(channelbag.fcurves), 9)

        for fcurve in channelbag.fcurves:
            # The keyframes should match the animation of obj2, not self.obj.
            if fcurve.data_path == "location":
                self.assertAlmostEqual(fcurve.keyframe_points[-1].co.x, 15,
                                       6, f"Baking over an existing action should preserve all keys even those out of range ({fcurve.data_path})")
                self.assertEqual(len(fcurve.keyframe_points), 11, f"Unexpected key count on {fcurve.data_path}")
                if fcurve.array_index == 0:
                    self.assertAlmostEqual(fcurve.keyframe_points[-1].co.y, 2,
                                           6, f"Unexpected key y position on {fcurve.data_path}")
                elif fcurve.array_index == 1:
                    self.assertAlmostEqual(fcurve.keyframe_points[-1].co.y, 1,
                                           6, f"Unexpected key y position on {fcurve.data_path}")
            else:
                self.assertAlmostEqual(fcurve.keyframe_points[-1].co.x, 9,
                                       6, f"Unexpected key y position on {fcurve.data_path}")
                self.assertEqual(len(fcurve.keyframe_points), 10, f"Unexpected key count on {fcurve.data_path}")


def main():
    global args
    import argparse

    argv = [sys.argv[0]]
    if '--' in sys.argv:
        argv += sys.argv[sys.argv.index('--') + 1:]

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--output-dir",
        dest="output_dir",
        type=pathlib.Path,
        default=pathlib.Path("."),
        help="Where to output temp saved blendfiles",
        required=False,
    )

    args, remaining = parser.parse_known_args(argv)

    unittest.main(argv=remaining)


if __name__ == "__main__":
    main()