Blender V5.3
anim_motion_paths.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "MEM_guardedalloc.h"
10
11#include <cstdlib>
12
13#include "BLI_bounds.hh"
14#include "BLI_listbase.hh"
16#include "BLI_math_matrix.hh"
17#include "BLI_math_matrix_c.hh"
18#include "BLI_math_vector_c.hh"
19#include "BLI_string.hh"
20
21#include "DNA_anim_types.h"
22#include "DNA_armature_types.h"
23#include "DNA_scene_types.h"
24
25#include "BKE_action.hh"
26#include "BKE_anim_data.hh"
28#include "BKE_camera.h"
29#include "BKE_main.hh"
30#include "BKE_scene.hh"
31
32#include "DEG_depsgraph.hh"
35
36#include "GPU_batch.hh"
37#include "GPU_vertex_buffer.hh"
38
39#include "ED_anim_api.hh"
41
42#include "ANIM_action.hh"
43#include "ANIM_action_legacy.hh"
44#include "ANIM_animdata.hh"
46
47#include "CLG_log.h"
48
49namespace blender {
50
51static CLG_LogRef LOG = {"anim.motion_paths"};
52
53/* ........ */
54
55namespace ed::motionpath {
56
57void tag_for_recalc(bMotionPath &motion_path)
58{
59 if (!motion_path.points) {
60 return;
61 }
62 for (int i = 0; i < motion_path.length; i++) {
63 motion_path.points[i].flag &= ~MOTIONPATH_VERT_EVALUATED;
64 }
65}
66
67} // namespace ed::motionpath
68
69Depsgraph *animviz_depsgraph_build(Main *bmain,
70 Scene *scene,
71 ViewLayer *view_layer,
72 const Span<MPathTarget> targets)
73{
74 /* Allocate dependency graph. */
75 Depsgraph *depsgraph = DEG_graph_new(bmain, scene, view_layer, DAG_EVAL_VIEWPORT);
76
77 /* Make a flat array of IDs for the DEG API. */
78 Array<ID *> ids(targets.size());
79 int current_id_index = 0;
80 for (const MPathTarget &mpt : targets) {
81 ids[current_id_index++] = &mpt.ob->id;
82 }
83
84 /* Build graph from all requested IDs. */
85 DEG_graph_build_from_ids(depsgraph, ids);
86
87 return depsgraph;
88}
89
91{
92 /* TODO: it would be nice in future to be able to update objects dependent on these bones too? */
93
94 /* Object itself first. */
95 if ((ob->avs.recalc & ANIMVIZ_RECALC_PATHS) && (ob->mpath)) {
96 /* New target for object. */
97 MPathTarget mpt;
98 mpt.mpath = ob->mpath;
99 mpt.ob = ob;
100
101 r_targets.append(mpt);
102 }
103
104 /* Bones. */
105 if ((ob->pose) && (ob->pose->avs.recalc & ANIMVIZ_RECALC_PATHS)) {
106 bArmature *arm = id_cast<bArmature *>(ob->data);
107 for (bPoseChannel &pchan : ob->pose->chanbase) {
108 if (!pchan.mpath) {
109 continue;
110 }
111 Bone *bone = pchan.bone_get(*ob);
112 if (!bone || !ANIM_bone_in_visible_collection(arm, bone)) {
113 continue;
114 }
115 /* New target for bone. */
116 MPathTarget mpt;
117 mpt.mpath = pchan.mpath;
118 mpt.ob = ob;
119 mpt.pchan = &pchan;
120 r_targets.append(mpt);
121 }
122 }
123}
124
125/* ........ */
126
127/* Converts the given point into NDC space. */
128static float3 transform_mpath_point_to_camera(Depsgraph &depsgraph,
129 Object &camera,
130 const float3 point)
131{
132 Object *cam_eval = DEG_get_evaluated(&depsgraph, &camera);
133 /* Aka projection matrix. */
134 float4x4 window_matrix;
135 Scene *scene = DEG_get_input_scene(&depsgraph);
136 BKE_camera_multiview_window_matrix(&scene->r, cam_eval, nullptr, window_matrix.ptr());
137 /* World to Object is the view matrix. */
138 float4x4 perspective_matrix = window_matrix * cam_eval->world_to_object();
139 const float4 co_clip_space = perspective_matrix * float4(point.x, point.y, point.z, 1.0);
140 /* Storing the verts in NDC space which contains lens effects like sensor offset. See
141 * `overlay_motion_path.hh/motion_path_sync`. Negative w values are behind the camera, thus
142 * can't be correctly projected into the scene. Using abs(w) is consistent with
143 * `project_point` in shader code. */
144 const float3 co_ndc_space = float3(co_clip_space) /
145 math::max(math::abs(co_clip_space.w), 0.0001f);
146 return co_ndc_space;
147}
148
153 Depsgraph &depsgraph,
154 Object *camera)
155{
156 bMotionPath *mpath = mpt.mpath;
157 Object *ob_eval = DEG_get_evaluated(&depsgraph, mpt.ob);
158
159 if (!ob_eval) {
160 /* The given Object should be in the depsgraph. */
162 return {};
163 }
164
165 /* Lookup evaluated pose channel, here because the depsgraph
166 * evaluation can change them so they are not cached in mpt. */
167 bPoseChannel *pchan_eval = nullptr;
168 if (mpt.pchan) {
169 pchan_eval = BKE_pose_channel_find_name(ob_eval->pose, mpt.pchan->name);
170 }
171
172 float3 calculated_point;
173
174 /* Pose-channel or object path baking? */
175 if (pchan_eval) {
176 /* Heads or tails. */
177 if (mpath->flag & MOTIONPATH_FLAG_BHEAD) {
178 copy_v3_v3(calculated_point, pchan_eval->pose_head);
179 }
180 else {
181 copy_v3_v3(calculated_point, pchan_eval->pose_tail);
182 }
183
184 /* Result must be in world-space. */
185 mul_m4_v3(ob_eval->object_to_world().ptr(), calculated_point);
186 }
187 else {
188 /* World-space object location. */
189 copy_v3_v3(calculated_point, ob_eval->object_to_world().location());
190 }
191
192 if (mpath->flag & MOTIONPATH_FLAG_BAKE_CAMERA && camera) {
193 calculated_point = transform_mpath_point_to_camera(depsgraph, *camera, calculated_point);
194 }
195
196 return calculated_point;
197}
198
199/* Perform baking for the targets on the current frame. Returns true if data was modified. */
201 const int cframe,
202 Depsgraph *depsgraph,
203 Object *camera)
204{
205 /* For each target, check if it can be baked on the current frame. */
206 bMotionPath *mpath = mpt.mpath;
207
208 /* Current frame must be within the range the cache works for.
209 * - is inclusive of the first frame, but not the last otherwise we get buffer overruns.
210 */
211 if ((cframe < mpath->start_frame) || (cframe >= mpath->end_frame)) {
212 return false;
213 }
214
215 /* Get the relevant cache vert to write to. */
216 bMotionPathVert &mpv = mpath->points[cframe - mpath->start_frame];
217 float3 calculated_point = get_evaluated_point_for_target(mpt, *depsgraph, camera);
218 float3 previous_point;
219 copy_v3_v3(previous_point, mpv.co);
220 copy_v3_v3(mpv.co, calculated_point);
221
222 /* Tag if it's a keyframe. */
223 if (ED_keylist_find_exact(mpt.keylist, cframe)) {
225 }
226 else {
228 }
229
230 const bool was_already_evaluated = mpv.flag & MOTIONPATH_VERT_EVALUATED;
232 /* This does a floating point equality comparison. While that is usually a bad idea, the code
233 * that arrives at those numbers is deterministic. So the result will be *identical* as long as
234 * the input values are the same. Since we care about equality of the input values bitwise
235 * equality is the only correct metric here. */
236 const bool has_changed = previous_point != calculated_point;
237 /* If the data was not evaluated before, by definition it changed even if the values are the
238 * same. */
239 return has_changed || !was_already_evaluated;
240}
241
242/* Get pointer to animviz settings for the given target. */
244{
245 if (mpt.pchan != nullptr) {
246 return &mpt.ob->pose->avs;
247 }
248 return &mpt.ob->avs;
249}
250
252{
253 bAnimVizSettings *avs = ob->mode == OB_MODE_POSE ? &ob->pose->avs : &ob->avs;
254
256 /* Don't touch manually-determined ranges. */
257 return;
258 }
259
260 const bool has_action = ob->adt && ob->adt->action;
261 if (avs->path_range == MOTIONPATH_RANGE_SCENE || !has_action ||
263 {
264 /* Default to the scene (preview) range if there is no animation data to
265 * find selected keys in. */
266 avs->path_sf = scene->playback_start();
267 avs->path_ef = scene->playback_end();
268 return;
269 }
270
271 AnimKeylist *keylist = ED_keylist_create();
273 fcurve_to_keylist(ob->adt, fcu, keylist, 0, {-FLT_MAX, FLT_MAX}, true);
274 }
275
276 Bounds<float> frame_range;
277 switch (avs->path_range) {
279 if (ED_keylist_selected_keys_frame_range(keylist, &frame_range)) {
280 break;
281 }
282 ATTR_FALLTHROUGH; /* Fall through if there were no selected keys found. */
284 ED_keylist_all_keys_frame_range(keylist, &frame_range);
285 break;
288 BLI_assert_msg(false, "This should not happen, function should have exited earlier.");
289 };
290
291 avs->path_sf = frame_range.min;
292 avs->path_ef = frame_range.max;
293
294 ED_keylist_free(keylist);
295}
296
298{
299 /* For object level motion paths this is a nullptr in which case the filtering is ignored. */
300 bPoseChannel *pose_bone = target.pchan;
301 for (FCurve *fcu : animrig::fcurves_for_assigned_action(target.ob->adt)) {
302 if (pose_bone &&
303 !animrig::fcurve_matches_collection_path(*fcu, "pose.bones[", pose_bone->name))
304 {
305 continue;
306 }
307 /* When only updating a subset of the motion path we could pass a range here to improve
308 * performance. */
309 fcurve_to_keylist(target.ob->adt, fcu, &keylist, 0, {-FLT_MAX, FLT_MAX}, true);
310 }
311}
312
313static bool any_range_contains(const Span<Bounds<int>> ranges, const int frame)
314{
315 for (const Bounds<int> &range : ranges) {
316 if (range.contains(frame)) {
317 return true;
318 }
319 }
320 return false;
321}
322
323static bMotionPath *get_evaluated_motion_path(Depsgraph &depsgraph, const MPathTarget &mpt)
324{
325 Object *ob_eval = DEG_get_evaluated(&depsgraph, mpt.ob);
326
327 if (!ob_eval) {
328 return nullptr;
329 }
330
331 /* Lookup evaluated pose channel, here because the depsgraph
332 * evaluation can change them so they are not cached in mpt. */
333 bPoseChannel *pchan_eval = nullptr;
334 if (mpt.pchan) {
335 pchan_eval = BKE_pose_channel_find_name(ob_eval->pose, mpt.pchan->name);
336 }
337 if (pchan_eval) {
338 return pchan_eval->mpath;
339 }
340 return ob_eval->mpath;
341}
342
343void animviz_update_motionpath_preview(Depsgraph &depsgraph, Span<MPathTarget> targets)
344{
345 for (const MPathTarget &mpt : targets) {
346 /* Since this is just a temporary visualization we always want the world space here. */
347 const float3 point = get_evaluated_point_for_target(mpt, depsgraph, /* camera= */ nullptr);
348 bke::motionpath::set_preview_location(*mpt.mpath, point);
349 /* Annoying but we have to write to the evaluated copy, otherwise the drawing would lag 1 frame
350 * behind. Since at the point of calling this function the depsgraph is already evaluated the
351 * motion path has already been copied (for CoW). It would only receive the new value after the
352 * next evaluation. */
353 bMotionPath *eval = get_evaluated_motion_path(depsgraph, mpt);
354 if (eval) {
356 }
357 }
358}
359
361{
362 for (const MPathTarget &mpt : targets) {
364 }
365}
366
367void animviz_calc_motionpaths(Depsgraph *depsgraph,
368 Scene *scene,
370 const int modified_frame)
371{
372 using namespace blender::animrig;
373 BLI_assert_msg(!DEG_is_active(depsgraph),
374 "Motion path calculation should always happen with a minimal depsgraph.");
375
376 if (targets.is_empty()) {
377 return;
378 }
379
380 for (MPathTarget &mpt : targets) {
381 AnimData *adt = BKE_animdata_from_id(&mpt.ob->id);
382
383 /* Build list of all keyframes in active action for object or pchan. */
384 mpt.keylist = ED_keylist_create();
385
386 if (adt && adt->action) {
387 /* Get pointer to animviz settings for each target. */
389
390 /* For bones it is likely that all FCurves belong to a group named after the bone. Only
391 * checking FCurves of a given group can improve performance when building the keylist. */
392 if ((mpt.pchan) && (avs->path_viewflag & MOTIONPATH_VIEW_KFACT) == 0) {
393 Action &action = adt->action->wrap();
394 bActionGroup *agrp = nullptr;
396 agrp = cbag ? cbag->channel_group_find(mpt.pchan->name) : nullptr;
397
398 if (agrp) {
399 action_group_to_keylist(adt, agrp, mpt.keylist, 0, {-FLT_MAX, FLT_MAX});
400 }
401 }
402 else {
403 build_keylist_for_target(mpt, *mpt.keylist);
404 }
405 }
407 }
408
409 Vector<Bounds<int>> evaluated_ranges;
410
411 /* We need this extra loop for the edge case when the ranges of the motion paths don't overlap.
412 * We need to touch at least one frame of each motion path to ensure it has the
413 * `MOTIONPATH_VERT_EVALUATED` flag. In practice this will almost always be the case and this
414 * loop will trigger the `continue` immediately below. That is because we evaluate all targets
415 * for every frame visited (so we only evaluate the depsgraph once per frame). */
416 for (MPathTarget &mpt : targets) {
417 const int start_frame = clamp_i(modified_frame, mpt.mpath->start_frame, mpt.mpath->end_frame);
418 /* We can safely skip the target if the start frame of it's range was already
419 * visited. That is because if we had visited it, and it would need recalculation,
420 * `motionpaths_calc_bake_target` would return `true`, meaning any neighboring frames would
421 * also be visited. */
422 if (any_range_contains(evaluated_ranges, start_frame)) {
423 continue;
424 }
425 int frame = start_frame;
426 Bounds<int> evaluated_range = {start_frame, start_frame};
427
428 bool finished_left = false;
429 bool finished_right = false;
430 /* Counts how many times the result of `motionpaths_calc_bake_target` hasn't changed existing
431 * data. */
432 int stable_result_counter = 0;
433 /* At least 2 frames need to return a result different from the currently buffered values. This
434 * is because FCURVE_SMOOTH can affect the interpolation beyond a key, but on said key it will
435 * be on the exact value of the key. */
436 constexpr int stable_result_threshold = 2;
437
438 while (!finished_left || !finished_right) {
439 /* Update relevant data for new frame. */
440 DEG_evaluate_on_framechange(depsgraph, frame);
441
442 /* Perform baking for targets. */
443 bool any_modified = false;
444 for (const MPathTarget &target : targets) {
445 any_modified |= motionpaths_calc_bake_target(target, frame, depsgraph, scene->camera);
446 }
447 if (frame == start_frame) {
448 frame--;
449 continue;
450 }
451
452 if (any_modified) {
453 stable_result_counter = 0;
454 }
455 else {
456 stable_result_counter++;
457 }
458
459 if (frame < start_frame) {
460 if (stable_result_counter >= stable_result_threshold) {
461 finished_left = true;
462 /* This has to reset the counter because we will sweep the range right of the start frame
463 * next. */
464 stable_result_counter = 0;
465 }
466 evaluated_range.min = frame;
467 }
468 else {
469 if (stable_result_counter >= stable_result_threshold) {
470 finished_right = true;
471 stable_result_counter = 0;
472 }
473 evaluated_range.max = frame;
474 }
475
476 if (!finished_left) {
477 frame = evaluated_range.min - 1;
478 }
479 else {
480 frame = evaluated_range.max + 1;
481 }
482 }
483
484 evaluated_ranges.append(evaluated_range);
485 }
486
487 /* Clear recalc flags from targets. */
488 for (MPathTarget &mpt : targets) {
489 bMotionPath *mpath = mpt.mpath;
490
491 /* Get pointer to animviz settings for each target. */
493
494 /* Clear the flag requesting recalculation of targets. */
496
497 /* Clean temp data. */
498 ED_keylist_free(mpt.keylist);
499
500 /* Free previous batches to force update. */
504 }
505}
506
507} // namespace blender
Functions and classes to work with Actions.
Functions for backward compatibility with the legacy Action API.
Functions to work with AnimData.
C++ functions to deal with Armature collections (i.e. the successor of bone layers).
Blender kernel action and pose functionality.
Camera data-block and utility functions.
#define ATTR_FALLTHROUGH
#define GPU_BATCH_DISCARD_SAFE(batch)
Definition GPU_batch.hh:199
#define GPU_VERTBUF_DISCARD_SAFE(verts)
Read Blender memory allocation and freeing.
#define BLI_assert_unreachable()
#define BLI_assert_msg(a, msg)
constexpr bool is_empty() const
Definition BLI_span.hh:515
constexpr int64_t size() const
Definition BLI_span.hh:256
void append(const T &value)
const bActionGroup * channel_group_find(StringRef name) const
void camera(KernelGlobals &kg, const ShadingData &sd, float3 &outview, float &outdepth, float &outdist)
bool assigned_action_has_keyframes(AnimData *adt)
bool fcurve_matches_collection_path(const FCurve &fcurve, StringRefNull collection_rna_path, StringRefNull data_name)
const animrig::Channelbag * channelbag_for_action_slot(const Action &action, slot_handle_t slot_handle)
Span< FCurve * > fcurves_for_assigned_action(AnimData *adt)
Definition animdata.cc:349
void clear_preview_location(bMotionPath &mpath)
void set_preview_location(bMotionPath &mpath, const float location[3])
void tag_for_recalc(bMotionPath &motion_path)
T max(const T &a, const T &b)
T abs(const T &a)
BMesh Iterators.
void animviz_clear_motionpath_preview(Span< MPathTarget > targets)
static bool any_range_contains(const Span< Bounds< int > > ranges, const int frame)
static float3 get_evaluated_point_for_target(const MPathTarget &mpt, Depsgraph &depsgraph, Object *camera)
MINLINE void copy_v3_v3(float r[3], const float a[3])
bool DEG_is_active(const Depsgraph *depsgraph)
Definition depsgraph.cc:324
static bool motionpaths_calc_bake_target(const MPathTarget &mpt, const int cframe, Depsgraph *depsgraph, Object *camera)
bool ED_keylist_selected_keys_frame_range(const AnimKeylist *keylist, Bounds< float > *r_frame_range)
@ MOTIONPATH_FLAG_BAKE_CAMERA
@ MOTIONPATH_FLAG_BHEAD
Depsgraph * DEG_graph_new(Main *bmain, Scene *scene, ViewLayer *view_layer, eEvaluationMode mode)
Definition depsgraph.cc:279
bool ANIM_bone_in_visible_collection(const bArmature *armature, const Bone *bone)
MatBase< float, 4, 4 > float4x4
const ActKeyColumn * ED_keylist_find_exact(const AnimKeylist *keylist, const float cfra)
VecBase< float, 4 > float4
void mul_m4_v3(const float M[4][4], float r[3])
AnimData * BKE_animdata_from_id(const ID *id)
Definition anim_data.cc:93
static bAnimVizSettings * animviz_target_settings_get(const MPathTarget &mpt)
void animviz_build_motionpath_targets(Object *ob, Vector< MPathTarget > &r_targets)
void fcurve_to_keylist(AnimData *adt, FCurve *fcu, AnimKeylist *keylist, const int saction_flag, float2 range, const bool use_nla_remapping)
static float3 transform_mpath_point_to_camera(Depsgraph &depsgraph, Object &camera, const float3 point)
Depsgraph * animviz_depsgraph_build(Main *bmain, Scene *scene, ViewLayer *view_layer, const Span< MPathTarget > targets)
void BKE_camera_multiview_window_matrix(const struct RenderData *rd, const struct Object *camera, const char *viewname, float r_winmat[4][4])
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
void DEG_graph_build_from_ids(Depsgraph *graph, Span< ID * > ids)
void action_group_to_keylist(AnimData *adt, bActionGroup *agrp, AnimKeylist *keylist, const int saction_flag, float2 range)
void ED_keylist_prepare_for_direct_access(AnimKeylist *keylist)
void animviz_calc_motionpaths(Depsgraph *depsgraph, Scene *scene, MutableSpan< MPathTarget > targets, const int modified_frame)
@ DAG_EVAL_VIEWPORT
AnimKeylist * ED_keylist_create()
static void build_keylist_for_target(MPathTarget &target, AnimKeylist &keylist)
void animviz_motionpath_compute_range(Object *ob, Scene *scene)
@ MOTIONPATH_VERT_EVALUATED
@ MOTIONPATH_RANGE_KEYS_ALL
@ MOTIONPATH_RANGE_MANUAL
@ MOTIONPATH_RANGE_KEYS_SELECTED
static bMotionPath * get_evaluated_motion_path(Depsgraph &depsgraph, const MPathTarget &mpt)
Scene * DEG_get_input_scene(const Depsgraph *graph)
void DEG_evaluate_on_framechange(Depsgraph *graph, float frame, DepsgraphEvaluateSyncWriteback sync_writeback=DEG_EVALUATE_SYNC_WRITEBACK_NO)
static CLG_LogRef LOG
Definition logging.cpp:12
void ED_keylist_free(AnimKeylist *keylist)
VecBase< float, 3 > float3
MINLINE int clamp_i(int value, int min, int max)
bPoseChannel * BKE_pose_channel_find_name(const bPose *pose, const char *name)
bool ED_keylist_all_keys_frame_range(const AnimKeylist *keylist, Bounds< float > *r_frame_range)
void animviz_update_motionpath_preview(Depsgraph &depsgraph, Span< MPathTarget > targets)
AnimKeylist * keylist
bMotionPath * mpath
bPoseChannel * pchan
const c_style_mat & ptr() const
bAnimVizSettings avs
bMotionPath * mpath
struct AnimData * adt
struct bPose * pose
struct Object * camera
struct RenderData r
eMotionPath_Ranges path_range
eMotionPaths_ViewFlag path_viewflag
eAnimViz_RecalcFlags recalc
eMotionPathVert_Flag flag
eMotionPath_Flag flag
bMotionPathVert * points
gpu::VertBuf * points_vbo
bAnimVizSettings avs
ListBaseT< bPoseChannel > chanbase