2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * The Original Code is Copyright (C) 2009 Blender Foundation, Joshua Leung
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): Joshua Leung (full recode)
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/fcurve.c
40 #include "MEM_guardedalloc.h"
42 #include "DNA_anim_types.h"
43 #include "DNA_constraint_types.h"
44 #include "DNA_object_types.h"
46 #include "BLI_blenlib.h"
48 #include "BLI_easing.h"
49 #include "BLI_threads.h"
50 #include "BLI_string_utils.h"
51 #include "BLI_utildefines.h"
53 #include "BLT_translation.h"
55 #include "BKE_fcurve.h"
56 #include "BKE_animsys.h"
57 #include "BKE_action.h"
58 #include "BKE_armature.h"
59 #include "BKE_constraint.h"
60 #include "BKE_context.h"
61 #include "BKE_curve.h"
62 #include "BKE_global.h"
63 #include "BKE_object.h"
66 #include "RNA_access.h"
69 #include "BPY_extern.h"
72 #define SMALL -1.0e-10
76 static ThreadMutex python_driver_lock = BLI_MUTEX_INITIALIZER;
79 /* ************************** Data-Level Functions ************************* */
81 /* ---------------------- Freeing --------------------------- */
83 /* Frees the F-Curve itself too, so make sure BLI_remlink is called before calling this... */
84 void free_fcurve(FCurve *fcu)
90 MEM_SAFE_FREE(fcu->bezt);
91 MEM_SAFE_FREE(fcu->fpt);
93 /* free RNA-path, as this were allocated when getting the path string */
94 MEM_SAFE_FREE(fcu->rna_path);
96 /* free extra data - i.e. modifiers, and driver */
97 fcurve_free_driver(fcu);
98 free_fmodifiers(&fcu->modifiers);
100 /* free f-curve itself */
104 /* Frees a list of F-Curves */
105 void free_fcurves(ListBase *list)
113 /* free data - no need to call remlink before freeing each curve,
114 * as we store reference to next, and freeing only touches the curve
117 for (fcu = list->first; fcu; fcu = fcn) {
122 /* clear pointers just in case */
123 BLI_listbase_clear(list);
126 /* ---------------------- Copy --------------------------- */
128 /* duplicate an F-Curve */
129 FCurve *copy_fcurve(const FCurve *fcu)
138 fcu_d = MEM_dupallocN(fcu);
140 fcu_d->next = fcu_d->prev = NULL;
143 /* copy curve data */
144 fcu_d->bezt = MEM_dupallocN(fcu_d->bezt);
145 fcu_d->fpt = MEM_dupallocN(fcu_d->fpt);
148 fcu_d->rna_path = MEM_dupallocN(fcu_d->rna_path);
151 fcu_d->driver = fcurve_copy_driver(fcu_d->driver);
154 copy_fmodifiers(&fcu_d->modifiers, &fcu->modifiers);
156 /* return new data */
160 /* duplicate a list of F-Curves */
161 void copy_fcurves(ListBase *dst, ListBase *src)
166 if (ELEM(NULL, dst, src))
169 /* clear destination list first */
170 BLI_listbase_clear(dst);
172 /* copy one-by-one */
173 for (sfcu = src->first; sfcu; sfcu = sfcu->next) {
174 dfcu = copy_fcurve(sfcu);
175 BLI_addtail(dst, dfcu);
179 /* ----------------- Finding F-Curves -------------------------- */
181 /* high level function to get an fcurve from C without having the rna */
182 FCurve *id_data_find_fcurve(ID *id, void *data, StructRNA *type, const char *prop_name, int index, bool *r_driven)
185 AnimData *adt = BKE_animdata_from_id(id);
196 /* only use the current action ??? */
197 if (ELEM(NULL, adt, adt->action))
200 RNA_pointer_create(id, type, data, &ptr);
201 prop = RNA_struct_find_property(&ptr, prop_name);
204 path = RNA_path_from_ID_to_property(&ptr, prop);
207 /* animation takes priority over drivers */
208 if ((adt->action) && (adt->action->curves.first))
209 fcu = list_find_fcurve(&adt->action->curves, path, index);
211 /* if not animated, check if driven */
212 if ((fcu == NULL) && (adt->drivers.first)) {
213 fcu = list_find_fcurve(&adt->drivers, path, index);
227 /* Find the F-Curve affecting the given RNA-access path + index, in the list of F-Curves provided */
228 FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_index)
233 if (ELEM(NULL, list, rna_path) || (array_index < 0) )
236 /* check paths of curves, then array indices... */
237 for (fcu = list->first; fcu; fcu = fcu->next) {
238 /* simple string-compare (this assumes that they have the same root...) */
239 if (fcu->rna_path && STREQ(fcu->rna_path, rna_path)) {
240 /* now check indices */
241 if (fcu->array_index == array_index)
250 /* quick way to loop over all fcurves of a given 'path' */
251 FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[])
256 if (ELEM(NULL, fcu_iter, rna_path))
259 /* check paths of curves, then array indices... */
260 for (fcu = fcu_iter; fcu; fcu = fcu->next) {
261 /* simple string-compare (this assumes that they have the same root...) */
262 if (fcu->rna_path && STREQ(fcu->rna_path, rna_path)) {
271 /* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated
273 * - dst: list of LinkData's matching the criteria returned.
274 * List must be freed after use, and is assumed to be empty when passed.
275 * - src: list of F-Curves to search through
277 * - dataPrefix: i.e. 'pose.bones[' or 'nodes['
278 * - dataName: name of entity within "" immediately following the prefix
280 int list_find_data_fcurves(ListBase *dst, ListBase *src, const char *dataPrefix, const char *dataName)
286 if (ELEM(NULL, dst, src, dataPrefix, dataName))
288 else if ((dataPrefix[0] == 0) || (dataName[0] == 0))
291 /* search each F-Curve one by one */
292 for (fcu = src->first; fcu; fcu = fcu->next) {
293 /* check if quoted string matches the path */
294 if ((fcu->rna_path) && strstr(fcu->rna_path, dataPrefix)) {
295 char *quotedName = BLI_str_quoted_substrN(fcu->rna_path, dataPrefix);
298 /* check if the quoted name matches the required name */
299 if (STREQ(quotedName, dataName)) {
300 LinkData *ld = MEM_callocN(sizeof(LinkData), __func__);
303 BLI_addtail(dst, ld);
308 /* always free the quoted string, since it needs freeing */
309 MEM_freeN(quotedName);
314 /* return the number of matches */
318 FCurve *rna_get_fcurve(
319 PointerRNA *ptr, PropertyRNA *prop, int rnaindex,
320 AnimData **r_adt, bAction **r_action, bool *r_driven, bool *r_special)
322 return rna_get_fcurve_context_ui(NULL, ptr, prop, rnaindex, r_adt, r_action, r_driven, r_special);
325 FCurve *rna_get_fcurve_context_ui(
326 bContext *C, PointerRNA *ptr, PropertyRNA *prop, int rnaindex,
327 AnimData **r_animdata, bAction **r_action, bool *r_driven, bool *r_special)
330 PointerRNA tptr = *ptr;
335 if (r_animdata) *r_animdata = NULL;
336 if (r_action) *r_action = NULL;
338 /* Special case for NLA Control Curves... */
339 if (BKE_nlastrip_has_curves_for_property(ptr, prop)) {
340 NlaStrip *strip = (NlaStrip *)ptr->data;
342 /* Set the special flag, since it cannot be a normal action/driver
343 * if we've been told to start looking here...
347 /* The F-Curve either exists or it doesn't here... */
348 fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), rnaindex);
352 /* there must be some RNA-pointer + property combon */
353 if (prop && tptr.id.data && RNA_property_animateable(&tptr, prop)) {
354 AnimData *adt = BKE_animdata_from_id(tptr.id.data);
355 int step = C ? 2 : 1; /* Always 1 in case we have no context (can't check in 'ancestors' of given RNA ptr). */
359 path = BKE_animdata_driver_path_hack(C, &tptr, prop, NULL);
360 adt = BKE_animdata_from_id(tptr.id.data);
364 /* Standard F-Curve - Animation (Action) or Drivers */
365 while (adt && step--) {
366 if ((adt->action && adt->action->curves.first) || (adt->drivers.first)) {
367 /* XXX this function call can become a performance bottleneck */
369 path = RNA_path_from_ID_to_property(&tptr, prop);
372 // XXX: the logic here is duplicated with a function up above
374 /* animation takes priority over drivers */
375 if (adt->action && adt->action->curves.first) {
376 fcu = list_find_fcurve(&adt->action->curves, path, rnaindex);
379 *r_action = adt->action;
382 /* if not animated, check if driven */
383 if (!fcu && (adt->drivers.first)) {
384 fcu = list_find_fcurve(&adt->drivers, path, rnaindex);
387 if (r_animdata) *r_animdata = adt;
392 if (fcu && r_action) {
393 if (r_animdata) *r_animdata = adt;
394 *r_action = adt->action;
398 char *tpath = BKE_animdata_driver_path_hack(C, &tptr, prop, path);
399 if (tpath && tpath != path) {
402 adt = BKE_animdata_from_id(tptr.id.data);
417 /* ----------------- Finding Keyframes/Extents -------------------------- */
419 /* Binary search algorithm for finding where to insert BezTriple, with optional argument for precision required.
420 * Returns the index to insert at (data already at that index will be offset if replace is 0)
422 static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arraylen, float threshold, bool *r_replace)
424 int start = 0, end = arraylen;
425 int loopbreaker = 0, maxloop = arraylen * 2;
427 /* initialize replace-flag first */
430 /* sneaky optimizations (don't go through searching process if...):
431 * - keyframe to be added is to be added out of current bounds
432 * - keyframe to be added would replace one of the existing ones on bounds
434 if ((arraylen <= 0) || (array == NULL)) {
435 printf("Warning: binarysearch_bezt_index() encountered invalid array\n");
439 /* check whether to add before/after/on */
442 /* 'First' Keyframe (when only one keyframe, this case is used) */
443 framenum = array[0].vec[1][0];
444 if (IS_EQT(frame, framenum, threshold)) {
448 else if (frame < framenum)
451 /* 'Last' Keyframe */
452 framenum = array[(arraylen - 1)].vec[1][0];
453 if (IS_EQT(frame, framenum, threshold)) {
455 return (arraylen - 1);
457 else if (frame > framenum)
462 /* most of the time, this loop is just to find where to put it
463 * 'loopbreaker' is just here to prevent infinite loops
465 for (loopbreaker = 0; (start <= end) && (loopbreaker < maxloop); loopbreaker++) {
466 /* compute and get midpoint */
467 int mid = start + ((end - start) / 2); /* we calculate the midpoint this way to avoid int overflows... */
468 float midfra = array[mid].vec[1][0];
470 /* check if exactly equal to midpoint */
471 if (IS_EQT(frame, midfra, threshold)) {
476 /* repeat in upper/lower half */
479 else if (frame < midfra)
483 /* print error if loop-limit exceeded */
484 if (loopbreaker == (maxloop - 1)) {
485 printf("Error: binarysearch_bezt_index() was taking too long\n");
487 /* include debug info */
488 printf("\tround = %d: start = %d, end = %d, arraylen = %d\n", loopbreaker, start, end, arraylen);
491 /* not found, so return where to place it */
496 /* Binary search algorithm for finding where to insert BezTriple. (for use by insert_bezt_fcurve)
497 * Returns the index to insert at (data already at that index will be offset if replace is 0)
499 int binarysearch_bezt_index(BezTriple array[], float frame, int arraylen, bool *r_replace)
501 /* this is just a wrapper which uses the default threshold */
502 return binarysearch_bezt_index_ex(array, frame, arraylen, BEZT_BINARYSEARCH_THRESH, r_replace);
505 /* ...................................... */
507 /* helper for calc_fcurve_* functions -> find first and last BezTriple to be used */
508 static short get_fcurve_end_keyframes(FCurve *fcu, BezTriple **first, BezTriple **last,
509 const bool do_sel_only)
518 if (fcu->bezt == NULL)
521 /* only include selected items? */
526 /* find first selected */
528 for (i = 0; i < fcu->totvert; bezt++, i++) {
529 if (BEZT_ISSEL_ANY(bezt)) {
536 /* find last selected */
537 bezt = ARRAY_LAST_ITEM(fcu->bezt, BezTriple, fcu->totvert);
538 for (i = 0; i < fcu->totvert; bezt--, i++) {
539 if (BEZT_ISSEL_ANY(bezt)) {
547 /* just full array */
549 *last = ARRAY_LAST_ITEM(fcu->bezt, BezTriple, fcu->totvert);
557 /* Calculate the extents of F-Curve's data */
558 bool calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, float *ymax,
559 const bool do_sel_only, const bool include_handles)
561 float xminv = 999999999.0f, xmaxv = -999999999.0f;
562 float yminv = 999999999.0f, ymaxv = -999999999.0f;
563 bool foundvert = false;
568 BezTriple *bezt_first = NULL, *bezt_last = NULL;
571 /* get endpoint keyframes */
572 foundvert = get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only);
575 BLI_assert(bezt_last != NULL);
577 if (include_handles) {
578 xminv = min_fff(xminv, bezt_first->vec[0][0], bezt_first->vec[1][0]);
579 xmaxv = max_fff(xmaxv, bezt_last->vec[1][0], bezt_last->vec[2][0]);
582 xminv = min_ff(xminv, bezt_first->vec[1][0]);
583 xmaxv = max_ff(xmaxv, bezt_last->vec[1][0]);
588 /* only loop over keyframes to find extents for values if needed */
590 BezTriple *bezt, *prevbezt = NULL;
592 for (bezt = fcu->bezt, i = 0; i < fcu->totvert; prevbezt = bezt, bezt++, i++) {
593 if ((do_sel_only == false) || BEZT_ISSEL_ANY(bezt)) {
594 /* keyframe itself */
595 yminv = min_ff(yminv, bezt->vec[1][1]);
596 ymaxv = max_ff(ymaxv, bezt->vec[1][1]);
598 if (include_handles) {
599 /* left handle - only if applicable
600 * NOTE: for the very first keyframe, the left handle actually has no bearings on anything
602 if (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ)) {
603 yminv = min_ff(yminv, bezt->vec[0][1]);
604 ymaxv = max_ff(ymaxv, bezt->vec[0][1]);
607 /* right handle - only if applicable */
608 if (bezt->ipo == BEZT_IPO_BEZ) {
609 yminv = min_ff(yminv, bezt->vec[2][1]);
610 ymaxv = max_ff(ymaxv, bezt->vec[2][1]);
620 /* frame range can be directly calculated from end verts */
622 xminv = min_ff(xminv, fcu->fpt[0].vec[0]);
623 xmaxv = max_ff(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]);
626 /* only loop over keyframes to find extents for values if needed */
630 for (fpt = fcu->fpt, i = 0; i < fcu->totvert; fpt++, i++) {
631 if (fpt->vec[1] < yminv)
633 if (fpt->vec[1] > ymaxv)
643 if (xmin) *xmin = xminv;
644 if (xmax) *xmax = xmaxv;
646 if (ymin) *ymin = yminv;
647 if (ymax) *ymax = ymaxv;
650 if (G.debug & G_DEBUG)
651 printf("F-Curve calc bounds didn't find anything, so assuming minimum bounds of 1.0\n");
653 if (xmin) *xmin = 0.0f;
654 if (xmax) *xmax = 1.0f;
656 if (ymin) *ymin = 0.0f;
657 if (ymax) *ymax = 1.0f;
663 /* Calculate the extents of F-Curve's keyframes */
664 bool calc_fcurve_range(FCurve *fcu, float *start, float *end,
665 const bool do_sel_only, const bool do_min_length)
667 float min = 999999999.0f, max = -999999999.0f;
668 bool foundvert = false;
672 BezTriple *bezt_first = NULL, *bezt_last = NULL;
674 /* get endpoint keyframes */
675 get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only);
678 BLI_assert(bezt_last != NULL);
680 min = min_ff(min, bezt_first->vec[1][0]);
681 max = max_ff(max, bezt_last->vec[1][0]);
687 min = min_ff(min, fcu->fpt[0].vec[0]);
688 max = max_ff(max, fcu->fpt[fcu->totvert - 1].vec[0]);
695 if (foundvert == false) {
700 /* minimum length is 1 frame */
712 /* ----------------- Status Checks -------------------------- */
714 /* Are keyframes on F-Curve of any use?
715 * Usability of keyframes refers to whether they should be displayed,
716 * and also whether they will have any influence on the final result.
718 bool fcurve_are_keyframes_usable(FCurve *fcu)
720 /* F-Curve must exist */
724 /* F-Curve must not have samples - samples are mutually exclusive of keyframes */
728 /* if it has modifiers, none of these should "drastically" alter the curve */
729 if (fcu->modifiers.first) {
732 /* check modifiers from last to first, as last will be more influential */
733 /* TODO: optionally, only check modifier if it is the active one... */
734 for (fcm = fcu->modifiers.last; fcm; fcm = fcm->prev) {
735 /* ignore if muted/disabled */
736 if (fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED))
741 /* clearly harmless - do nothing */
742 case FMODIFIER_TYPE_CYCLES:
743 case FMODIFIER_TYPE_STEPPED:
744 case FMODIFIER_TYPE_NOISE:
747 /* sometimes harmful - depending on whether they're "additive" or not */
748 case FMODIFIER_TYPE_GENERATOR:
750 FMod_Generator *data = (FMod_Generator *)fcm->data;
752 if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0)
756 case FMODIFIER_TYPE_FN_GENERATOR:
758 FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data;
760 if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0)
764 /* always harmful - cannot allow */
771 /* keyframes are usable */
775 bool BKE_fcurve_is_protected(FCurve *fcu)
777 return ((fcu->flag & FCURVE_PROTECTED) ||
778 ((fcu->grp) && (fcu->grp->flag & AGRP_PROTECTED)));
781 /* Can keyframes be added to F-Curve?
782 * Keyframes can only be added if they are already visible
784 bool fcurve_is_keyframable(FCurve *fcu)
786 /* F-Curve's keyframes must be "usable" (i.e. visible + have an effect on final result) */
787 if (fcurve_are_keyframes_usable(fcu) == 0)
790 /* F-Curve must currently be editable too */
791 if (BKE_fcurve_is_protected(fcu))
794 /* F-Curve is keyframable */
798 /* ***************************** Keyframe Column Tools ********************************* */
800 /* add a BezTriple to a column */
801 void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt)
805 for (ce = lb->first; ce; ce = ce->next) {
807 if (IS_EQT(ce->cfra, bezt->vec[1][0], BEZT_BINARYSEARCH_THRESH)) {
808 if (bezt->f2 & SELECT) ce->sel = bezt->f2;
811 /* should key be inserted before this column? */
812 else if (ce->cfra > bezt->vec[1][0]) break;
815 /* create a new column */
816 cen = MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem");
817 if (ce) BLI_insertlinkbefore(lb, ce, cen);
818 else BLI_addtail(lb, cen);
820 cen->cfra = bezt->vec[1][0];
824 /* ***************************** Samples Utilities ******************************* */
825 /* Some utilities for working with FPoints (i.e. 'sampled' animation curve data, such as
826 * data imported from BVH/Mocap files), which are specialized for use with high density datasets,
827 * which BezTriples/Keyframe data are ill equipped to do.
831 /* Basic sampling callback which acts as a wrapper for evaluate_fcurve()
832 * 'data' arg here is unneeded here...
834 float fcurve_samplingcb_evalcurve(FCurve *fcu, void *UNUSED(data), float evaltime)
836 /* assume any interference from drivers on the curve is intended... */
837 return evaluate_fcurve(fcu, evaltime);
841 /* Main API function for creating a set of sampled curve data, given some callback function
842 * used to retrieve the values to store.
844 void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSampleFunc sample_cb)
846 FPoint *fpt, *new_fpt;
850 /* TODO: make these tests report errors using reports not printf's */
851 if (ELEM(NULL, fcu, sample_cb)) {
852 printf("Error: No F-Curve with F-Curve Modifiers to Bake\n");
856 printf("Error: Frame range for Sampled F-Curve creation is inappropriate\n");
860 /* set up sample data */
861 fpt = new_fpt = MEM_callocN(sizeof(FPoint) * (end - start + 1), "FPoint Samples");
863 /* use the sampling callback at 1-frame intervals from start to end frames */
864 for (cfra = start; cfra <= end; cfra++, fpt++) {
865 fpt->vec[0] = (float)cfra;
866 fpt->vec[1] = sample_cb(fcu, data, (float)cfra);
869 /* free any existing sample/keyframe data on curve */
870 if (fcu->bezt) MEM_freeN(fcu->bezt);
871 if (fcu->fpt) MEM_freeN(fcu->fpt);
873 /* store the samples */
876 fcu->totvert = end - start + 1;
879 /* ***************************** F-Curve Sanity ********************************* */
880 /* The functions here are used in various parts of Blender, usually after some editing
881 * of keyframe data has occurred. They ensure that keyframe data is properly ordered and
882 * that the handles are correctly
885 /* Checks if the F-Curve has a Cycles modifier with simple settings that warrant transition smoothing */
886 bool BKE_fcurve_is_cyclic(FCurve *fcu)
888 FModifier *fcm = fcu->modifiers.first;
890 if (!fcm || fcm->type != FMODIFIER_TYPE_CYCLES)
893 if (fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED))
896 if (fcm->flag & (FMODIFIER_FLAG_RANGERESTRICT | FMODIFIER_FLAG_USEINFLUENCE))
899 FMod_Cycles *data = (FMod_Cycles *)fcm->data;
901 return data && data->after_cycles == 0 && data->before_cycles == 0 &&
902 ELEM(data->before_mode, FCM_EXTRAPOLATE_CYCLIC, FCM_EXTRAPOLATE_CYCLIC_OFFSET) &&
903 ELEM(data->after_mode, FCM_EXTRAPOLATE_CYCLIC, FCM_EXTRAPOLATE_CYCLIC_OFFSET);
906 /* Shifts 'in' by the difference in coordinates between 'to' and 'from', using 'out' as the output buffer.
907 * When 'to' and 'from' are end points of the loop, this moves the 'in' point one loop cycle.
909 static BezTriple *cycle_offset_triple(bool cycle, BezTriple *out, const BezTriple *in, const BezTriple *from, const BezTriple *to)
914 memcpy(out, in, sizeof(BezTriple));
917 sub_v3_v3v3(delta, to->vec[1], from->vec[1]);
919 for (int i = 0; i < 3; i++)
920 add_v3_v3(out->vec[i], delta);
925 /* This function recalculates the handles of an F-Curve
926 * If the BezTriples have been rearranged, sort them first before using this.
928 void calchandles_fcurve(FCurve *fcu)
930 BezTriple *bezt, *prev, *next;
931 int a = fcu->totvert;
934 * - need at least two points
936 * - only bezier-interpolation has handles (for now)
938 if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/)
941 /* if the first modifier is Cycles, smooth the curve through the cycle */
942 BezTriple *first = &fcu->bezt[0], *last = &fcu->bezt[fcu->totvert - 1];
945 bool cycle = BKE_fcurve_is_cyclic(fcu) && BEZT_IS_AUTOH(first) && BEZT_IS_AUTOH(last);
947 /* get initial pointers */
949 prev = cycle_offset_triple(cycle, &tmp, &fcu->bezt[fcu->totvert - 2], last, first);
952 /* loop over all beztriples, adjusting handles */
954 /* clamp timing of handles to be on either side of beztriple */
955 if (bezt->vec[0][0] > bezt->vec[1][0]) bezt->vec[0][0] = bezt->vec[1][0];
956 if (bezt->vec[2][0] < bezt->vec[1][0]) bezt->vec[2][0] = bezt->vec[1][0];
958 /* calculate auto-handles */
959 BKE_nurb_handle_calc(bezt, prev, next, true, fcu->auto_smoothing);
961 /* for automatic ease in and out */
962 if (BEZT_IS_AUTOH(bezt) && !cycle) {
963 /* only do this on first or last beztriple */
964 if ((a == 0) || (a == fcu->totvert - 1)) {
965 /* set both handles to have same horizontal value as keyframe */
966 if (fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) {
967 bezt->vec[0][1] = bezt->vec[2][1] = bezt->vec[1][1];
968 /* remember that these keyframes are special, they don't need to be adjusted */
969 bezt->f5 = HD_AUTOTYPE_SPECIAL;
974 /* avoid total smoothing failure on duplicate keyframes (can happen during grab) */
975 if (prev && prev->vec[1][0] >= bezt->vec[1][0]) {
976 prev->f5 = bezt->f5 = HD_AUTOTYPE_SPECIAL;
979 /* advance pointers for next iteration */
983 next = cycle_offset_triple(cycle, &tmp, &fcu->bezt[1], first, last);
992 /* if cyclic extrapolation and Auto Clamp has triggered, ensure it is symmetric */
993 if (cycle && (first->f5 != HD_AUTOTYPE_NORMAL || last->f5 != HD_AUTOTYPE_NORMAL)) {
994 first->vec[0][1] = first->vec[2][1] = first->vec[1][1];
995 last->vec[0][1] = last->vec[2][1] = last->vec[1][1];
996 first->f5 = last->f5 = HD_AUTOTYPE_SPECIAL;
999 /* do a second pass for auto handle: compute the handle to have 0 accelaration step */
1000 if (fcu->auto_smoothing != FCURVE_SMOOTH_NONE) {
1001 BKE_nurb_handle_smooth_fcurve(fcu->bezt, fcu->totvert, cycle);
1005 void testhandles_fcurve(FCurve *fcu, const bool use_handle)
1010 /* only beztriples have handles (bpoints don't though) */
1011 if (ELEM(NULL, fcu, fcu->bezt))
1014 /* loop over beztriples */
1015 for (a = 0, bezt = fcu->bezt; a < fcu->totvert; a++, bezt++) {
1016 BKE_nurb_bezt_handle_test(bezt, use_handle);
1019 /* recalculate handles */
1020 calchandles_fcurve(fcu);
1023 /* This function sorts BezTriples so that they are arranged in chronological order,
1024 * as tools working on F-Curves expect that the BezTriples are in order.
1026 void sort_time_fcurve(FCurve *fcu)
1030 /* keep adjusting order of beztriples until nothing moves (bubble-sort) */
1034 /* currently, will only be needed when there are beztriples */
1039 /* loop over ALL points to adjust position in array and recalculate handles */
1040 for (a = 0, bezt = fcu->bezt; a < fcu->totvert; a++, bezt++) {
1041 /* check if thee's a next beztriple which we could try to swap with current */
1042 if (a < (fcu->totvert - 1)) {
1043 /* swap if one is after the other (and indicate that order has changed) */
1044 if (bezt->vec[1][0] > (bezt + 1)->vec[1][0]) {
1045 SWAP(BezTriple, *bezt, *(bezt + 1));
1049 /* if either one of both of the points exceeds crosses over the keyframe time... */
1050 if ( (bezt->vec[0][0] > bezt->vec[1][0]) && (bezt->vec[2][0] < bezt->vec[1][0]) ) {
1051 /* swap handles if they have switched sides for some reason */
1052 swap_v2_v2(bezt->vec[0], bezt->vec[2]);
1056 CLAMP_MAX(bezt->vec[0][0], bezt->vec[1][0]);
1057 CLAMP_MIN(bezt->vec[2][0], bezt->vec[1][0]);
1065 /* This function tests if any BezTriples are out of order, thus requiring a sort */
1066 short test_time_fcurve(FCurve *fcu)
1074 /* currently, only need to test beztriples */
1078 /* loop through all BezTriples, stopping when one exceeds the one after it */
1079 for (a = 0, bezt = fcu->bezt; a < (fcu->totvert - 1); a++, bezt++) {
1080 if (bezt->vec[1][0] > (bezt + 1)->vec[1][0])
1084 else if (fcu->fpt) {
1087 /* loop through all FPoints, stopping when one exceeds the one after it */
1088 for (a = 0, fpt = fcu->fpt; a < (fcu->totvert - 1); a++, fpt++) {
1089 if (fpt->vec[0] > (fpt + 1)->vec[0])
1094 /* none need any swapping */
1098 /* ***************************** Drivers ********************************* */
1100 /* Driver Variables --------------------------- */
1102 /* TypeInfo for Driver Variables (dvti) */
1103 typedef struct DriverVarTypeInfo {
1104 /* evaluation callback */
1105 float (*get_value)(ChannelDriver *driver, DriverVar *dvar);
1107 /* allocation of target slots */
1108 int num_targets; /* number of target slots required */
1109 const char *target_names[MAX_DRIVER_TARGETS]; /* UI names that should be given to the slots */
1110 short target_flags[MAX_DRIVER_TARGETS]; /* flags defining the requirements for each slot */
1111 } DriverVarTypeInfo;
1113 /* Macro to begin definitions */
1114 #define BEGIN_DVAR_TYPEDEF(type) \
1117 /* Macro to end definitions */
1118 #define END_DVAR_TYPEDEF \
1123 static ID *dtar_id_ensure_proxy_from(ID *id)
1125 if (id && GS(id->name) == ID_OB && ((Object *)id)->proxy_from)
1126 return (ID *)(((Object *)id)->proxy_from);
1130 /* Helper function to obtain a value using RNA from the specified source (for evaluating drivers) */
1131 static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar)
1133 PointerRNA id_ptr, ptr;
1140 if (ELEM(NULL, driver, dtar))
1143 id = dtar_id_ensure_proxy_from(dtar->id);
1145 /* error check for missing pointer... */
1147 if (G.debug & G_DEBUG) {
1148 printf("Error: driver has an invalid target to use (path = %s)\n", dtar->rna_path);
1151 driver->flag |= DRIVER_FLAG_INVALID;
1152 dtar->flag |= DTAR_FLAG_INVALID;
1156 /* get RNA-pointer for the ID-block given in target */
1157 RNA_id_pointer_create(id, &id_ptr);
1159 /* get property to read from, and get value as appropriate */
1160 if (RNA_path_resolve_property_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) {
1161 if (RNA_property_array_check(prop)) {
1163 if ((index >= 0) && (index < RNA_property_array_length(&ptr, prop))) {
1164 switch (RNA_property_type(prop)) {
1166 value = (float)RNA_property_boolean_get_index(&ptr, prop, index);
1169 value = (float)RNA_property_int_get_index(&ptr, prop, index);
1172 value = RNA_property_float_get_index(&ptr, prop, index);
1180 if (G.debug & G_DEBUG) {
1181 printf("Driver Evaluation Error: array index is out of bounds for %s -> %s (%d)",
1182 id->name, dtar->rna_path, index);
1185 driver->flag |= DRIVER_FLAG_INVALID;
1186 dtar->flag |= DTAR_FLAG_INVALID;
1192 switch (RNA_property_type(prop)) {
1194 value = (float)RNA_property_boolean_get(&ptr, prop);
1197 value = (float)RNA_property_int_get(&ptr, prop);
1200 value = RNA_property_float_get(&ptr, prop);
1203 value = (float)RNA_property_enum_get(&ptr, prop);
1211 /* path couldn't be resolved */
1212 if (G.debug & G_DEBUG) {
1213 printf("Driver Evaluation Error: cannot resolve target for %s -> %s\n", id->name, dtar->rna_path);
1216 driver->flag |= DRIVER_FLAG_INVALID;
1217 dtar->flag |= DTAR_FLAG_INVALID;
1221 /* if we're still here, we should be ok... */
1222 dtar->flag &= ~DTAR_FLAG_INVALID;
1227 * Same as 'dtar_get_prop_val'. but get the RNA property.
1229 bool driver_get_variable_property(
1230 ChannelDriver *driver, DriverTarget *dtar,
1231 PointerRNA *r_ptr, PropertyRNA **r_prop, int *r_index)
1240 if (ELEM(NULL, driver, dtar))
1243 id = dtar_id_ensure_proxy_from(dtar->id);
1245 /* error check for missing pointer... */
1247 if (G.debug & G_DEBUG) {
1248 printf("Error: driver has an invalid target to use (path = %s)\n", dtar->rna_path);
1251 driver->flag |= DRIVER_FLAG_INVALID;
1252 dtar->flag |= DTAR_FLAG_INVALID;
1256 /* get RNA-pointer for the ID-block given in target */
1257 RNA_id_pointer_create(id, &id_ptr);
1259 /* get property to read from, and get value as appropriate */
1260 if (dtar->rna_path == NULL || dtar->rna_path[0] == '\0') {
1261 ptr = PointerRNA_NULL;
1262 prop = NULL; /* ok */
1264 else if (RNA_path_resolve_property_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) {
1268 /* path couldn't be resolved */
1269 if (G.debug & G_DEBUG) {
1270 printf("Driver Evaluation Error: cannot resolve target for %s -> %s\n", id->name, dtar->rna_path);
1273 ptr = PointerRNA_NULL;
1277 driver->flag |= DRIVER_FLAG_INVALID;
1278 dtar->flag |= DTAR_FLAG_INVALID;
1286 /* if we're still here, we should be ok... */
1287 dtar->flag &= ~DTAR_FLAG_INVALID;
1292 /* Helper function to obtain a pointer to a Pose Channel (for evaluating drivers) */
1293 static bPoseChannel *dtar_get_pchan_ptr(ChannelDriver *driver, DriverTarget *dtar)
1297 if (ELEM(NULL, driver, dtar))
1300 id = dtar_id_ensure_proxy_from(dtar->id);
1302 /* check if the ID here is a valid object */
1303 if (id && GS(id->name)) {
1304 Object *ob = (Object *)id;
1306 /* get pose, and subsequently, posechannel */
1307 return BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1310 /* cannot find a posechannel this way */
1316 static short driver_check_valid_targets(ChannelDriver *driver, DriverVar *dvar)
1318 short valid_targets = 0;
1320 DRIVER_TARGETS_USED_LOOPER(dvar)
1322 Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1324 /* check if this target has valid data */
1325 if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) {
1326 /* invalid target, so will not have enough targets */
1327 driver->flag |= DRIVER_FLAG_INVALID;
1328 dtar->flag |= DTAR_FLAG_INVALID;
1331 /* target seems to be OK now... */
1332 dtar->flag &= ~DTAR_FLAG_INVALID;
1336 DRIVER_TARGETS_LOOPER_END
1338 return valid_targets;
1343 /* evaluate 'single prop' driver variable */
1344 static float dvar_eval_singleProp(ChannelDriver *driver, DriverVar *dvar)
1346 /* just evaluate the first target slot */
1347 return dtar_get_prop_val(driver, &dvar->targets[0]);
1350 /* evaluate 'rotation difference' driver variable */
1351 static float dvar_eval_rotDiff(ChannelDriver *driver, DriverVar *dvar)
1353 short valid_targets = driver_check_valid_targets(driver, dvar);
1355 /* make sure we have enough valid targets to use - all or nothing for now... */
1356 if (driver_check_valid_targets(driver, dvar) != 2) {
1357 if (G.debug & G_DEBUG) {
1358 printf("RotDiff DVar: not enough valid targets (n = %d) (a = %p, b = %p)\n",
1359 valid_targets, dvar->targets[0].id, dvar->targets[1].id);
1366 /* NOTE: for now, these are all just worldspace */
1367 for (int i = 0; i < 2; i++) {
1368 /* get pointer to loc values to store in */
1369 DriverTarget *dtar = &dvar->targets[i];
1370 Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1371 bPoseChannel *pchan;
1373 /* after the checks above, the targets should be valid here... */
1374 BLI_assert((ob != NULL) && (GS(ob->id.name) == ID_OB));
1376 /* try to get posechannel */
1377 pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1379 /* check if object or bone */
1382 mat[i] = pchan->pose_mat;
1390 float q1[4], q2[4], quat[4], angle;
1392 /* use the final posed locations */
1393 mat4_to_quat(q1, mat[0]);
1394 mat4_to_quat(q2, mat[1]);
1396 invert_qt_normalized(q1);
1397 mul_qt_qtqt(quat, q1, q2);
1398 angle = 2.0f * (saacos(quat[0]));
1401 return (angle > (float)M_PI) ? (float)((2.0f * (float)M_PI) - angle) : (float)(angle);
1404 /* evaluate 'location difference' driver variable */
1405 /* TODO: this needs to take into account space conversions... */
1406 static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar)
1408 float loc1[3] = {0.0f, 0.0f, 0.0f};
1409 float loc2[3] = {0.0f, 0.0f, 0.0f};
1410 short valid_targets = driver_check_valid_targets(driver, dvar);
1412 /* make sure we have enough valid targets to use - all or nothing for now... */
1413 if (valid_targets < dvar->num_targets) {
1414 if (G.debug & G_DEBUG) {
1415 printf("LocDiff DVar: not enough valid targets (n = %d) (a = %p, b = %p)\n",
1416 valid_targets, dvar->targets[0].id, dvar->targets[1].id);
1421 /* SECOND PASS: get two location values */
1422 /* NOTE: for now, these are all just worldspace */
1423 DRIVER_TARGETS_USED_LOOPER(dvar)
1425 /* get pointer to loc values to store in */
1426 Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1427 bPoseChannel *pchan;
1430 /* after the checks above, the targets should be valid here... */
1431 BLI_assert((ob != NULL) && (GS(ob->id.name) == ID_OB));
1433 /* try to get posechannel */
1434 pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1436 /* check if object or bone */
1439 if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1440 if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1443 /* extract transform just like how the constraints do it! */
1444 copy_m4_m4(mat, pchan->pose_mat);
1445 BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false);
1447 /* ... and from that, we get our transform */
1448 copy_v3_v3(tmp_loc, mat[3]);
1451 /* transform space (use transform values directly) */
1452 copy_v3_v3(tmp_loc, pchan->loc);
1456 /* convert to worldspace */
1457 copy_v3_v3(tmp_loc, pchan->pose_head);
1458 mul_m4_v3(ob->obmat, tmp_loc);
1463 if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1464 if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1465 /* XXX: this should practically be the same as transform space... */
1468 /* extract transform just like how the constraints do it! */
1469 copy_m4_m4(mat, ob->obmat);
1470 BKE_constraint_mat_convertspace(ob, NULL, mat, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL, false);
1472 /* ... and from that, we get our transform */
1473 copy_v3_v3(tmp_loc, mat[3]);
1476 /* transform space (use transform values directly) */
1477 copy_v3_v3(tmp_loc, ob->loc);
1482 copy_v3_v3(tmp_loc, ob->obmat[3]);
1486 /* copy the location to the right place */
1488 copy_v3_v3(loc2, tmp_loc);
1491 copy_v3_v3(loc1, tmp_loc);
1494 DRIVER_TARGETS_LOOPER_END
1497 /* if we're still here, there should now be two targets to use,
1498 * so just take the length of the vector between these points
1500 return len_v3v3(loc1, loc2);
1503 /* evaluate 'transform channel' driver variable */
1504 static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar)
1506 DriverTarget *dtar = &dvar->targets[0];
1507 Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1508 bPoseChannel *pchan;
1510 float oldEul[3] = {0.0f, 0.0f, 0.0f};
1511 bool use_eulers = false;
1512 short rot_order = ROT_MODE_EUL;
1514 /* check if this target has valid data */
1515 if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) {
1516 /* invalid target, so will not have enough targets */
1517 driver->flag |= DRIVER_FLAG_INVALID;
1518 dtar->flag |= DTAR_FLAG_INVALID;
1522 /* target should be valid now */
1523 dtar->flag &= ~DTAR_FLAG_INVALID;
1526 /* try to get posechannel */
1527 pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1529 /* check if object or bone, and get transform matrix accordingly
1530 * - "useEulers" code is used to prevent the problems associated with non-uniqueness
1531 * of euler decomposition from matrices [#20870]
1532 * - localspace is for [#21384], where parent results are not wanted
1533 * but local-consts is for all the common "corrective-shapes-for-limbs" situations
1537 if (pchan->rotmode > 0) {
1538 copy_v3_v3(oldEul, pchan->eul);
1539 rot_order = pchan->rotmode;
1543 if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1544 if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1545 /* just like how the constraints do it! */
1546 copy_m4_m4(mat, pchan->pose_mat);
1547 BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false);
1550 /* specially calculate local matrix, since chan_mat is not valid
1551 * since it stores delta transform of pose_mat so that deforms work
1552 * so it cannot be used here for "transform" space
1554 BKE_pchan_to_mat4(pchan, mat);
1558 /* worldspace matrix */
1559 mul_m4_m4m4(mat, ob->obmat, pchan->pose_mat);
1564 if (ob->rotmode > 0) {
1565 copy_v3_v3(oldEul, ob->rot);
1566 rot_order = ob->rotmode;
1570 if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1571 if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1572 /* just like how the constraints do it! */
1573 copy_m4_m4(mat, ob->obmat);
1574 BKE_constraint_mat_convertspace(ob, NULL, mat, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL, false);
1577 /* transforms to matrix */
1578 BKE_object_to_mat4(ob, mat);
1582 /* worldspace matrix - just the good-old one */
1583 copy_m4_m4(mat, ob->obmat);
1587 /* check which transform */
1588 if (dtar->transChan >= MAX_DTAR_TRANSCHAN_TYPES) {
1589 /* not valid channel */
1592 else if (dtar->transChan >= DTAR_TRANSCHAN_SCALEX) {
1593 /* Extract scale, and choose the right axis,
1594 * inline 'mat4_to_size'. */
1595 return len_v3(mat[dtar->transChan - DTAR_TRANSCHAN_SCALEX]);
1597 else if (dtar->transChan >= DTAR_TRANSCHAN_ROTX) {
1598 /* extract rotation as eulers (if needed)
1599 * - definitely if rotation order isn't eulers already
1600 * - if eulers, then we have 2 options:
1601 * a) decompose transform matrix as required, then try to make eulers from
1602 * there compatible with original values
1603 * b) [NOT USED] directly use the original values (no decomposition)
1604 * - only an option for "transform space", if quality is really bad with a)
1608 mat4_to_eulO(eul, rot_order, mat);
1611 compatible_eul(eul, oldEul);
1614 return eul[dtar->transChan - DTAR_TRANSCHAN_ROTX];
1617 /* extract location and choose right axis */
1618 return mat[3][dtar->transChan];
1624 /* Table of Driver Varaiable Type Info Data */
1625 static DriverVarTypeInfo dvar_types[MAX_DVAR_TYPES] = {
1626 BEGIN_DVAR_TYPEDEF(DVAR_TYPE_SINGLE_PROP)
1627 dvar_eval_singleProp, /* eval callback */
1628 1, /* number of targets used */
1629 {"Property"}, /* UI names for targets */
1633 BEGIN_DVAR_TYPEDEF(DVAR_TYPE_ROT_DIFF)
1634 dvar_eval_rotDiff, /* eval callback */
1635 2, /* number of targets used */
1636 {"Object/Bone 1", "Object/Bone 2"}, /* UI names for targets */
1637 {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */
1640 BEGIN_DVAR_TYPEDEF(DVAR_TYPE_LOC_DIFF)
1641 dvar_eval_locDiff, /* eval callback */
1642 2, /* number of targets used */
1643 {"Object/Bone 1", "Object/Bone 2"}, /* UI names for targets */
1644 {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */
1647 BEGIN_DVAR_TYPEDEF(DVAR_TYPE_TRANSFORM_CHAN)
1648 dvar_eval_transChan, /* eval callback */
1649 1, /* number of targets used */
1650 {"Object/Bone"}, /* UI names for targets */
1651 {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */
1655 /* Get driver variable typeinfo */
1656 static const DriverVarTypeInfo *get_dvar_typeinfo(int type)
1658 /* check if valid type */
1659 if ((type >= 0) && (type < MAX_DVAR_TYPES))
1660 return &dvar_types[type];
1665 /* Driver API --------------------------------- */
1667 /* Perform actual freeing driver variable and remove it from the given list */
1668 void driver_free_variable(ListBase *variables, DriverVar *dvar)
1675 * - need to go over all of them, not just up to the ones that are used
1676 * currently, since there may be some lingering RNA paths from
1677 * previous users needing freeing
1679 DRIVER_TARGETS_LOOPER(dvar)
1681 /* free RNA path if applicable */
1683 MEM_freeN(dtar->rna_path);
1685 DRIVER_TARGETS_LOOPER_END
1687 /* remove the variable from the driver */
1688 BLI_freelinkN(variables, dvar);
1691 /* Free the driver variable and do extra updates */
1692 void driver_free_variable_ex(ChannelDriver *driver, DriverVar *dvar)
1694 /* remove and free the driver variable */
1695 driver_free_variable(&driver->variables, dvar);
1698 /* since driver variables are cached, the expression needs re-compiling too */
1699 if (driver->type == DRIVER_TYPE_PYTHON)
1700 driver->flag |= DRIVER_FLAG_RENAMEVAR;
1704 /* Copy driver variables from src_vars list to dst_vars list */
1705 void driver_variables_copy(ListBase *dst_vars, const ListBase *src_vars)
1707 BLI_assert(BLI_listbase_is_empty(dst_vars));
1708 BLI_duplicatelist(dst_vars, src_vars);
1710 for (DriverVar *dvar = dst_vars->first; dvar; dvar = dvar->next) {
1711 /* need to go over all targets so that we don't leave any dangling paths */
1712 DRIVER_TARGETS_LOOPER(dvar)
1714 /* make a copy of target's rna path if available */
1716 dtar->rna_path = MEM_dupallocN(dtar->rna_path);
1718 DRIVER_TARGETS_LOOPER_END
1722 /* Change the type of driver variable */
1723 void driver_change_variable_type(DriverVar *dvar, int type)
1725 const DriverVarTypeInfo *dvti = get_dvar_typeinfo(type);
1728 if (ELEM(NULL, dvar, dvti))
1731 /* set the new settings */
1733 dvar->num_targets = dvti->num_targets;
1735 /* make changes to the targets based on the defines for these types
1736 * NOTE: only need to make sure the ones we're using here are valid...
1738 DRIVER_TARGETS_USED_LOOPER(dvar)
1740 short flags = dvti->target_flags[tarIndex];
1742 /* store the flags */
1745 /* object ID types only, or idtype not yet initialized */
1746 if ((flags & DTAR_FLAG_ID_OB_ONLY) || (dtar->idtype == 0))
1747 dtar->idtype = ID_OB;
1749 DRIVER_TARGETS_LOOPER_END
1752 /* Validate driver name (after being renamed) */
1753 void driver_variable_name_validate(DriverVar *dvar)
1755 /* Special character blacklist */
1756 const char special_char_blacklist[] = {
1757 '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '+', '=', '-',
1758 '/', '\\', '?', ':', ';', '<', '>', '{', '}', '[', ']', '|',
1759 ' ', '.', '\t', '\n', '\r'
1766 /* clear all invalid-name flags */
1767 dvar->flag &= ~DVAR_ALL_INVALID_FLAGS;
1769 /* 0) Zero-length identifiers are not allowed */
1770 if (dvar->name[0] == '\0') {
1771 dvar->flag |= DVAR_FLAG_INVALID_EMPTY;
1774 /* 1) Must start with a letter */
1775 /* XXX: We assume that valid unicode letters in other languages are ok too, hence the blacklisting */
1776 if (IN_RANGE_INCL(dvar->name[0], '0', '9')) {
1777 dvar->flag |= DVAR_FLAG_INVALID_START_NUM;
1779 else if (dvar->name[0] == '_') {
1780 /* NOTE: We don't allow names to start with underscores (i.e. it helps when ruling out security risks) */
1781 dvar->flag |= DVAR_FLAG_INVALID_START_CHAR;
1784 /* 2) Must not contain invalid stuff in the middle of the string */
1785 if (strchr(dvar->name, ' ')) {
1786 dvar->flag |= DVAR_FLAG_INVALID_HAS_SPACE;
1788 if (strchr(dvar->name, '.')) {
1789 dvar->flag |= DVAR_FLAG_INVALID_HAS_DOT;
1792 /* 3) Check for special characters - Either at start, or in the middle */
1793 for (int i = 0; i < sizeof(special_char_blacklist); i++) {
1794 char *match = strchr(dvar->name, special_char_blacklist[i]);
1796 if (match == dvar->name)
1797 dvar->flag |= DVAR_FLAG_INVALID_START_CHAR;
1798 else if (match != NULL)
1799 dvar->flag |= DVAR_FLAG_INVALID_HAS_SPECIAL;
1802 /* 4) Check if the name is a reserved keyword
1803 * NOTE: These won't confuse Python, but it will be impossible to use the variable
1804 * in an expression without Python misinterpreting what these are for
1807 if (BPY_string_is_keyword(dvar->name)) {
1808 dvar->flag |= DVAR_FLAG_INVALID_PY_KEYWORD;
1812 /* If any these conditions match, the name is invalid */
1813 if (dvar->flag & DVAR_ALL_INVALID_FLAGS)
1814 dvar->flag |= DVAR_FLAG_INVALID_NAME;
1817 /* Add a new driver variable */
1818 DriverVar *driver_add_new_variable(ChannelDriver *driver)
1826 /* make a new variable */
1827 dvar = MEM_callocN(sizeof(DriverVar), "DriverVar");
1828 BLI_addtail(&driver->variables, dvar);
1830 /* give the variable a 'unique' name */
1831 strcpy(dvar->name, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var"));
1832 BLI_uniquename(&driver->variables, dvar, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var"), '_',
1833 offsetof(DriverVar, name), sizeof(dvar->name));
1835 /* set the default type to 'single prop' */
1836 driver_change_variable_type(dvar, DVAR_TYPE_SINGLE_PROP);
1839 /* since driver variables are cached, the expression needs re-compiling too */
1840 if (driver->type == DRIVER_TYPE_PYTHON)
1841 driver->flag |= DRIVER_FLAG_RENAMEVAR;
1844 /* return the target */
1848 /* This frees the driver itself */
1849 void fcurve_free_driver(FCurve *fcu)
1851 ChannelDriver *driver;
1852 DriverVar *dvar, *dvarn;
1855 if (ELEM(NULL, fcu, fcu->driver))
1857 driver = fcu->driver;
1859 /* free driver targets */
1860 for (dvar = driver->variables.first; dvar; dvar = dvarn) {
1862 driver_free_variable_ex(driver, dvar);
1866 /* free compiled driver expression */
1867 if (driver->expr_comp)
1868 BPY_DECREF(driver->expr_comp);
1871 /* free driver itself, then set F-Curve's point to this to NULL (as the curve may still be used) */
1876 /* This makes a copy of the given driver */
1877 ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver)
1879 ChannelDriver *ndriver;
1886 ndriver = MEM_dupallocN(driver);
1887 ndriver->expr_comp = NULL;
1889 /* copy variables */
1890 BLI_listbase_clear(&ndriver->variables); /* to get rid of refs to non-copied data (that's still used on original) */
1891 driver_variables_copy(&ndriver->variables, &driver->variables);
1893 /* return the new driver */
1897 /* Driver Evaluation -------------------------- */
1899 /* Evaluate a Driver Variable to get a value that contributes to the final */
1900 float driver_get_variable_value(ChannelDriver *driver, DriverVar *dvar)
1902 const DriverVarTypeInfo *dvti;
1905 if (ELEM(NULL, driver, dvar))
1908 /* call the relevant callbacks to get the variable value
1909 * using the variable type info, storing the obtained value
1910 * in dvar->curval so that drivers can be debugged
1912 dvti = get_dvar_typeinfo(dvar->type);
1914 if (dvti && dvti->get_value)
1915 dvar->curval = dvti->get_value(driver, dvar);
1917 dvar->curval = 0.0f;
1919 return dvar->curval;
1922 /* Evaluate an Channel-Driver to get a 'time' value to use instead of "evaltime"
1923 * - "evaltime" is the frame at which F-Curve is being evaluated
1924 * - has to return a float value
1926 float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const float evaltime)
1930 /* check if driver can be evaluated */
1931 if (driver->flag & DRIVER_FLAG_INVALID)
1934 switch (driver->type) {
1935 case DRIVER_TYPE_AVERAGE: /* average values of driver targets */
1936 case DRIVER_TYPE_SUM: /* sum values of driver targets */
1938 /* check how many variables there are first (i.e. just one?) */
1939 if (BLI_listbase_is_single(&driver->variables)) {
1940 /* just one target, so just use that */
1941 dvar = driver->variables.first;
1942 driver->curval = driver_get_variable_value(driver, dvar);
1945 /* more than one target, so average the values of the targets */
1949 /* loop through targets, adding (hopefully we don't get any overflow!) */
1950 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1951 value += driver_get_variable_value(driver, dvar);
1955 /* perform operations on the total if appropriate */
1956 if (driver->type == DRIVER_TYPE_AVERAGE)
1957 driver->curval = tot ? (value / (float)tot) : 0.0f;
1959 driver->curval = value;
1963 case DRIVER_TYPE_MIN: /* smallest value */
1964 case DRIVER_TYPE_MAX: /* largest value */
1968 /* loop through the variables, getting the values and comparing them to existing ones */
1969 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1971 float tmp_val = driver_get_variable_value(driver, dvar);
1973 /* store this value if appropriate */
1975 /* check if greater/smaller than the baseline */
1976 if (driver->type == DRIVER_TYPE_MAX) {
1978 if (tmp_val > value)
1983 if (tmp_val < value)
1988 /* first item - make this the baseline for comparisons */
1993 /* store value in driver */
1994 driver->curval = value;
1997 case DRIVER_TYPE_PYTHON: /* expression */
2000 /* check for empty or invalid expression */
2001 if ( (driver->expression[0] == '\0') ||
2002 (driver->flag & DRIVER_FLAG_INVALID) )
2004 driver->curval = 0.0f;
2007 /* this evaluates the expression using Python, and returns its result:
2008 * - on errors it reports, then returns 0.0f
2010 BLI_mutex_lock(&python_driver_lock);
2012 driver->curval = BPY_driver_exec(anim_rna, driver, evaltime);
2014 BLI_mutex_unlock(&python_driver_lock);
2016 #else /* WITH_PYTHON*/
2017 UNUSED_VARS(anim_rna, evaltime);
2018 #endif /* WITH_PYTHON*/
2023 /* special 'hack' - just use stored value
2024 * This is currently used as the mechanism which allows animated settings to be able
2025 * to be changed via the UI.
2031 /* return value for driver */
2032 return driver->curval;
2035 /* ***************************** Curve Calculations ********************************* */
2037 /* The total length of the handles is not allowed to be more
2038 * than the horizontal distance between (v1-v4).
2039 * This is to prevent curve loops.
2041 void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2])
2043 float h1[2], h2[2], len1, len2, len, fac;
2045 /* calculate handle deltas */
2046 h1[0] = v1[0] - v2[0];
2047 h1[1] = v1[1] - v2[1];
2049 h2[0] = v4[0] - v3[0];
2050 h2[1] = v4[1] - v3[1];
2052 /* calculate distances:
2053 * - len = span of time between keyframes
2054 * - len1 = length of handle of start key
2055 * - len2 = length of handle of end key
2057 len = v4[0] - v1[0];
2058 len1 = fabsf(h1[0]);
2059 len2 = fabsf(h2[0]);
2061 /* if the handles have no length, no need to do any corrections */
2062 if ((len1 + len2) == 0.0f)
2065 /* the two handles cross over each other, so force them
2066 * apart using the proportion they overlap
2068 if ((len1 + len2) > len) {
2069 fac = len / (len1 + len2);
2071 v2[0] = (v1[0] - fac * h1[0]);
2072 v2[1] = (v1[1] - fac * h1[1]);
2074 v3[0] = (v4[0] - fac * h2[0]);
2075 v3[1] = (v4[1] - fac * h2[1]);
2079 /* find root ('zero') */
2080 static int findzero(float x, float q0, float q1, float q2, float q3, float *o)
2082 double c0, c1, c2, c3, a, b, c, p, q, d, t, phi;
2086 c1 = 3.0f * (q1 - q0);
2087 c2 = 3.0f * (q0 - 2.0f * q1 + q2);
2088 c3 = q3 - q0 + 3.0f * (q1 - q2);
2097 q = (2 * a * a * a - a * b + c) / 2;
2098 d = q * q + p * p * p;
2102 o[0] = (float)(sqrt3d(-q + t) + sqrt3d(-q - t) - a);
2104 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1;
2107 else if (d == 0.0) {
2109 o[0] = (float)(2 * t - a);
2111 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++;
2112 o[nr] = (float)(-t - a);
2114 if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1;
2118 phi = acos(-q / sqrt(-(p * p * p)));
2121 q = sqrt(3 - 3 * p * p);
2122 o[0] = (float)(2 * t * p - a);
2124 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++;
2125 o[nr] = (float)(-t * (p + q) - a);
2127 if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) nr++;
2128 o[nr] = (float)(-t * (p - q) - a);
2130 if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1;
2141 p = b * b - 4 * a * c;
2145 o[0] = (float)((-b - p) / (2 * a));
2147 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++;
2148 o[nr] = (float)((-b + p) / (2 * a));
2150 if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1;
2154 o[0] = (float)(-b / (2 * a));
2155 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1;
2159 else if (b != 0.0) {
2160 o[0] = (float)(-c / b);
2162 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1;
2165 else if (c == 0.0) {
2174 static void berekeny(float f1, float f2, float f3, float f4, float *o, int b)
2176 float t, c0, c1, c2, c3;
2180 c1 = 3.0f * (f2 - f1);
2181 c2 = 3.0f * (f1 - 2.0f * f2 + f3);
2182 c3 = f4 - f1 + 3.0f * (f2 - f3);
2184 for (a = 0; a < b; a++) {
2186 o[a] = c0 + t * c1 + t * t * c2 + t * t * t * c3;
2191 static void berekenx(float *f, float *o, int b)
2193 float t, c0, c1, c2, c3;
2197 c1 = 3.0f * (f[3] - f[0]);
2198 c2 = 3.0f * (f[0] - 2.0f * f[3] + f[6]);
2199 c3 = f[9] - f[0] + 3.0f * (f[3] - f[6]);
2201 for (a = 0; a < b; a++) {
2203 o[a] = c0 + t * c1 + t * t * c2 + t * t * t * c3;
2209 /* -------------------------- */
2211 /* Calculate F-Curve value for 'evaltime' using BezTriple keyframes */
2212 static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime)
2214 const float eps = 1.e-8f;
2215 BezTriple *bezt, *prevbezt, *lastbezt;
2216 float v1[2], v2[2], v3[2], v4[2], opl[32], dx, fac;
2219 float cvalue = 0.0f;
2222 a = fcu->totvert - 1;
2224 bezt = prevbezt + 1;
2225 lastbezt = prevbezt + a;
2227 /* evaluation time at or past endpoints? */
2228 if (prevbezt->vec[1][0] >= evaltime) {
2229 /* before or on first keyframe */
2230 if ( (fcu->extend == FCURVE_EXTRAPOLATE_LINEAR) && (prevbezt->ipo != BEZT_IPO_CONST) &&
2231 !(fcu->flag & FCURVE_DISCRETE_VALUES) )
2233 /* linear or bezier interpolation */
2234 if (prevbezt->ipo == BEZT_IPO_LIN) {
2235 /* Use the next center point instead of our own handle for
2236 * linear interpolated extrapolate
2238 if (fcu->totvert == 1) {
2239 cvalue = prevbezt->vec[1][1];
2242 bezt = prevbezt + 1;
2243 dx = prevbezt->vec[1][0] - evaltime;
2244 fac = bezt->vec[1][0] - prevbezt->vec[1][0];
2246 /* prevent division by zero */
2248 fac = (bezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
2249 cvalue = prevbezt->vec[1][1] - (fac * dx);
2252 cvalue = prevbezt->vec[1][1];
2257 /* Use the first handle (earlier) of first BezTriple to calculate the
2258 * gradient and thus the value of the curve at evaltime
2260 dx = prevbezt->vec[1][0] - evaltime;
2261 fac = prevbezt->vec[1][0] - prevbezt->vec[0][0];
2263 /* prevent division by zero */
2265 fac = (prevbezt->vec[1][1] - prevbezt->vec[0][1]) / fac;
2266 cvalue = prevbezt->vec[1][1] - (fac * dx);
2269 cvalue = prevbezt->vec[1][1];
2274 /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation,
2275 * so just extend first keyframe's value
2277 cvalue = prevbezt->vec[1][1];
2280 else if (lastbezt->vec[1][0] <= evaltime) {
2281 /* after or on last keyframe */
2282 if ( (fcu->extend == FCURVE_EXTRAPOLATE_LINEAR) && (lastbezt->ipo != BEZT_IPO_CONST) &&
2283 !(fcu->flag & FCURVE_DISCRETE_VALUES) )
2285 /* linear or bezier interpolation */
2286 if (lastbezt->ipo == BEZT_IPO_LIN) {
2287 /* Use the next center point instead of our own handle for
2288 * linear interpolated extrapolate
2290 if (fcu->totvert == 1) {
2291 cvalue = lastbezt->vec[1][1];
2294 prevbezt = lastbezt - 1;
2295 dx = evaltime - lastbezt->vec[1][0];
2296 fac = lastbezt->vec[1][0] - prevbezt->vec[1][0];
2298 /* prevent division by zero */
2300 fac = (lastbezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
2301 cvalue = lastbezt->vec[1][1] + (fac * dx);
2304 cvalue = lastbezt->vec[1][1];
2309 /* Use the gradient of the second handle (later) of last BezTriple to calculate the
2310 * gradient and thus the value of the curve at evaltime
2312 dx = evaltime - lastbezt->vec[1][0];
2313 fac = lastbezt->vec[2][0] - lastbezt->vec[1][0];
2315 /* prevent division by zero */
2317 fac = (lastbezt->vec[2][1] - lastbezt->vec[1][1]) / fac;
2318 cvalue = lastbezt->vec[1][1] + (fac * dx);
2321 cvalue = lastbezt->vec[1][1];
2326 /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation,
2327 * so just extend last keyframe's value
2329 cvalue = lastbezt->vec[1][1];
2333 /* evaltime occurs somewhere in the middle of the curve */
2336 /* Use binary search to find appropriate keyframes...
2338 * The threshold here has the following constraints:
2339 * - 0.001 is too coarse -> We get artifacts with 2cm driver movements at 1BU = 1m (see T40332)
2340 * - 0.00001 is too fine -> Weird errors, like selecting the wrong keyframe range (see T39207), occur.
2341 * This lower bound was established in b888a32eee8147b028464336ad2404d8155c64dd
2343 a = binarysearch_bezt_index_ex(bezts, evaltime, fcu->totvert, 0.0001, &exact);
2344 if (G.debug & G_DEBUG) printf("eval fcurve '%s' - %f => %u/%u, %d\n", fcu->rna_path, evaltime, a, fcu->totvert, exact);
2347 /* index returned must be interpreted differently when it sits on top of an existing keyframe
2348 * - that keyframe is the start of the segment we need (see action_bug_2.blend in T39207)
2350 prevbezt = bezts + a;
2351 bezt = (a < fcu->totvert - 1) ? (prevbezt + 1) : prevbezt;
2354 /* index returned refers to the keyframe that the eval-time occurs *before*
2355 * - hence, that keyframe marks the start of the segment we're dealing with
2358 prevbezt = (a > 0) ? (bezt - 1) : bezt;
2361 /* use if the key is directly on the frame, rare cases this is needed else we get 0.0 instead. */
2362 /* XXX: consult T39207 for examples of files where failure of these checks can cause issues */
2364 cvalue = prevbezt->vec[1][1];
2366 else if (fabsf(bezt->vec[1][0] - evaltime) < eps) {
2367 cvalue = bezt->vec[1][1];
2369 /* evaltime occurs within the interval defined by these two keyframes */
2370 else if ((prevbezt->vec[1][0] <= evaltime) && (bezt->vec[1][0] >= evaltime)) {
2371 const float begin = prevbezt->vec[1][1];
2372 const float change = bezt->vec[1][1] - prevbezt->vec[1][1];
2373 const float duration = bezt->vec[1][0] - prevbezt->vec[1][0];
2374 const float time = evaltime - prevbezt->vec[1][0];
2375 const float amplitude = prevbezt->amplitude;
2376 const float period = prevbezt->period;
2378 /* value depends on interpolation mode */
2379 if ((prevbezt->ipo == BEZT_IPO_CONST) || (fcu->flag & FCURVE_DISCRETE_VALUES) || (duration == 0)) {
2380 /* constant (evaltime not relevant, so no interpolation needed) */
2381 cvalue = prevbezt->vec[1][1];
2384 switch (prevbezt->ipo) {
2385 /* interpolation ...................................... */
2387 /* bezier interpolation */
2388 /* (v1, v2) are the first keyframe and its 2nd handle */
2389 v1[0] = prevbezt->vec[1][0];
2390 v1[1] = prevbezt->vec[1][1];
2391 v2[0] = prevbezt->vec[2][0];
2392 v2[1] = prevbezt->vec[2][1];
2393 /* (v3, v4) are the last keyframe's 1st handle + the last keyframe */
2394 v3[0] = bezt->vec[0][0];
2395 v3[1] = bezt->vec[0][1];
2396 v4[0] = bezt->vec[1][0];
2397 v4[1] = bezt->vec[1][1];
2399 if (fabsf(v1[1] - v4[1]) < FLT_EPSILON &&
2400 fabsf(v2[1] - v3[1]) < FLT_EPSILON &&
2401 fabsf(v3[1] - v4[1]) < FLT_EPSILON)
2403 /* Optimisation: If all the handles are flat/at the same values,
2404 * the value is simply the shared value (see T40372 -> F91346)
2409 /* adjust handles so that they don't overlap (forming a loop) */
2410 correct_bezpart(v1, v2, v3, v4);
2412 /* try to get a value for this position - if failure, try another set of points */
2413 b = findzero(evaltime, v1[0], v2[0], v3[0], v4[0], opl);
2415 berekeny(v1[1], v2[1], v3[1], v4[1], opl, 1);
2420 if (G.debug & G_DEBUG) printf(" ERROR: findzero() failed at %f with %f %f %f %f\n", evaltime, v1[0], v2[0], v3[0], v4[0]);
2426 /* linear - simply linearly interpolate between values of the two keyframes */
2427 cvalue = BLI_easing_linear_ease(time, begin, change, duration);
2430 /* easing ............................................ */
2432 switch (prevbezt->easing) {
2433 case BEZT_IPO_EASE_IN:
2434 cvalue = BLI_easing_back_ease_in(time, begin, change, duration, prevbezt->back);
2436 case BEZT_IPO_EASE_OUT:
2437 cvalue = BLI_easing_back_ease_out(time, begin, change, duration, prevbezt->back);
2439 case BEZT_IPO_EASE_IN_OUT:
2440 cvalue = BLI_easing_back_ease_in_out(time, begin, change, duration, prevbezt->back);
2443 default: /* default/auto: same as ease out */
2444 cvalue = BLI_easing_back_ease_out(time, begin, change, duration, prevbezt->back);
2449 case BEZT_IPO_BOUNCE:
2450 switch (prevbezt->easing) {
2451 case BEZT_IPO_EASE_IN:
2452 cvalue = BLI_easing_bounce_ease_in(time, begin, change, duration);
2454 case BEZT_IPO_EASE_OUT:
2455 cvalue = BLI_easing_bounce_ease_out(time, begin, change, duration);
2457 case BEZT_IPO_EASE_IN_OUT:
2458 cvalue = BLI_easing_bounce_ease_in_out(time, begin, change, duration);
2461 default: /* default/auto: same as ease out */
2462 cvalue = BLI_easing_bounce_ease_out(time, begin, change, duration);
2468 switch (prevbezt->easing) {
2469 case BEZT_IPO_EASE_IN:
2470 cvalue = BLI_easing_circ_ease_in(time, begin, change, duration);
2472 case BEZT_IPO_EASE_OUT:
2473 cvalue = BLI_easing_circ_ease_out(time, begin, change, duration);
2475 case BEZT_IPO_EASE_IN_OUT:
2476 cvalue = BLI_easing_circ_ease_in_out(time, begin, change, duration);
2479 default: /* default/auto: same as ease in */
2480 cvalue = BLI_easing_circ_ease_in(time, begin, change, duration);
2485 case BEZT_IPO_CUBIC:
2486 switch (prevbezt->easing) {
2487 case BEZT_IPO_EASE_IN:
2488 cvalue = BLI_easing_cubic_ease_in(time, begin, change, duration);
2490 case BEZT_IPO_EASE_OUT:
2491 cvalue = BLI_easing_cubic_ease_out(time, begin, change, duration);
2493 case BEZT_IPO_EASE_IN_OUT:
2494 cvalue = BLI_easing_cubic_ease_in_out(time, begin, change, duration);
2497 default: /* default/auto: same as ease in */
2498 cvalue = BLI_easing_cubic_ease_in(time, begin, change, duration);
2503 case BEZT_IPO_ELASTIC:
2504 switch (prevbezt->easing) {
2505 case BEZT_IPO_EASE_IN:
2506 cvalue = BLI_easing_elastic_ease_in(time, begin, change, duration, amplitude, period);
2508 case BEZT_IPO_EASE_OUT:
2509 cvalue = BLI_easing_elastic_ease_out(time, begin, change, duration, amplitude, period);
2511 case BEZT_IPO_EASE_IN_OUT:
2512 cvalue = BLI_easing_elastic_ease_in_out(time, begin, change, duration, amplitude, period);
2515 default: /* default/auto: same as ease out */
2516 cvalue = BLI_easing_elastic_ease_out(time, begin, change, duration, amplitude, period);
2522 switch (prevbezt->easing) {
2523 case BEZT_IPO_EASE_IN:
2524 cvalue = BLI_easing_expo_ease_in(time, begin, change, duration);
2526 case BEZT_IPO_EASE_OUT:
2527 cvalue = BLI_easing_expo_ease_out(time, begin, change, duration);
2529 case BEZT_IPO_EASE_IN_OUT:
2530 cvalue = BLI_easing_expo_ease_in_out(time, begin, change, duration);
2533 default: /* default/auto: same as ease in */
2534 cvalue = BLI_easing_expo_ease_in(time, begin, change, duration);
2540 switch (prevbezt->easing) {
2541 case BEZT_IPO_EASE_IN:
2542 cvalue = BLI_easing_quad_ease_in(time, begin, change, duration);
2544 case BEZT_IPO_EASE_OUT:
2545 cvalue = BLI_easing_quad_ease_out(time, begin, change, duration);
2547 case BEZT_IPO_EASE_IN_OUT:
2548 cvalue = BLI_easing_quad_ease_in_out(time, begin, change, duration);
2551 default: /* default/auto: same as ease in */
2552 cvalue = BLI_easing_quad_ease_in(time, begin, change, duration);
2557 case BEZT_IPO_QUART:
2558 switch (prevbezt->easing) {
2559 case BEZT_IPO_EASE_IN:
2560 cvalue = BLI_easing_quart_ease_in(time, begin, change, duration);
2562 case BEZT_IPO_EASE_OUT:
2563 cvalue = BLI_easing_quart_ease_out(time, begin, change, duration);
2565 case BEZT_IPO_EASE_IN_OUT:
2566 cvalue = BLI_easing_quart_ease_in_out(time, begin, change, duration);
2569 default: /* default/auto: same as ease in */
2570 cvalue = BLI_easing_quart_ease_in(time, begin, change, duration);
2575 case BEZT_IPO_QUINT:
2576 switch (prevbezt->easing) {
2577 case BEZT_IPO_EASE_IN:
2578 cvalue = BLI_easing_quint_ease_in(time, begin, change, duration);
2580 case BEZT_IPO_EASE_OUT:
2581 cvalue = BLI_easing_quint_ease_out(time, begin, change, duration);
2583 case BEZT_IPO_EASE_IN_OUT:
2584 cvalue = BLI_easing_quint_ease_in_out(time, begin, change, duration);
2587 default: /* default/auto: same as ease in */
2588 cvalue = BLI_easing_quint_ease_in(time, begin, change, duration);
2594 switch (prevbezt->easing) {
2595 case BEZT_IPO_EASE_IN:
2596 cvalue = BLI_easing_sine_ease_in(time, begin, change, duration);
2598 case BEZT_IPO_EASE_OUT:
2599 cvalue = BLI_easing_sine_ease_out(time, begin, change, duration);
2601 case BEZT_IPO_EASE_IN_OUT:
2602 cvalue = BLI_easing_sine_ease_in_out(time, begin, change, duration);
2605 default: /* default/auto: same as ease in */
2606 cvalue = BLI_easing_sine_ease_in(time, begin, change, duration);
2613 cvalue = prevbezt->vec[1][1];
2619 if (G.debug & G_DEBUG) printf(" ERROR: failed eval - p=%f b=%f, t=%f (%f)\n", prevbezt->vec[1][0], bezt->vec[1][0], evaltime, fabsf(bezt->vec[1][0] - evaltime));
2627 /* Calculate F-Curve value for 'evaltime' using FPoint samples */
2628 static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime)
2630 FPoint *prevfpt, *lastfpt, *fpt;
2631 float cvalue = 0.0f;
2635 lastfpt = prevfpt + fcu->totvert - 1;
2637 /* evaluation time at or past endpoints? */
2638 if (prevfpt->vec[0] >= evaltime) {
2639 /* before or on first sample, so just extend value */
2640 cvalue = prevfpt->vec[1];
2642 else if (lastfpt->vec[0] <= evaltime) {
2643 /* after or on last sample, so just extend value */
2644 cvalue = lastfpt->vec[1];
2647 float t = fabsf(evaltime - floorf(evaltime));
2649 /* find the one on the right frame (assume that these are spaced on 1-frame intervals) */
2650 fpt = prevfpt + ((int)evaltime - (int)prevfpt->vec[0]);
2652 /* if not exactly on the frame, perform linear interpolation with the next one */
2653 if ((t != 0.0f) && (t < 1.0f))
2654 cvalue = interpf(fpt->vec[1], (fpt + 1)->vec[1], 1.0f - t);
2656 cvalue = fpt->vec[1];
2663 /* ***************************** F-Curve - Evaluation ********************************* */
2665 /* Evaluate and return the value of the given F-Curve at the specified frame ("evaltime")
2666 * Note: this is also used for drivers
2668 static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue)
2670 FModifierStackStorage *storage;
2673 /* evaluate modifiers which modify time to evaluate the base curve at */
2674 storage = evaluate_fmodifiers_storage_new(&fcu->modifiers);
2675 devaltime = evaluate_time_fmodifiers(storage, &fcu->modifiers, fcu, cvalue, evaltime);
2677 /* evaluate curve-data
2678 * - 'devaltime' instead of 'evaltime', as this is the time that the last time-modifying
2679 * F-Curve modifier on the stack requested the curve to be evaluated at
2682 cvalue = fcurve_eval_keyframes(fcu, fcu->bezt, devaltime);
2684 cvalue = fcurve_eval_samples(fcu, fcu->fpt, devaltime);
2686 /* evaluate modifiers */
2687 evaluate_value_fmodifiers(storage, &fcu->modifiers, fcu, &cvalue, devaltime);
2689 evaluate_fmodifiers_storage_free(storage);
2691 /* if curve can only have integral values, perform truncation (i.e. drop the decimal part)
2692 * here so that the curve can be sampled correctly
2694 if (fcu->flag & FCURVE_INT_VALUES)
2695 cvalue = floorf(cvalue + 0.5f);
2697 /* return evaluated value */
2701 float evaluate_fcurve(FCurve *fcu, float evaltime)
2703 BLI_assert(fcu->driver == NULL);
2705 return evaluate_fcurve_ex(fcu, evaltime, 0.0);
2708 float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime)
2710 BLI_assert(fcu->driver != NULL);
2711 float cvalue = 0.0f;
2713 /* if there is a driver (only if this F-Curve is acting as 'driver'), evaluate it to find value to use as "evaltime"
2714 * since drivers essentially act as alternative input (i.e. in place of 'time') for F-Curves
2717 /* evaltime now serves as input for the curve */
2718 evaltime = evaluate_driver(anim_rna, fcu->driver, evaltime);
2720 /* only do a default 1-1 mapping if it's unlikely that anything else will set a value... */
2721 if (fcu->totvert == 0) {
2723 bool do_linear = true;
2725 /* out-of-range F-Modifiers will block, as will those which just plain overwrite the values
2726 * XXX: additive is a bit more dicey; it really depends then if things are in range or not...
2728 for (fcm = fcu->modifiers.first; fcm; fcm = fcm->next) {
2729 /* if there are range-restrictions, we must definitely block [#36950] */
2730 if ((fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) == 0 ||
2731 ((fcm->sfra <= evaltime) && (fcm->efra >= evaltime)) )
2733 /* within range: here it probably doesn't matter, though we'd want to check on additive... */
2736 /* outside range: modifier shouldn't contribute to the curve here, though it does in other areas,
2737 * so neither should the driver!
2743 /* only copy over results if none of the modifiers disagreed with this */
2750 return evaluate_fcurve_ex(fcu, evaltime, cvalue);
2753 /* Calculate the value of the given F-Curve at the given frame, and set its curval */
2754 float calculate_fcurve(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime)
2756 /* only calculate + set curval (overriding the existing value) if curve has
2757 * any data which warrants this...
2759 if ((fcu->totvert) || (fcu->driver && !(fcu->driver->flag & DRIVER_FLAG_INVALID)) ||
2760 list_has_suitable_fmodifier(&fcu->modifiers, 0, FMI_TYPE_GENERATE_CURVE))
2762 /* calculate and set curval (evaluates driver too if necessary) */
2765 curval = evaluate_fcurve_driver(anim_rna, fcu, evaltime);
2768 curval = evaluate_fcurve(fcu, evaltime);
2770 fcu->curval = curval; /* debug display only, not thread safe! */