Building w/o Python works again
[blender.git] / source / blender / blenkernel / intern / fcurve.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
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.
8  *
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.
13  *
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.
17  *
18  * The Original Code is Copyright (C) 2009 Blender Foundation, Joshua Leung
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joshua Leung (full recode)
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/fcurve.c
29  *  \ingroup bke
30  */
31
32  
33
34 #include <math.h>
35 #include <stdio.h>
36 #include <stddef.h>
37 #include <string.h>
38 #include <float.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "DNA_anim_types.h"
43 #include "DNA_constraint_types.h"
44 #include "DNA_object_types.h"
45
46 #include "BLI_blenlib.h"
47 #include "BLI_math.h"
48 #include "BLI_easing.h"
49 #include "BLI_threads.h"
50 #include "BLI_string_utils.h"
51 #include "BLI_utildefines.h"
52
53 #include "BLT_translation.h"
54
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"
64
65 #include "RNA_access.h"
66
67 #ifdef WITH_PYTHON
68 #include "BPY_extern.h" 
69 #endif
70
71 #define SMALL -1.0e-10
72 #define SELECT 1
73
74 #ifdef WITH_PYTHON
75 static ThreadMutex python_driver_lock = BLI_MUTEX_INITIALIZER;
76 #endif
77
78 /* ************************** Data-Level Functions ************************* */
79
80 /* ---------------------- Freeing --------------------------- */
81
82 /* Frees the F-Curve itself too, so make sure BLI_remlink is called before calling this... */
83 void free_fcurve(FCurve *fcu)
84 {
85         if (fcu == NULL) 
86                 return;
87
88         /* free curve data */
89         if (fcu->bezt) MEM_freeN(fcu->bezt);
90         if (fcu->fpt)  MEM_freeN(fcu->fpt);
91         
92         /* free RNA-path, as this were allocated when getting the path string */
93         if (fcu->rna_path)
94                 MEM_freeN(fcu->rna_path);
95         
96         /* free extra data - i.e. modifiers, and driver */
97         fcurve_free_driver(fcu);
98         free_fmodifiers(&fcu->modifiers);
99         
100         /* free f-curve itself */
101         MEM_freeN(fcu);
102 }
103
104 /* Frees a list of F-Curves */
105 void free_fcurves(ListBase *list)
106 {
107         FCurve *fcu, *fcn;
108         
109         /* sanity check */
110         if (list == NULL)
111                 return;
112                 
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
115          * it's given
116          */
117         for (fcu = list->first; fcu; fcu = fcn) {
118                 fcn = fcu->next;
119                 free_fcurve(fcu);
120         }
121         
122         /* clear pointers just in case */
123         BLI_listbase_clear(list);
124 }       
125
126 /* ---------------------- Copy --------------------------- */
127
128 /* duplicate an F-Curve */
129 FCurve *copy_fcurve(const FCurve *fcu)
130 {
131         FCurve *fcu_d;
132         
133         /* sanity check */
134         if (fcu == NULL)
135                 return NULL;
136                 
137         /* make a copy */
138         fcu_d = MEM_dupallocN(fcu);
139         
140         fcu_d->next = fcu_d->prev = NULL;
141         fcu_d->grp = NULL;
142         
143         /* copy curve data */
144         fcu_d->bezt = MEM_dupallocN(fcu_d->bezt);
145         fcu_d->fpt = MEM_dupallocN(fcu_d->fpt);
146         
147         /* copy rna-path */
148         fcu_d->rna_path = MEM_dupallocN(fcu_d->rna_path);
149         
150         /* copy driver */
151         fcu_d->driver = fcurve_copy_driver(fcu_d->driver);
152         
153         /* copy modifiers */
154         copy_fmodifiers(&fcu_d->modifiers, &fcu->modifiers);
155         
156         /* return new data */
157         return fcu_d;
158 }
159
160 /* duplicate a list of F-Curves */
161 void copy_fcurves(ListBase *dst, ListBase *src)
162 {
163         FCurve *dfcu, *sfcu;
164         
165         /* sanity checks */
166         if (ELEM(NULL, dst, src))
167                 return;
168         
169         /* clear destination list first */
170         BLI_listbase_clear(dst);
171         
172         /* copy one-by-one */
173         for (sfcu = src->first; sfcu; sfcu = sfcu->next) {
174                 dfcu = copy_fcurve(sfcu);
175                 BLI_addtail(dst, dfcu);
176         }
177 }
178
179 /* ----------------- Finding F-Curves -------------------------- */
180
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)
183 {
184         /* anim vars */
185         AnimData *adt = BKE_animdata_from_id(id);
186         FCurve *fcu = NULL;
187
188         /* rna vars */
189         PointerRNA ptr;
190         PropertyRNA *prop;
191         char *path;
192
193         if (r_driven)
194                 *r_driven = false;
195         
196         /* only use the current action ??? */
197         if (ELEM(NULL, adt, adt->action))
198                 return NULL;
199         
200         RNA_pointer_create(id, type, data, &ptr);
201         prop = RNA_struct_find_property(&ptr, prop_name);
202         
203         if (prop) {
204                 path = RNA_path_from_ID_to_property(&ptr, prop);
205                         
206                 if (path) {
207                         /* animation takes priority over drivers */
208                         if ((adt->action) && (adt->action->curves.first))
209                                 fcu = list_find_fcurve(&adt->action->curves, path, index);
210                         
211                         /* if not animated, check if driven */
212                         if ((fcu == NULL) && (adt->drivers.first)) {
213                                 fcu = list_find_fcurve(&adt->drivers, path, index);
214                                 if (fcu && r_driven)
215                                         *r_driven = true;
216                                 fcu = NULL;
217                         }
218                         
219                         MEM_freeN(path);
220                 }
221         }
222
223         return fcu;
224 }
225
226
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)
229 {
230         FCurve *fcu;
231         
232         /* sanity checks */
233         if (ELEM(NULL, list, rna_path) || (array_index < 0) )
234                 return NULL;
235         
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)
242                                 return fcu;
243                 }
244         }
245         
246         /* return */
247         return NULL;
248 }
249
250 /* quick way to loop over all fcurves of a given 'path' */
251 FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[])
252 {
253         FCurve *fcu;
254         
255         /* sanity checks */
256         if (ELEM(NULL, fcu_iter, rna_path))
257                 return NULL;
258
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)) {
263                         return fcu;
264                 }
265         }
266
267         /* return */
268         return NULL;
269 }
270
271 /* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated 
272  * Lists...
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
276  * Filters...
277  *  - dataPrefix: i.e. 'pose.bones[' or 'nodes['
278  *  - dataName: name of entity within "" immediately following the prefix
279  */
280 int list_find_data_fcurves(ListBase *dst, ListBase *src, const char *dataPrefix, const char *dataName)
281 {
282         FCurve *fcu;
283         int matches = 0;
284         
285         /* sanity checks */
286         if (ELEM(NULL, dst, src, dataPrefix, dataName))
287                 return 0;
288         else if ((dataPrefix[0] == 0) || (dataName[0] == 0))
289                 return 0;
290         
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);
296                         
297                         if (quotedName) {
298                                 /* check if the quoted name matches the required name */
299                                 if (STREQ(quotedName, dataName)) {
300                                         LinkData *ld = MEM_callocN(sizeof(LinkData), __func__);
301                                         
302                                         ld->data = fcu;
303                                         BLI_addtail(dst, ld);
304                                         
305                                         matches++;
306                                 }
307                                 
308                                 /* always free the quoted string, since it needs freeing */
309                                 MEM_freeN(quotedName);
310                         }
311                 }
312         }
313         
314         /* return the number of matches */
315         return matches;
316 }
317
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)
321 {
322         return rna_get_fcurve_context_ui(NULL, ptr, prop, rnaindex, r_adt, r_action, r_driven, r_special);
323 }
324
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)
328 {
329         FCurve *fcu = NULL;
330         PointerRNA tptr = *ptr;
331         
332         *r_driven = false;
333         *r_special = false;
334         
335         if (r_animdata) *r_animdata = NULL;
336         if (r_action) *r_action = NULL;
337         
338         /* Special case for NLA Control Curves... */
339         if (ptr->type == &RNA_NlaStrip) {
340                 NlaStrip *strip = (NlaStrip *)ptr->data;
341                 
342                 /* Set the special flag, since it cannot be a normal action/driver
343                  * if we've been told to start looking here...
344                  */
345                 *r_special = true;
346                 
347                 /* The F-Curve either exists or it doesn't here... */
348                 fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), rnaindex);
349                 return fcu;
350         }
351         
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). */
356                 char *path = NULL;
357                 
358                 if (!adt && C) {
359                         path = BKE_animdata_driver_path_hack(C, &tptr, prop, NULL);
360                         adt = BKE_animdata_from_id(tptr.id.data);
361                         step--;
362                 }
363                 
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 */
368                                 if (step) {
369                                         path = RNA_path_from_ID_to_property(&tptr, prop);
370                                 }
371                                 
372                                 // XXX: the logic here is duplicated with a function up above
373                                 if (path) {
374                                         /* animation takes priority over drivers */
375                                         if (adt->action && adt->action->curves.first) {
376                                                 fcu = list_find_fcurve(&adt->action->curves, path, rnaindex);
377                                                 
378                                                 if (fcu && r_action)
379                                                         *r_action = adt->action;
380                                         }
381                                         
382                                         /* if not animated, check if driven */
383                                         if (!fcu && (adt->drivers.first)) {
384                                                 fcu = list_find_fcurve(&adt->drivers, path, rnaindex);
385                                                 
386                                                 if (fcu) {
387                                                         if (r_animdata) *r_animdata = adt;
388                                                         *r_driven = true;
389                                                 }
390                                         }
391                                         
392                                         if (fcu && r_action) {
393                                                 if (r_animdata) *r_animdata = adt;
394                                                 *r_action = adt->action;
395                                                 break;
396                                         }
397                                         else if (step) {
398                                                 char *tpath = BKE_animdata_driver_path_hack(C, &tptr, prop, path);
399                                                 if (tpath && tpath != path) {
400                                                         MEM_freeN(path);
401                                                         path = tpath;
402                                                         adt = BKE_animdata_from_id(tptr.id.data);
403                                                 }
404                                                 else {
405                                                         adt = NULL;
406                                                 }
407                                         }
408                                 }
409                         }
410                 }
411                 MEM_SAFE_FREE(path);
412         }
413         
414         return fcu;
415 }
416
417 /* ----------------- Finding Keyframes/Extents -------------------------- */
418
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)
421  */
422 static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arraylen, float threshold, bool *r_replace)
423 {
424         int start = 0, end = arraylen;
425         int loopbreaker = 0, maxloop = arraylen * 2;
426         
427         /* initialize replace-flag first */
428         *r_replace = false;
429         
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
433          */
434         if ((arraylen <= 0) || (array == NULL)) {
435                 printf("Warning: binarysearch_bezt_index() encountered invalid array\n");
436                 return 0;
437         }
438         else {
439                 /* check whether to add before/after/on */
440                 float framenum;
441                 
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)) {
445                         *r_replace = true;
446                         return 0;
447                 }
448                 else if (frame < framenum)
449                         return 0;
450                         
451                 /* 'Last' Keyframe */
452                 framenum = array[(arraylen - 1)].vec[1][0];
453                 if (IS_EQT(frame, framenum, threshold)) {
454                         *r_replace = true;
455                         return (arraylen - 1);
456                 }
457                 else if (frame > framenum)
458                         return arraylen;
459         }
460         
461         
462         /* most of the time, this loop is just to find where to put it
463          * 'loopbreaker' is just here to prevent infinite loops 
464          */
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];
469                 
470                 /* check if exactly equal to midpoint */
471                 if (IS_EQT(frame, midfra, threshold)) {
472                         *r_replace = true;
473                         return mid;
474                 }
475                 
476                 /* repeat in upper/lower half */
477                 if (frame > midfra)
478                         start = mid + 1;
479                 else if (frame < midfra)
480                         end = mid - 1;
481         }
482         
483         /* print error if loop-limit exceeded */
484         if (loopbreaker == (maxloop - 1)) {
485                 printf("Error: binarysearch_bezt_index() was taking too long\n");
486                 
487                 /* include debug info */
488                 printf("\tround = %d: start = %d, end = %d, arraylen = %d\n", loopbreaker, start, end, arraylen);
489         }
490         
491         /* not found, so return where to place it */
492         return start;
493 }
494
495
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)
498  */
499 int binarysearch_bezt_index(BezTriple array[], float frame, int arraylen, bool *r_replace)
500 {
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);
503 }
504
505 /* ...................................... */
506
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)
510 {
511         bool found = false;
512         
513         /* init outputs */
514         *first = NULL;
515         *last = NULL;
516         
517         /* sanity checks */
518         if (fcu->bezt == NULL)
519                 return found;
520         
521         /* only include selected items? */
522         if (do_sel_only) {
523                 BezTriple *bezt;
524                 unsigned int i;
525                 
526                 /* find first selected */
527                 bezt = fcu->bezt;
528                 for (i = 0; i < fcu->totvert; bezt++, i++) {
529                         if (BEZT_ISSEL_ANY(bezt)) {
530                                 *first = bezt;
531                                 found = true;
532                                 break;
533                         }
534                 }
535                 
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)) {
540                                 *last = bezt;
541                                 found = true;
542                                 break;
543                         }
544                 }
545         }
546         else {
547                 /* just full array */
548                 *first = fcu->bezt;
549                 *last = ARRAY_LAST_ITEM(fcu->bezt, BezTriple, fcu->totvert);
550                 found = true;
551         }
552         
553         return found;
554 }
555
556
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)
560 {
561         float xminv = 999999999.0f, xmaxv = -999999999.0f;
562         float yminv = 999999999.0f, ymaxv = -999999999.0f;
563         bool foundvert = false;
564         unsigned int i;
565         
566         if (fcu->totvert) {
567                 if (fcu->bezt) {
568                         BezTriple *bezt_first = NULL, *bezt_last = NULL;
569                         
570                         if (xmin || xmax) {
571                                 /* get endpoint keyframes */
572                                 foundvert = get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only);
573                                 
574                                 if (bezt_first) {
575                                         BLI_assert(bezt_last != NULL);
576                                         
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]);
580                                         }
581                                         else {
582                                                 xminv = min_ff(xminv, bezt_first->vec[1][0]);
583                                                 xmaxv = max_ff(xmaxv, bezt_last->vec[1][0]);
584                                         }
585                                 }
586                         }
587                         
588                         /* only loop over keyframes to find extents for values if needed */
589                         if (ymin || ymax) {
590                                 BezTriple *bezt, *prevbezt = NULL;
591                                 
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]);
597                                                 
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
601                                                          */
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]);
605                                                         }
606                                                         
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]);
611                                                         }
612                                                 }
613                                                 
614                                                 foundvert = true;
615                                         }
616                                 }
617                         }
618                 }
619                 else if (fcu->fpt) {
620                         /* frame range can be directly calculated from end verts */
621                         if (xmin || xmax) {
622                                 xminv = min_ff(xminv, fcu->fpt[0].vec[0]);
623                                 xmaxv = max_ff(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]);
624                         }
625                         
626                         /* only loop over keyframes to find extents for values if needed */
627                         if (ymin || ymax) {
628                                 FPoint *fpt;
629                                 
630                                 for (fpt = fcu->fpt, i = 0; i < fcu->totvert; fpt++, i++) {
631                                         if (fpt->vec[1] < yminv)
632                                                 yminv = fpt->vec[1];
633                                         if (fpt->vec[1] > ymaxv)
634                                                 ymaxv = fpt->vec[1];
635                                         
636                                         foundvert = true;
637                                 }
638                         }
639                 }
640         }
641         
642         if (foundvert) {
643                 if (xmin) *xmin = xminv;
644                 if (xmax) *xmax = xmaxv;
645                 
646                 if (ymin) *ymin = yminv;
647                 if (ymax) *ymax = ymaxv;
648         }
649         else {
650                 if (G.debug & G_DEBUG)
651                         printf("F-Curve calc bounds didn't find anything, so assuming minimum bounds of 1.0\n");
652                         
653                 if (xmin) *xmin = 0.0f;
654                 if (xmax) *xmax = 1.0f;
655                 
656                 if (ymin) *ymin = 0.0f;
657                 if (ymax) *ymax = 1.0f;
658         }
659         
660         return foundvert;
661 }
662
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)
666 {
667         float min = 999999999.0f, max = -999999999.0f;
668         bool foundvert = false;
669
670         if (fcu->totvert) {
671                 if (fcu->bezt) {
672                         BezTriple *bezt_first = NULL, *bezt_last = NULL;
673                         
674                         /* get endpoint keyframes */
675                         get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only);
676                         
677                         if (bezt_first) {
678                                 BLI_assert(bezt_last != NULL);
679                                 
680                                 min = min_ff(min, bezt_first->vec[1][0]);
681                                 max = max_ff(max, bezt_last->vec[1][0]);
682                                 
683                                 foundvert = true;
684                         }
685                 }
686                 else if (fcu->fpt) {
687                         min = min_ff(min, fcu->fpt[0].vec[0]);
688                         max = max_ff(max, fcu->fpt[fcu->totvert - 1].vec[0]);
689                         
690                         foundvert = true;
691                 }
692                 
693         }
694         
695         if (foundvert == false) {
696                 min = max = 0.0f;
697         }
698
699         if (do_min_length) {
700                 /* minimum length is 1 frame */
701                 if (min == max) {
702                         max += 1.0f;
703                 }
704         }
705
706         *start = min;
707         *end = max;
708
709         return foundvert;
710 }
711
712 /* ----------------- Status Checks -------------------------- */
713
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.
717  */
718 bool fcurve_are_keyframes_usable(FCurve *fcu)
719 {
720         /* F-Curve must exist */
721         if (fcu == NULL)
722                 return false;
723                 
724         /* F-Curve must not have samples - samples are mutually exclusive of keyframes */
725         if (fcu->fpt)
726                 return false;
727         
728         /* if it has modifiers, none of these should "drastically" alter the curve */
729         if (fcu->modifiers.first) {
730                 FModifier *fcm;
731
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))
737                                 continue;
738                                 
739                         /* type checks */
740                         switch (fcm->type) {
741                                 /* clearly harmless - do nothing */
742                                 case FMODIFIER_TYPE_CYCLES:
743                                 case FMODIFIER_TYPE_STEPPED:
744                                 case FMODIFIER_TYPE_NOISE:
745                                         break;
746                                         
747                                 /* sometimes harmful - depending on whether they're "additive" or not */
748                                 case FMODIFIER_TYPE_GENERATOR:
749                                 {
750                                         FMod_Generator *data = (FMod_Generator *)fcm->data;
751                                         
752                                         if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0)
753                                                 return false;
754                                         break;
755                                 }
756                                 case FMODIFIER_TYPE_FN_GENERATOR:
757                                 {
758                                         FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data;
759                                         
760                                         if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0)
761                                                 return false;
762                                         break;
763                                 }
764                                 /* always harmful - cannot allow */
765                                 default:
766                                         return false;
767                         }
768                 }
769         }
770         
771         /* keyframes are usable */
772         return true;
773 }
774
775 bool BKE_fcurve_is_protected(FCurve *fcu)
776 {
777         return ((fcu->flag & FCURVE_PROTECTED) ||
778                 ((fcu->grp) && (fcu->grp->flag & AGRP_PROTECTED)));
779 }
780
781 /* Can keyframes be added to F-Curve? 
782  * Keyframes can only be added if they are already visible
783  */
784 bool fcurve_is_keyframable(FCurve *fcu)
785 {
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)
788                 return false;
789                 
790         /* F-Curve must currently be editable too */
791         if (BKE_fcurve_is_protected(fcu))
792                 return false;
793         
794         /* F-Curve is keyframable */
795         return true;
796 }
797
798 /* ***************************** Keyframe Column Tools ********************************* */
799
800 /* add a BezTriple to a column */
801 void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt)
802 {
803         CfraElem *ce, *cen;
804         
805         for (ce = lb->first; ce; ce = ce->next) {
806                 /* double key? */
807                 if (ce->cfra == bezt->vec[1][0]) {
808                         if (bezt->f2 & SELECT) ce->sel = bezt->f2;
809                         return;
810                 }
811                 /* should key be inserted before this column? */
812                 else if (ce->cfra > bezt->vec[1][0]) break;
813         }
814         
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);
819
820         cen->cfra = bezt->vec[1][0];
821         cen->sel = bezt->f2;
822 }
823
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.
828  */
829  
830  
831 /* Basic sampling callback which acts as a wrapper for evaluate_fcurve() 
832  *      'data' arg here is unneeded here...
833  */
834 float fcurve_samplingcb_evalcurve(FCurve *fcu, void *UNUSED(data), float evaltime)
835 {
836         /* assume any interference from drivers on the curve is intended... */
837         return evaluate_fcurve(fcu, evaltime);
838
839
840  
841 /* Main API function for creating a set of sampled curve data, given some callback function 
842  * used to retrieve the values to store.
843  */
844 void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSampleFunc sample_cb)
845 {
846         FPoint *fpt, *new_fpt;
847         int cfra;
848         
849         /* sanity checks */
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");
853                 return;
854         }
855         if (start > end) {
856                 printf("Error: Frame range for Sampled F-Curve creation is inappropriate\n");
857                 return;
858         }
859         
860         /* set up sample data */
861         fpt = new_fpt = MEM_callocN(sizeof(FPoint) * (end - start + 1), "FPoint Samples");
862         
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);
867         }
868         
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);
872         
873         /* store the samples */
874         fcu->bezt = NULL;
875         fcu->fpt = new_fpt;
876         fcu->totvert = end - start + 1;
877 }
878
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 
883  */
884
885 /* This function recalculates the handles of an F-Curve 
886  * If the BezTriples have been rearranged, sort them first before using this.
887  */
888 void calchandles_fcurve(FCurve *fcu)
889 {
890         BezTriple *bezt, *prev, *next;
891         int a = fcu->totvert;
892
893         /* Error checking:
894          *      - need at least two points
895          *      - need bezier keys
896          *      - only bezier-interpolation has handles (for now)
897          */
898         if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/) 
899                 return;
900         
901         /* get initial pointers */
902         bezt = fcu->bezt;
903         prev = NULL;
904         next = (bezt + 1);
905         
906         /* loop over all beztriples, adjusting handles */
907         while (a--) {
908                 /* clamp timing of handles to be on either side of beztriple */
909                 if (bezt->vec[0][0] > bezt->vec[1][0]) bezt->vec[0][0] = bezt->vec[1][0];
910                 if (bezt->vec[2][0] < bezt->vec[1][0]) bezt->vec[2][0] = bezt->vec[1][0];
911                 
912                 /* calculate auto-handles */
913                 BKE_nurb_handle_calc(bezt, prev, next, true);
914                 
915                 /* for automatic ease in and out */
916                 if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM) && ELEM(bezt->h2, HD_AUTO, HD_AUTO_ANIM)) {
917                         /* only do this on first or last beztriple */
918                         if ((a == 0) || (a == fcu->totvert - 1)) {
919                                 /* set both handles to have same horizontal value as keyframe */
920                                 if (fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) {
921                                         bezt->vec[0][1] = bezt->vec[2][1] = bezt->vec[1][1];
922                                 }
923                         }
924                 }
925                 
926                 /* advance pointers for next iteration */
927                 prev = bezt;
928                 if (a == 1) next = NULL;
929                 else next++;
930                 bezt++;
931         }
932 }
933
934 void testhandles_fcurve(FCurve *fcu, const bool use_handle)
935 {
936         BezTriple *bezt;
937         unsigned int a;
938
939         /* only beztriples have handles (bpoints don't though) */
940         if (ELEM(NULL, fcu, fcu->bezt))
941                 return;
942
943         /* loop over beztriples */
944         for (a = 0, bezt = fcu->bezt; a < fcu->totvert; a++, bezt++) {
945                 BKE_nurb_bezt_handle_test(bezt, use_handle);
946         }
947
948         /* recalculate handles */
949         calchandles_fcurve(fcu);
950 }
951
952 /* This function sorts BezTriples so that they are arranged in chronological order,
953  * as tools working on F-Curves expect that the BezTriples are in order.
954  */
955 void sort_time_fcurve(FCurve *fcu)
956 {
957         bool ok = true;
958         
959         /* keep adjusting order of beztriples until nothing moves (bubble-sort) */
960         while (ok) {
961                 ok = 0;
962                 
963                 /* currently, will only be needed when there are beztriples */
964                 if (fcu->bezt) {
965                         BezTriple *bezt;
966                         unsigned int a;
967                         
968                         /* loop over ALL points to adjust position in array and recalculate handles */
969                         for (a = 0, bezt = fcu->bezt; a < fcu->totvert; a++, bezt++) {
970                                 /* check if thee's a next beztriple which we could try to swap with current */
971                                 if (a < (fcu->totvert - 1)) {
972                                         /* swap if one is after the other (and indicate that order has changed) */
973                                         if (bezt->vec[1][0] > (bezt + 1)->vec[1][0]) {
974                                                 SWAP(BezTriple, *bezt, *(bezt + 1));
975                                                 ok = 1;
976                                         }
977                                         
978                                         /* if either one of both of the points exceeds crosses over the keyframe time... */
979                                         if ( (bezt->vec[0][0] > bezt->vec[1][0]) && (bezt->vec[2][0] < bezt->vec[1][0]) ) {
980                                                 /* swap handles if they have switched sides for some reason */
981                                                 swap_v2_v2(bezt->vec[0], bezt->vec[2]);
982                                         }
983                                         else {
984                                                 /* clamp handles */
985                                                 CLAMP_MAX(bezt->vec[0][0], bezt->vec[1][0]);
986                                                 CLAMP_MIN(bezt->vec[2][0], bezt->vec[1][0]);
987                                         }
988                                 }
989                         }
990                 }
991         }
992 }
993
994 /* This function tests if any BezTriples are out of order, thus requiring a sort */
995 short test_time_fcurve(FCurve *fcu)
996 {
997         unsigned int a;
998         
999         /* sanity checks */
1000         if (fcu == NULL)
1001                 return 0;
1002         
1003         /* currently, only need to test beztriples */
1004         if (fcu->bezt) {
1005                 BezTriple *bezt;
1006                 
1007                 /* loop through all BezTriples, stopping when one exceeds the one after it */
1008                 for (a = 0, bezt = fcu->bezt; a < (fcu->totvert - 1); a++, bezt++) {
1009                         if (bezt->vec[1][0] > (bezt + 1)->vec[1][0])
1010                                 return 1;
1011                 }
1012         }
1013         else if (fcu->fpt) {
1014                 FPoint *fpt;
1015                 
1016                 /* loop through all FPoints, stopping when one exceeds the one after it */
1017                 for (a = 0, fpt = fcu->fpt; a < (fcu->totvert - 1); a++, fpt++) {
1018                         if (fpt->vec[0] > (fpt + 1)->vec[0])
1019                                 return 1;
1020                 }
1021         }
1022         
1023         /* none need any swapping */
1024         return 0;
1025 }
1026
1027 /* ***************************** Drivers ********************************* */
1028
1029 /* Driver Variables --------------------------- */
1030
1031 /* TypeInfo for Driver Variables (dvti) */
1032 typedef struct DriverVarTypeInfo {
1033         /* evaluation callback */
1034         float (*get_value)(ChannelDriver *driver, DriverVar *dvar);
1035         
1036         /* allocation of target slots */
1037         int num_targets;                                        /* number of target slots required */
1038         const char *target_names[MAX_DRIVER_TARGETS];   /* UI names that should be given to the slots */
1039         short target_flags[MAX_DRIVER_TARGETS];                 /* flags defining the requirements for each slot */
1040 } DriverVarTypeInfo;
1041
1042 /* Macro to begin definitions */
1043 #define BEGIN_DVAR_TYPEDEF(type) \
1044         {
1045         
1046 /* Macro to end definitions */
1047 #define END_DVAR_TYPEDEF \
1048         }
1049
1050 /* ......... */
1051
1052 static ID *dtar_id_ensure_proxy_from(ID *id)
1053 {
1054         if (id && GS(id->name) == ID_OB && ((Object *)id)->proxy_from)
1055                 return (ID *)(((Object *)id)->proxy_from);
1056         return id;
1057 }
1058
1059 /* Helper function to obtain a value using RNA from the specified source (for evaluating drivers) */
1060 static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar)
1061 {
1062         PointerRNA id_ptr, ptr;
1063         PropertyRNA *prop;
1064         ID *id;
1065         int index = -1;
1066         float value = 0.0f;
1067         
1068         /* sanity check */
1069         if (ELEM(NULL, driver, dtar))
1070                 return 0.0f;
1071         
1072         id = dtar_id_ensure_proxy_from(dtar->id);
1073         
1074         /* error check for missing pointer... */
1075         if (id == NULL) {
1076                 if (G.debug & G_DEBUG) {
1077                         printf("Error: driver has an invalid target to use (path = %s)\n", dtar->rna_path);
1078                 }
1079                 
1080                 driver->flag |= DRIVER_FLAG_INVALID;
1081                 dtar->flag   |= DTAR_FLAG_INVALID;
1082                 return 0.0f;
1083         }
1084         
1085         /* get RNA-pointer for the ID-block given in target */
1086         RNA_id_pointer_create(id, &id_ptr);
1087         
1088         /* get property to read from, and get value as appropriate */
1089         if (RNA_path_resolve_property_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) {
1090                 if (RNA_property_array_check(prop)) {
1091                         /* array */
1092                         if ((index >= 0) && (index < RNA_property_array_length(&ptr, prop))) {
1093                                 switch (RNA_property_type(prop)) {
1094                                         case PROP_BOOLEAN:
1095                                                 value = (float)RNA_property_boolean_get_index(&ptr, prop, index);
1096                                                 break;
1097                                         case PROP_INT:
1098                                                 value = (float)RNA_property_int_get_index(&ptr, prop, index);
1099                                                 break;
1100                                         case PROP_FLOAT:
1101                                                 value = RNA_property_float_get_index(&ptr, prop, index);
1102                                                 break;
1103                                         default:
1104                                                 break;
1105                                 }
1106                         }
1107                         else {
1108                                 /* out of bounds */
1109                                 if (G.debug & G_DEBUG) {
1110                                         printf("Driver Evaluation Error: array index is out of bounds for %s -> %s (%d)", 
1111                                                id->name, dtar->rna_path, index);
1112                                 }
1113                                 
1114                                 driver->flag |= DRIVER_FLAG_INVALID;
1115                                 dtar->flag   |= DTAR_FLAG_INVALID;
1116                                 return 0.0f;
1117                         }
1118                 }
1119                 else {
1120                         /* not an array */
1121                         switch (RNA_property_type(prop)) {
1122                                 case PROP_BOOLEAN:
1123                                         value = (float)RNA_property_boolean_get(&ptr, prop);
1124                                         break;
1125                                 case PROP_INT:
1126                                         value = (float)RNA_property_int_get(&ptr, prop);
1127                                         break;
1128                                 case PROP_FLOAT:
1129                                         value = RNA_property_float_get(&ptr, prop);
1130                                         break;
1131                                 case PROP_ENUM:
1132                                         value = (float)RNA_property_enum_get(&ptr, prop);
1133                                         break;
1134                                 default:
1135                                         break;
1136                         }
1137                 }
1138         }
1139         else {
1140                 /* path couldn't be resolved */
1141                 if (G.debug & G_DEBUG) {
1142                         printf("Driver Evaluation Error: cannot resolve target for %s -> %s\n", id->name, dtar->rna_path);
1143                 }
1144                 
1145                 driver->flag |= DRIVER_FLAG_INVALID;
1146                 dtar->flag   |= DTAR_FLAG_INVALID;
1147                 return 0.0f;
1148         }
1149         
1150         /* if we're still here, we should be ok... */
1151         dtar->flag &= ~DTAR_FLAG_INVALID;
1152         return value;
1153 }
1154
1155 /**
1156  * Same as 'dtar_get_prop_val'. but get the RNA property.
1157  */
1158 bool driver_get_variable_property(
1159         ChannelDriver *driver, DriverTarget *dtar,
1160         PointerRNA *r_ptr, PropertyRNA **r_prop, int *r_index)
1161 {
1162         PointerRNA id_ptr;
1163         PointerRNA ptr;
1164         PropertyRNA *prop;
1165         ID *id;
1166         int index = -1;
1167
1168         /* sanity check */
1169         if (ELEM(NULL, driver, dtar))
1170                 return false;
1171
1172         id = dtar_id_ensure_proxy_from(dtar->id);
1173
1174         /* error check for missing pointer... */
1175         if (id == NULL) {
1176                 if (G.debug & G_DEBUG) {
1177                         printf("Error: driver has an invalid target to use (path = %s)\n", dtar->rna_path);
1178                 }
1179
1180                 driver->flag |= DRIVER_FLAG_INVALID;
1181                 dtar->flag   |= DTAR_FLAG_INVALID;
1182                 return false;
1183         }
1184
1185         /* get RNA-pointer for the ID-block given in target */
1186         RNA_id_pointer_create(id, &id_ptr);
1187
1188         /* get property to read from, and get value as appropriate */
1189         if (dtar->rna_path == NULL || dtar->rna_path[0] == '\0') {
1190                 ptr = PointerRNA_NULL;
1191                 prop = NULL; /* ok */
1192         }
1193         else if (RNA_path_resolve_property_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) {
1194                 /* ok */
1195         }
1196         else {
1197                 /* path couldn't be resolved */
1198                 if (G.debug & G_DEBUG) {
1199                         printf("Driver Evaluation Error: cannot resolve target for %s -> %s\n", id->name, dtar->rna_path);
1200                 }
1201
1202                 ptr = PointerRNA_NULL;
1203                 *r_prop = NULL;
1204                 *r_index = -1;
1205
1206                 driver->flag |= DRIVER_FLAG_INVALID;
1207                 dtar->flag   |= DTAR_FLAG_INVALID;
1208                 return false;
1209         }
1210
1211         *r_ptr = ptr;
1212         *r_prop = prop;
1213         *r_index = index;
1214
1215         /* if we're still here, we should be ok... */
1216         dtar->flag &= ~DTAR_FLAG_INVALID;
1217         return true;
1218 }
1219
1220 #if 0
1221 /* Helper function to obtain a pointer to a Pose Channel (for evaluating drivers) */
1222 static bPoseChannel *dtar_get_pchan_ptr(ChannelDriver *driver, DriverTarget *dtar)
1223 {
1224         ID *id;
1225         /* sanity check */
1226         if (ELEM(NULL, driver, dtar))
1227                 return NULL;
1228
1229         id = dtar_id_ensure_proxy_from(dtar->id);
1230
1231         /* check if the ID here is a valid object */
1232         if (id && GS(id->name)) {
1233                 Object *ob = (Object *)id;
1234                 
1235                 /* get pose, and subsequently, posechannel */
1236                 return BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1237         }
1238         else {
1239                 /* cannot find a posechannel this way */
1240                 return NULL;
1241         }
1242 }
1243 #endif
1244
1245 static short driver_check_valid_targets(ChannelDriver *driver, DriverVar *dvar)
1246 {
1247         short valid_targets = 0;
1248
1249         DRIVER_TARGETS_USED_LOOPER(dvar)
1250         {
1251                 Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1252
1253                 /* check if this target has valid data */
1254                 if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) {
1255                         /* invalid target, so will not have enough targets */
1256                         driver->flag |= DRIVER_FLAG_INVALID;
1257                         dtar->flag |= DTAR_FLAG_INVALID;
1258                 }
1259                 else {
1260                         /* target seems to be OK now... */
1261                         dtar->flag &= ~DTAR_FLAG_INVALID;
1262                         valid_targets++;
1263                 }
1264         }
1265         DRIVER_TARGETS_LOOPER_END
1266
1267         return valid_targets;
1268 }
1269
1270 /* ......... */
1271
1272 /* evaluate 'single prop' driver variable */
1273 static float dvar_eval_singleProp(ChannelDriver *driver, DriverVar *dvar)
1274 {
1275         /* just evaluate the first target slot */
1276         return dtar_get_prop_val(driver, &dvar->targets[0]);
1277 }
1278
1279 /* evaluate 'rotation difference' driver variable */
1280 static float dvar_eval_rotDiff(ChannelDriver *driver, DriverVar *dvar)
1281 {
1282         short valid_targets = driver_check_valid_targets(driver, dvar);
1283
1284         /* make sure we have enough valid targets to use - all or nothing for now... */
1285         if (driver_check_valid_targets(driver, dvar) != 2) {
1286                 if (G.debug & G_DEBUG) {
1287                         printf("RotDiff DVar: not enough valid targets (n = %d) (a = %p, b = %p)\n",
1288                                 valid_targets, dvar->targets[0].id, dvar->targets[1].id);
1289                 }
1290                 return 0.0f;
1291         }
1292
1293         float (*mat[2])[4];
1294
1295         /* NOTE: for now, these are all just worldspace */
1296         for (int i = 0; i < 2; i++) {
1297                 /* get pointer to loc values to store in */
1298                 DriverTarget *dtar = &dvar->targets[i];
1299                 Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1300                 bPoseChannel *pchan;
1301
1302                 /* after the checks above, the targets should be valid here... */
1303                 BLI_assert((ob != NULL) && (GS(ob->id.name) == ID_OB));
1304
1305                 /* try to get posechannel */
1306                 pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1307
1308                 /* check if object or bone */
1309                 if (pchan) {
1310                         /* bone */
1311                         mat[i] = pchan->pose_mat;
1312                 }
1313                 else {
1314                         /* object */
1315                         mat[i] = ob->obmat;
1316                 }
1317         }
1318
1319         float q1[4], q2[4], quat[4], angle;
1320
1321         /* use the final posed locations */
1322         mat4_to_quat(q1, mat[0]);
1323         mat4_to_quat(q2, mat[1]);
1324
1325         invert_qt_normalized(q1);
1326         mul_qt_qtqt(quat, q1, q2);
1327         angle = 2.0f * (saacos(quat[0]));
1328         angle = ABS(angle);
1329
1330         return (angle > (float)M_PI) ? (float)((2.0f * (float)M_PI) - angle) : (float)(angle);
1331 }
1332
1333 /* evaluate 'location difference' driver variable */
1334 /* TODO: this needs to take into account space conversions... */
1335 static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar)
1336 {
1337         float loc1[3] = {0.0f, 0.0f, 0.0f};
1338         float loc2[3] = {0.0f, 0.0f, 0.0f};
1339         short valid_targets = driver_check_valid_targets(driver, dvar);
1340
1341         /* make sure we have enough valid targets to use - all or nothing for now... */
1342         if (valid_targets < dvar->num_targets) {
1343                 if (G.debug & G_DEBUG) {
1344                         printf("LocDiff DVar: not enough valid targets (n = %d) (a = %p, b = %p)\n",
1345                                 valid_targets, dvar->targets[0].id, dvar->targets[1].id);
1346                 }
1347                 return 0.0f;
1348         }
1349
1350         /* SECOND PASS: get two location values */
1351         /* NOTE: for now, these are all just worldspace */
1352         DRIVER_TARGETS_USED_LOOPER(dvar)
1353         {
1354                 /* get pointer to loc values to store in */
1355                 Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1356                 bPoseChannel *pchan;
1357                 float tmp_loc[3];
1358                 
1359                 /* after the checks above, the targets should be valid here... */
1360                 BLI_assert((ob != NULL) && (GS(ob->id.name) == ID_OB));
1361                 
1362                 /* try to get posechannel */
1363                 pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1364                 
1365                 /* check if object or bone */
1366                 if (pchan) {
1367                         /* bone */
1368                         if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1369                                 if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1370                                         float mat[4][4];
1371                                         
1372                                         /* extract transform just like how the constraints do it! */
1373                                         copy_m4_m4(mat, pchan->pose_mat);
1374                                         BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false);
1375                                         
1376                                         /* ... and from that, we get our transform */
1377                                         copy_v3_v3(tmp_loc, mat[3]);
1378                                 }
1379                                 else {
1380                                         /* transform space (use transform values directly) */
1381                                         copy_v3_v3(tmp_loc, pchan->loc);
1382                                 }
1383                         }
1384                         else {
1385                                 /* convert to worldspace */
1386                                 copy_v3_v3(tmp_loc, pchan->pose_head);
1387                                 mul_m4_v3(ob->obmat, tmp_loc);
1388                         }
1389                 }
1390                 else {
1391                         /* object */
1392                         if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1393                                 if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1394                                         /* XXX: this should practically be the same as transform space... */
1395                                         float mat[4][4];
1396                                         
1397                                         /* extract transform just like how the constraints do it! */
1398                                         copy_m4_m4(mat, ob->obmat);
1399                                         BKE_constraint_mat_convertspace(ob, NULL, mat, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL, false);
1400                                         
1401                                         /* ... and from that, we get our transform */
1402                                         copy_v3_v3(tmp_loc, mat[3]);
1403                                 }
1404                                 else {
1405                                         /* transform space (use transform values directly) */
1406                                         copy_v3_v3(tmp_loc, ob->loc);
1407                                 }
1408                         }
1409                         else {
1410                                 /* worldspace */
1411                                 copy_v3_v3(tmp_loc, ob->obmat[3]);
1412                         }
1413                 }
1414                 
1415                 /* copy the location to the right place */
1416                 if (tarIndex) {
1417                         copy_v3_v3(loc2, tmp_loc);
1418                 }
1419                 else {
1420                         copy_v3_v3(loc1, tmp_loc);
1421                 }
1422         }
1423         DRIVER_TARGETS_LOOPER_END
1424         
1425         
1426         /* if we're still here, there should now be two targets to use,
1427          * so just take the length of the vector between these points 
1428          */
1429         return len_v3v3(loc1, loc2);
1430 }
1431
1432 /* evaluate 'transform channel' driver variable */
1433 static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar)
1434 {
1435         DriverTarget *dtar = &dvar->targets[0];
1436         Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
1437         bPoseChannel *pchan;
1438         float mat[4][4];
1439         float oldEul[3] = {0.0f, 0.0f, 0.0f};
1440         bool use_eulers = false;
1441         short rot_order = ROT_MODE_EUL;
1442         
1443         /* check if this target has valid data */
1444         if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) {
1445                 /* invalid target, so will not have enough targets */
1446                 driver->flag |= DRIVER_FLAG_INVALID;
1447                 dtar->flag   |= DTAR_FLAG_INVALID;
1448                 return 0.0f;
1449         }
1450         else {
1451                 /* target should be valid now */
1452                 dtar->flag &= ~DTAR_FLAG_INVALID;
1453         }
1454         
1455         /* try to get posechannel */
1456         pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
1457         
1458         /* check if object or bone, and get transform matrix accordingly 
1459          *      - "useEulers" code is used to prevent the problems associated with non-uniqueness
1460          *        of euler decomposition from matrices [#20870]
1461          *      - localspace is for [#21384], where parent results are not wanted
1462          *        but local-consts is for all the common "corrective-shapes-for-limbs" situations
1463          */
1464         if (pchan) {
1465                 /* bone */
1466                 if (pchan->rotmode > 0) {
1467                         copy_v3_v3(oldEul, pchan->eul);
1468                         rot_order = pchan->rotmode;
1469                         use_eulers = true;
1470                 }
1471                 
1472                 if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1473                         if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1474                                 /* just like how the constraints do it! */
1475                                 copy_m4_m4(mat, pchan->pose_mat);
1476                                 BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false);
1477                         }
1478                         else {
1479                                 /* specially calculate local matrix, since chan_mat is not valid 
1480                                  * since it stores delta transform of pose_mat so that deforms work
1481                                  * so it cannot be used here for "transform" space
1482                                  */
1483                                 BKE_pchan_to_mat4(pchan, mat);
1484                         }
1485                 }
1486                 else {
1487                         /* worldspace matrix */
1488                         mul_m4_m4m4(mat, ob->obmat, pchan->pose_mat);
1489                 }
1490         }
1491         else {
1492                 /* object */
1493                 if (ob->rotmode > 0) {
1494                         copy_v3_v3(oldEul, ob->rot);
1495                         rot_order = ob->rotmode;
1496                         use_eulers = true;
1497                 }
1498                 
1499                 if (dtar->flag & DTAR_FLAG_LOCALSPACE) {
1500                         if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) {
1501                                 /* just like how the constraints do it! */
1502                                 copy_m4_m4(mat, ob->obmat);
1503                                 BKE_constraint_mat_convertspace(ob, NULL, mat, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL, false);
1504                         }
1505                         else {
1506                                 /* transforms to matrix */
1507                                 BKE_object_to_mat4(ob, mat);
1508                         }
1509                 }
1510                 else {
1511                         /* worldspace matrix - just the good-old one */
1512                         copy_m4_m4(mat, ob->obmat);
1513                 }
1514         }
1515         
1516         /* check which transform */
1517         if (dtar->transChan >= MAX_DTAR_TRANSCHAN_TYPES) {
1518                 /* not valid channel */
1519                 return 0.0f;
1520         }
1521         else if (dtar->transChan >= DTAR_TRANSCHAN_SCALEX) {
1522                 /* extract scale, and choose the right axis */
1523                 float scale[3];
1524                 
1525                 mat4_to_size(scale, mat);
1526                 return scale[dtar->transChan - DTAR_TRANSCHAN_SCALEX];
1527         }
1528         else if (dtar->transChan >= DTAR_TRANSCHAN_ROTX) {
1529                 /* extract rotation as eulers (if needed) 
1530                  *      - definitely if rotation order isn't eulers already
1531                  *      - if eulers, then we have 2 options:
1532                  *              a) decompose transform matrix as required, then try to make eulers from
1533                  *                 there compatible with original values
1534                  *              b) [NOT USED] directly use the original values (no decomposition) 
1535                  *                      - only an option for "transform space", if quality is really bad with a)
1536                  */
1537                 float eul[3];
1538                 
1539                 mat4_to_eulO(eul, rot_order, mat);
1540                 
1541                 if (use_eulers) {
1542                         compatible_eul(eul, oldEul);
1543                 }
1544                 
1545                 return eul[dtar->transChan - DTAR_TRANSCHAN_ROTX];
1546         }
1547         else {
1548                 /* extract location and choose right axis */
1549                 return mat[3][dtar->transChan];
1550         }
1551 }
1552
1553 /* ......... */
1554
1555 /* Table of Driver Varaiable Type Info Data */
1556 static DriverVarTypeInfo dvar_types[MAX_DVAR_TYPES] = {
1557         BEGIN_DVAR_TYPEDEF(DVAR_TYPE_SINGLE_PROP)
1558                 dvar_eval_singleProp,     /* eval callback */
1559                 1,     /* number of targets used */
1560                 {"Property"},     /* UI names for targets */
1561                 {0}     /* flags */
1562         END_DVAR_TYPEDEF,
1563         
1564         BEGIN_DVAR_TYPEDEF(DVAR_TYPE_ROT_DIFF)
1565                 dvar_eval_rotDiff,     /* eval callback */
1566                 2,     /* number of targets used */
1567                 {"Object/Bone 1", "Object/Bone 2"},     /* UI names for targets */
1568                 {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */
1569         END_DVAR_TYPEDEF,
1570         
1571         BEGIN_DVAR_TYPEDEF(DVAR_TYPE_LOC_DIFF)
1572                 dvar_eval_locDiff,     /* eval callback */
1573                 2,     /* number of targets used */
1574                 {"Object/Bone 1", "Object/Bone 2"},     /* UI names for targets */
1575                 {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */
1576         END_DVAR_TYPEDEF,
1577         
1578         BEGIN_DVAR_TYPEDEF(DVAR_TYPE_TRANSFORM_CHAN)
1579                 dvar_eval_transChan,     /* eval callback */
1580                 1,     /* number of targets used */
1581                 {"Object/Bone"},     /* UI names for targets */
1582                 {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY}   /* flags */
1583         END_DVAR_TYPEDEF,
1584 };
1585
1586 /* Get driver variable typeinfo */
1587 static const DriverVarTypeInfo *get_dvar_typeinfo(int type)
1588 {
1589         /* check if valid type */
1590         if ((type >= 0) && (type < MAX_DVAR_TYPES))
1591                 return &dvar_types[type];
1592         else
1593                 return NULL;
1594 }
1595
1596 /* Driver API --------------------------------- */
1597
1598 /* Perform actual freeing driver variable and remove it from the given list */
1599 void driver_free_variable(ListBase *variables, DriverVar *dvar)
1600 {
1601         /* sanity checks */
1602         if (dvar == NULL)
1603                 return;
1604                 
1605         /* free target vars 
1606          *      - need to go over all of them, not just up to the ones that are used
1607          *        currently, since there may be some lingering RNA paths from 
1608          *    previous users needing freeing
1609          */
1610         DRIVER_TARGETS_LOOPER(dvar) 
1611         {
1612                 /* free RNA path if applicable */
1613                 if (dtar->rna_path)
1614                         MEM_freeN(dtar->rna_path);
1615         }
1616         DRIVER_TARGETS_LOOPER_END
1617         
1618         /* remove the variable from the driver */
1619         BLI_freelinkN(variables, dvar);
1620 }
1621
1622 /* Free the driver variable and do extra updates */
1623 void driver_free_variable_ex(ChannelDriver *driver, DriverVar *dvar)
1624 {
1625         /* remove and free the driver variable */
1626         driver_free_variable(&driver->variables, dvar);
1627         
1628 #ifdef WITH_PYTHON
1629         /* since driver variables are cached, the expression needs re-compiling too */
1630         if (driver->type == DRIVER_TYPE_PYTHON)
1631                 driver->flag |= DRIVER_FLAG_RENAMEVAR;
1632 #endif
1633 }
1634
1635 /* Copy driver variables from src_vars list to dst_vars list */
1636 void driver_variables_copy(ListBase *dst_vars, const ListBase *src_vars)
1637 {
1638         BLI_assert(BLI_listbase_is_empty(dst_vars));
1639         BLI_duplicatelist(dst_vars, src_vars);
1640         
1641         for (DriverVar *dvar = dst_vars->first; dvar; dvar = dvar->next) {
1642                 /* need to go over all targets so that we don't leave any dangling paths */
1643                 DRIVER_TARGETS_LOOPER(dvar) 
1644                 {
1645                         /* make a copy of target's rna path if available */
1646                         if (dtar->rna_path)
1647                                 dtar->rna_path = MEM_dupallocN(dtar->rna_path);
1648                 }
1649                 DRIVER_TARGETS_LOOPER_END
1650         }
1651 }
1652
1653 /* Change the type of driver variable */
1654 void driver_change_variable_type(DriverVar *dvar, int type)
1655 {
1656         const DriverVarTypeInfo *dvti = get_dvar_typeinfo(type);
1657         
1658         /* sanity check */
1659         if (ELEM(NULL, dvar, dvti))
1660                 return;
1661                 
1662         /* set the new settings */
1663         dvar->type = type;
1664         dvar->num_targets = dvti->num_targets;
1665         
1666         /* make changes to the targets based on the defines for these types 
1667          * NOTE: only need to make sure the ones we're using here are valid...
1668          */
1669         DRIVER_TARGETS_USED_LOOPER(dvar)
1670         {
1671                 short flags = dvti->target_flags[tarIndex];
1672                 
1673                 /* store the flags */
1674                 dtar->flag = flags;
1675                 
1676                 /* object ID types only, or idtype not yet initialized */
1677                 if ((flags & DTAR_FLAG_ID_OB_ONLY) || (dtar->idtype == 0))
1678                         dtar->idtype = ID_OB;
1679         }
1680         DRIVER_TARGETS_LOOPER_END
1681 }
1682
1683 /* Validate driver name (after being renamed) */
1684 void driver_variable_name_validate(DriverVar *dvar)
1685 {
1686         /* Special character blacklist */
1687         const char special_char_blacklist[] = {
1688             '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '+', '=', '-',
1689             '/', '\\', '?', ':', ';',  '<', '>', '{', '}', '[', ']', '|',
1690             ' ', '.', '\t', '\n', '\r'
1691         };
1692         
1693         /* sanity checks */
1694         if (dvar == NULL)
1695                 return;
1696         
1697         /* clear all invalid-name flags */
1698         dvar->flag &= ~DVAR_ALL_INVALID_FLAGS;
1699         
1700         /* 0) Zero-length identifiers are not allowed */
1701         if (dvar->name[0] == '\0') {
1702                 dvar->flag |= DVAR_FLAG_INVALID_EMPTY;
1703         }
1704         
1705         /* 1) Must start with a letter */
1706         /* XXX: We assume that valid unicode letters in other languages are ok too, hence the blacklisting */
1707         if (ELEM(dvar->name[0], '0', '1', '2', '3', '4', '5', '6', '7', '8', '9')) {
1708                 dvar->flag |= DVAR_FLAG_INVALID_START_NUM;
1709         }
1710         else if (dvar->name[0] == '_') {
1711                 /* NOTE: We don't allow names to start with underscores (i.e. it helps when ruling out security risks) */
1712                 dvar->flag |= DVAR_FLAG_INVALID_START_CHAR;
1713         }
1714         
1715         /* 2) Must not contain invalid stuff in the middle of the string */
1716         if (strchr(dvar->name, ' ')) {
1717                 dvar->flag |= DVAR_FLAG_INVALID_HAS_SPACE;
1718         }
1719         if (strchr(dvar->name, '.')) {
1720                 dvar->flag |= DVAR_FLAG_INVALID_HAS_DOT;
1721         }
1722         
1723         /* 3) Check for special characters - Either at start, or in the middle */
1724         for (int i = 0; i < sizeof(special_char_blacklist); i++) {
1725                 char *match = strchr(dvar->name, special_char_blacklist[i]);
1726                 
1727                 if (match == dvar->name)
1728                         dvar->flag |= DVAR_FLAG_INVALID_START_CHAR;
1729                 else if (match != NULL)
1730                         dvar->flag |= DVAR_FLAG_INVALID_HAS_SPECIAL;
1731         }
1732         
1733         /* 4) Check if the name is a reserved keyword
1734          * NOTE: These won't confuse Python, but it will be impossible to use the variable
1735          *       in an expression without Python misinterpreting what these are for
1736          */
1737 #ifdef WITH_PYTHON
1738         if (BPY_string_is_keyword(dvar->name)) {
1739                 dvar->flag |= DVAR_FLAG_INVALID_PY_KEYWORD;
1740         }
1741 #endif
1742
1743         /* If any these conditions match, the name is invalid */
1744         if (dvar->flag & DVAR_ALL_INVALID_FLAGS)
1745                 dvar->flag |= DVAR_FLAG_INVALID_NAME;
1746 }
1747
1748 /* Add a new driver variable */
1749 DriverVar *driver_add_new_variable(ChannelDriver *driver)
1750 {
1751         DriverVar *dvar;
1752         
1753         /* sanity checks */
1754         if (driver == NULL)
1755                 return NULL;
1756                 
1757         /* make a new variable */
1758         dvar = MEM_callocN(sizeof(DriverVar), "DriverVar");
1759         BLI_addtail(&driver->variables, dvar);
1760         
1761         /* give the variable a 'unique' name */
1762         strcpy(dvar->name, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var"));
1763         BLI_uniquename(&driver->variables, dvar, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var"), '_',
1764                        offsetof(DriverVar, name), sizeof(dvar->name));
1765         
1766         /* set the default type to 'single prop' */
1767         driver_change_variable_type(dvar, DVAR_TYPE_SINGLE_PROP);
1768         
1769 #ifdef WITH_PYTHON
1770         /* since driver variables are cached, the expression needs re-compiling too */
1771         if (driver->type == DRIVER_TYPE_PYTHON)
1772                 driver->flag |= DRIVER_FLAG_RENAMEVAR;
1773 #endif
1774         
1775         /* return the target */
1776         return dvar;
1777 }
1778
1779 /* This frees the driver itself */
1780 void fcurve_free_driver(FCurve *fcu)
1781 {
1782         ChannelDriver *driver;
1783         DriverVar *dvar, *dvarn;
1784         
1785         /* sanity checks */
1786         if (ELEM(NULL, fcu, fcu->driver))
1787                 return;
1788         driver = fcu->driver;
1789         
1790         /* free driver targets */
1791         for (dvar = driver->variables.first; dvar; dvar = dvarn) {
1792                 dvarn = dvar->next;
1793                 driver_free_variable_ex(driver, dvar);
1794         }
1795
1796 #ifdef WITH_PYTHON
1797         /* free compiled driver expression */
1798         if (driver->expr_comp)
1799                 BPY_DECREF(driver->expr_comp);
1800 #endif
1801
1802         /* free driver itself, then set F-Curve's point to this to NULL (as the curve may still be used) */
1803         MEM_freeN(driver);
1804         fcu->driver = NULL;
1805 }
1806
1807 /* This makes a copy of the given driver */
1808 ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver)
1809 {
1810         ChannelDriver *ndriver;
1811         
1812         /* sanity checks */
1813         if (driver == NULL)
1814                 return NULL;
1815                 
1816         /* copy all data */
1817         ndriver = MEM_dupallocN(driver);
1818         ndriver->expr_comp = NULL;
1819         
1820         /* copy variables */
1821         BLI_listbase_clear(&ndriver->variables); /* to get rid of refs to non-copied data (that's still used on original) */ 
1822         driver_variables_copy(&ndriver->variables, &driver->variables);
1823         
1824         /* return the new driver */
1825         return ndriver;
1826 }
1827
1828 /* Driver Evaluation -------------------------- */
1829
1830 /* Evaluate a Driver Variable to get a value that contributes to the final */
1831 float driver_get_variable_value(ChannelDriver *driver, DriverVar *dvar)
1832 {
1833         const DriverVarTypeInfo *dvti;
1834
1835         /* sanity check */
1836         if (ELEM(NULL, driver, dvar))
1837                 return 0.0f;
1838         
1839         /* call the relevant callbacks to get the variable value 
1840          * using the variable type info, storing the obtained value
1841          * in dvar->curval so that drivers can be debugged
1842          */
1843         dvti = get_dvar_typeinfo(dvar->type);
1844         
1845         if (dvti && dvti->get_value)
1846                 dvar->curval = dvti->get_value(driver, dvar);
1847         else
1848                 dvar->curval = 0.0f;
1849         
1850         return dvar->curval;
1851 }
1852
1853 /* Evaluate an Channel-Driver to get a 'time' value to use instead of "evaltime"
1854  *      - "evaltime" is the frame at which F-Curve is being evaluated
1855  *  - has to return a float value
1856  */
1857 float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const float evaltime)
1858 {
1859         DriverVar *dvar;
1860         
1861         /* check if driver can be evaluated */
1862         if (driver->flag & DRIVER_FLAG_INVALID)
1863                 return 0.0f;
1864         
1865         switch (driver->type) {
1866                 case DRIVER_TYPE_AVERAGE: /* average values of driver targets */
1867                 case DRIVER_TYPE_SUM: /* sum values of driver targets */
1868                 {
1869                         /* check how many variables there are first (i.e. just one?) */
1870                         if (BLI_listbase_is_single(&driver->variables)) {
1871                                 /* just one target, so just use that */
1872                                 dvar = driver->variables.first;
1873                                 driver->curval = driver_get_variable_value(driver, dvar);
1874                         }
1875                         else {
1876                                 /* more than one target, so average the values of the targets */
1877                                 float value = 0.0f;
1878                                 int tot = 0;
1879                                 
1880                                 /* loop through targets, adding (hopefully we don't get any overflow!) */
1881                                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1882                                         value += driver_get_variable_value(driver, dvar);
1883                                         tot++;
1884                                 }
1885                                 
1886                                 /* perform operations on the total if appropriate */
1887                                 if (driver->type == DRIVER_TYPE_AVERAGE)
1888                                         driver->curval = tot ? (value / (float)tot) : 0.0f;
1889                                 else
1890                                         driver->curval = value;
1891                         }
1892                         break;
1893                 }
1894                 case DRIVER_TYPE_MIN: /* smallest value */
1895                 case DRIVER_TYPE_MAX: /* largest value */
1896                 {
1897                         float value = 0.0f;
1898                         
1899                         /* loop through the variables, getting the values and comparing them to existing ones */
1900                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1901                                 /* get value */
1902                                 float tmp_val = driver_get_variable_value(driver, dvar);
1903                                 
1904                                 /* store this value if appropriate */
1905                                 if (dvar->prev) {
1906                                         /* check if greater/smaller than the baseline */
1907                                         if (driver->type == DRIVER_TYPE_MAX) {
1908                                                 /* max? */
1909                                                 if (tmp_val > value) 
1910                                                         value = tmp_val;
1911                                         }
1912                                         else {
1913                                                 /* min? */
1914                                                 if (tmp_val < value) 
1915                                                         value = tmp_val;
1916                                         }
1917                                 }
1918                                 else {
1919                                         /* first item - make this the baseline for comparisons */
1920                                         value = tmp_val;
1921                                 }
1922                         }
1923                         
1924                         /* store value in driver */
1925                         driver->curval = value;
1926                         break;
1927                 }
1928                 case DRIVER_TYPE_PYTHON: /* expression */
1929                 {
1930 #ifdef WITH_PYTHON
1931                         /* check for empty or invalid expression */
1932                         if ( (driver->expression[0] == '\0') ||
1933                              (driver->flag & DRIVER_FLAG_INVALID) )
1934                         {
1935                                 driver->curval = 0.0f;
1936                         }
1937                         else {
1938                                 /* this evaluates the expression using Python, and returns its result:
1939                                  *  - on errors it reports, then returns 0.0f
1940                                  */
1941                                 BLI_mutex_lock(&python_driver_lock);
1942
1943                                 driver->curval = BPY_driver_exec(anim_rna, driver, evaltime);
1944
1945                                 BLI_mutex_unlock(&python_driver_lock);
1946                         }
1947 #else /* WITH_PYTHON*/
1948                         UNUSED_VARS(anim_rna, evaltime);
1949 #endif /* WITH_PYTHON*/
1950                         break;
1951                 }
1952                 default:
1953                 {
1954                         /* special 'hack' - just use stored value 
1955                          *      This is currently used as the mechanism which allows animated settings to be able
1956                          *  to be changed via the UI.
1957                          */
1958                         break;
1959                 }
1960         }
1961         
1962         /* return value for driver */
1963         return driver->curval;
1964 }
1965
1966 /* ***************************** Curve Calculations ********************************* */
1967
1968 /* The total length of the handles is not allowed to be more
1969  * than the horizontal distance between (v1-v4).
1970  * This is to prevent curve loops.
1971  */
1972 void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2])
1973 {
1974         float h1[2], h2[2], len1, len2, len, fac;
1975         
1976         /* calculate handle deltas */
1977         h1[0] = v1[0] - v2[0];
1978         h1[1] = v1[1] - v2[1];
1979         
1980         h2[0] = v4[0] - v3[0];
1981         h2[1] = v4[1] - v3[1];
1982         
1983         /* calculate distances: 
1984          *  - len       = span of time between keyframes
1985          *      - len1  = length of handle of start key
1986          *      - len2  = length of handle of end key
1987          */
1988         len = v4[0] - v1[0];
1989         len1 = fabsf(h1[0]);
1990         len2 = fabsf(h2[0]);
1991         
1992         /* if the handles have no length, no need to do any corrections */
1993         if ((len1 + len2) == 0.0f)
1994                 return;
1995                 
1996         /* the two handles cross over each other, so force them
1997          * apart using the proportion they overlap 
1998          */
1999         if ((len1 + len2) > len) {
2000                 fac = len / (len1 + len2);
2001                 
2002                 v2[0] = (v1[0] - fac * h1[0]);
2003                 v2[1] = (v1[1] - fac * h1[1]);
2004                 
2005                 v3[0] = (v4[0] - fac * h2[0]);
2006                 v3[1] = (v4[1] - fac * h2[1]);
2007         }
2008 }
2009
2010 /* find root ('zero') */
2011 static int findzero(float x, float q0, float q1, float q2, float q3, float *o)
2012 {
2013         double c0, c1, c2, c3, a, b, c, p, q, d, t, phi;
2014         int nr = 0;
2015
2016         c0 = q0 - x;
2017         c1 = 3.0f * (q1 - q0);
2018         c2 = 3.0f * (q0 - 2.0f * q1 + q2);
2019         c3 = q3 - q0 + 3.0f * (q1 - q2);
2020         
2021         if (c3 != 0.0) {
2022                 a = c2 / c3;
2023                 b = c1 / c3;
2024                 c = c0 / c3;
2025                 a = a / 3;
2026
2027                 p = b / 3 - a * a;
2028                 q = (2 * a * a * a - a * b + c) / 2;
2029                 d = q * q + p * p * p;
2030                 
2031                 if (d > 0.0) {
2032                         t = sqrt(d);
2033                         o[0] = (float)(sqrt3d(-q + t) + sqrt3d(-q - t) - a);
2034                         
2035                         if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1;
2036                         else return 0;
2037                 }
2038                 else if (d == 0.0) {
2039                         t = sqrt3d(-q);
2040                         o[0] = (float)(2 * t - a);
2041                         
2042                         if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++;
2043                         o[nr] = (float)(-t - a);
2044                         
2045                         if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1;
2046                         else return nr;
2047                 }
2048                 else {
2049                         phi = acos(-q / sqrt(-(p * p * p)));
2050                         t = sqrt(-p);
2051                         p = cos(phi / 3);
2052                         q = sqrt(3 - 3 * p * p);
2053                         o[0] = (float)(2 * t * p - a);
2054                         
2055                         if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++;
2056                         o[nr] = (float)(-t * (p + q) - a);
2057                         
2058                         if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) nr++;
2059                         o[nr] = (float)(-t * (p - q) - a);
2060                         
2061                         if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1;
2062                         else return nr;
2063                 }
2064         }
2065         else {
2066                 a = c2;
2067                 b = c1;
2068                 c = c0;
2069                 
2070                 if (a != 0.0) {
2071                         /* discriminant */
2072                         p = b * b - 4 * a * c;
2073                         
2074                         if (p > 0) {
2075                                 p = sqrt(p);
2076                                 o[0] = (float)((-b - p) / (2 * a));
2077                                 
2078                                 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++;
2079                                 o[nr] = (float)((-b + p) / (2 * a));
2080                                 
2081                                 if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1;
2082                                 else return nr;
2083                         }
2084                         else if (p == 0) {
2085                                 o[0] = (float)(-b / (2 * a));
2086                                 if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1;
2087                                 else return 0;
2088                         }
2089                 }
2090                 else if (b != 0.0) {
2091                         o[0] = (float)(-c / b);
2092                         
2093                         if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1;
2094                         else return 0;
2095                 }
2096                 else if (c == 0.0) {
2097                         o[0] = 0.0;
2098                         return 1;
2099                 }
2100                 
2101                 return 0;
2102         }
2103 }
2104
2105 static void berekeny(float f1, float f2, float f3, float f4, float *o, int b)
2106 {
2107         float t, c0, c1, c2, c3;
2108         int a;
2109
2110         c0 = f1;
2111         c1 = 3.0f * (f2 - f1);
2112         c2 = 3.0f * (f1 - 2.0f * f2 + f3);
2113         c3 = f4 - f1 + 3.0f * (f2 - f3);
2114
2115         for (a = 0; a < b; a++) {
2116                 t = o[a];
2117                 o[a] = c0 + t * c1 + t * t * c2 + t * t * t * c3;
2118         }
2119 }
2120
2121 #if 0
2122 static void berekenx(float *f, float *o, int b)
2123 {
2124         float t, c0, c1, c2, c3;
2125         int a;
2126
2127         c0 = f[0];
2128         c1 = 3.0f * (f[3] - f[0]);
2129         c2 = 3.0f * (f[0] - 2.0f * f[3] + f[6]);
2130         c3 = f[9] - f[0] + 3.0f * (f[3] - f[6]);
2131
2132         for (a = 0; a < b; a++) {
2133                 t = o[a];
2134                 o[a] = c0 + t * c1 + t * t * c2 + t * t * t * c3;
2135         }
2136 }
2137 #endif
2138
2139
2140 /* -------------------------- */
2141
2142 /* Calculate F-Curve value for 'evaltime' using BezTriple keyframes */
2143 static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime)
2144 {
2145         const float eps = 1.e-8f;
2146         BezTriple *bezt, *prevbezt, *lastbezt;
2147         float v1[2], v2[2], v3[2], v4[2], opl[32], dx, fac;
2148         unsigned int a;
2149         int b;
2150         float cvalue = 0.0f;
2151         
2152         /* get pointers */
2153         a = fcu->totvert - 1;
2154         prevbezt = bezts;
2155         bezt = prevbezt + 1;
2156         lastbezt = prevbezt + a;
2157         
2158         /* evaluation time at or past endpoints? */
2159         if (prevbezt->vec[1][0] >= evaltime) {
2160                 /* before or on first keyframe */
2161                 if ( (fcu->extend == FCURVE_EXTRAPOLATE_LINEAR) && (prevbezt->ipo != BEZT_IPO_CONST) &&
2162                      !(fcu->flag & FCURVE_DISCRETE_VALUES) )
2163                 {
2164                         /* linear or bezier interpolation */
2165                         if (prevbezt->ipo == BEZT_IPO_LIN) {
2166                                 /* Use the next center point instead of our own handle for
2167                                  * linear interpolated extrapolate 
2168                                  */
2169                                 if (fcu->totvert == 1) {
2170                                         cvalue = prevbezt->vec[1][1];
2171                                 }
2172                                 else {
2173                                         bezt = prevbezt + 1;
2174                                         dx = prevbezt->vec[1][0] - evaltime;
2175                                         fac = bezt->vec[1][0] - prevbezt->vec[1][0];
2176                                         
2177                                         /* prevent division by zero */
2178                                         if (fac) {
2179                                                 fac = (bezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
2180                                                 cvalue = prevbezt->vec[1][1] - (fac * dx);
2181                                         }
2182                                         else {
2183                                                 cvalue = prevbezt->vec[1][1];
2184                                         }
2185                                 }
2186                         }
2187                         else {
2188                                 /* Use the first handle (earlier) of first BezTriple to calculate the
2189                                  * gradient and thus the value of the curve at evaltime
2190                                  */
2191                                 dx = prevbezt->vec[1][0] - evaltime;
2192                                 fac = prevbezt->vec[1][0] - prevbezt->vec[0][0];
2193                                 
2194                                 /* prevent division by zero */
2195                                 if (fac) {
2196                                         fac = (prevbezt->vec[1][1] - prevbezt->vec[0][1]) / fac;
2197                                         cvalue = prevbezt->vec[1][1] - (fac * dx);
2198                                 }
2199                                 else {
2200                                         cvalue = prevbezt->vec[1][1];
2201                                 }
2202                         }
2203                 }
2204                 else {
2205                         /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, 
2206                          * so just extend first keyframe's value 
2207                          */
2208                         cvalue = prevbezt->vec[1][1];
2209                 }
2210         }
2211         else if (lastbezt->vec[1][0] <= evaltime) {
2212                 /* after or on last keyframe */
2213                 if ( (fcu->extend == FCURVE_EXTRAPOLATE_LINEAR) && (lastbezt->ipo != BEZT_IPO_CONST) &&
2214                      !(fcu->flag & FCURVE_DISCRETE_VALUES) )
2215                 {
2216                         /* linear or bezier interpolation */
2217                         if (lastbezt->ipo == BEZT_IPO_LIN) {
2218                                 /* Use the next center point instead of our own handle for
2219                                  * linear interpolated extrapolate 
2220                                  */
2221                                 if (fcu->totvert == 1) {
2222                                         cvalue = lastbezt->vec[1][1];
2223                                 }
2224                                 else {
2225                                         prevbezt = lastbezt - 1;
2226                                         dx = evaltime - lastbezt->vec[1][0];
2227                                         fac = lastbezt->vec[1][0] - prevbezt->vec[1][0];
2228                                         
2229                                         /* prevent division by zero */
2230                                         if (fac) {
2231                                                 fac = (lastbezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
2232                                                 cvalue = lastbezt->vec[1][1] + (fac * dx);
2233                                         }
2234                                         else {
2235                                                 cvalue = lastbezt->vec[1][1];
2236                                         }
2237                                 }
2238                         }
2239                         else {
2240                                 /* Use the gradient of the second handle (later) of last BezTriple to calculate the
2241                                  * gradient and thus the value of the curve at evaltime
2242                                  */
2243                                 dx = evaltime - lastbezt->vec[1][0];
2244                                 fac = lastbezt->vec[2][0] - lastbezt->vec[1][0];
2245                                 
2246                                 /* prevent division by zero */
2247                                 if (fac) {
2248                                         fac = (lastbezt->vec[2][1] - lastbezt->vec[1][1]) / fac;
2249                                         cvalue = lastbezt->vec[1][1] + (fac * dx);
2250                                 }
2251                                 else {
2252                                         cvalue = lastbezt->vec[1][1];
2253                                 }
2254                         }
2255                 }
2256                 else {
2257                         /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, 
2258                          * so just extend last keyframe's value 
2259                          */
2260                         cvalue = lastbezt->vec[1][1];
2261                 }
2262         }
2263         else {
2264                 /* evaltime occurs somewhere in the middle of the curve */
2265                 bool exact = false;
2266                 
2267                 /* Use binary search to find appropriate keyframes...
2268                  * 
2269                  * The threshold here has the following constraints:
2270                  *    - 0.001   is too coarse   -> We get artifacts with 2cm driver movements at 1BU = 1m (see T40332)
2271                  *    - 0.00001 is too fine     -> Weird errors, like selecting the wrong keyframe range (see T39207), occur.
2272                  *                                 This lower bound was established in b888a32eee8147b028464336ad2404d8155c64dd
2273                  */
2274                 a = binarysearch_bezt_index_ex(bezts, evaltime, fcu->totvert, 0.0001, &exact);
2275                 if (G.debug & G_DEBUG) printf("eval fcurve '%s' - %f => %u/%u, %d\n", fcu->rna_path, evaltime, a, fcu->totvert, exact);
2276                 
2277                 if (exact) {
2278                         /* index returned must be interpreted differently when it sits on top of an existing keyframe 
2279                          * - that keyframe is the start of the segment we need (see action_bug_2.blend in T39207)
2280                          */
2281                         prevbezt = bezts + a;
2282                         bezt = (a < fcu->totvert - 1) ? (prevbezt + 1) : prevbezt;
2283                 }
2284                 else {
2285                         /* index returned refers to the keyframe that the eval-time occurs *before*
2286                          * - hence, that keyframe marks the start of the segment we're dealing with
2287                          */
2288                         bezt = bezts + a;
2289                         prevbezt = (a > 0) ? (bezt - 1) : bezt;
2290                 }
2291                 
2292                 /* use if the key is directly on the frame, rare cases this is needed else we get 0.0 instead. */
2293                 /* XXX: consult T39207 for examples of files where failure of these checks can cause issues */
2294                 if (exact) {
2295                         cvalue = prevbezt->vec[1][1];
2296                 }
2297                 else if (fabsf(bezt->vec[1][0] - evaltime) < eps) {
2298                         cvalue = bezt->vec[1][1];
2299                 }
2300                 /* evaltime occurs within the interval defined by these two keyframes */
2301                 else if ((prevbezt->vec[1][0] <= evaltime) && (bezt->vec[1][0] >= evaltime)) {
2302                         const float begin = prevbezt->vec[1][1];
2303                         const float change = bezt->vec[1][1] - prevbezt->vec[1][1];
2304                         const float duration = bezt->vec[1][0] - prevbezt->vec[1][0];
2305                         const float time = evaltime - prevbezt->vec[1][0];
2306                         const float amplitude = prevbezt->amplitude;
2307                         const float period = prevbezt->period;
2308                         
2309                         /* value depends on interpolation mode */
2310                         if ((prevbezt->ipo == BEZT_IPO_CONST) || (fcu->flag & FCURVE_DISCRETE_VALUES) || (duration == 0)) {
2311                                 /* constant (evaltime not relevant, so no interpolation needed) */
2312                                 cvalue = prevbezt->vec[1][1];
2313                         }
2314                         else {
2315                                 switch (prevbezt->ipo) {
2316                                         /* interpolation ...................................... */
2317                                         case BEZT_IPO_BEZ:
2318                                                 /* bezier interpolation */
2319                                                 /* (v1, v2) are the first keyframe and its 2nd handle */
2320                                                 v1[0] = prevbezt->vec[1][0];
2321                                                 v1[1] = prevbezt->vec[1][1];
2322                                                 v2[0] = prevbezt->vec[2][0];
2323                                                 v2[1] = prevbezt->vec[2][1];
2324                                                 /* (v3, v4) are the last keyframe's 1st handle + the last keyframe */
2325                                                 v3[0] = bezt->vec[0][0];
2326                                                 v3[1] = bezt->vec[0][1];
2327                                                 v4[0] = bezt->vec[1][0];
2328                                                 v4[1] = bezt->vec[1][1];
2329                                                 
2330                                                 if (fabsf(v1[1] - v4[1]) < FLT_EPSILON &&
2331                                                     fabsf(v2[1] - v3[1]) < FLT_EPSILON &&
2332                                                     fabsf(v3[1] - v4[1]) < FLT_EPSILON)
2333                                                 {
2334                                                         /* Optimisation: If all the handles are flat/at the same values,
2335                                                          * the value is simply the shared value (see T40372 -> F91346)
2336                                                          */
2337                                                         cvalue = v1[1];
2338                                                 }
2339                                                 else {
2340                                                         /* adjust handles so that they don't overlap (forming a loop) */
2341                                                         correct_bezpart(v1, v2, v3, v4);
2342                                                         
2343                                                         /* try to get a value for this position - if failure, try another set of points */
2344                                                         b = findzero(evaltime, v1[0], v2[0], v3[0], v4[0], opl);
2345                                                         if (b) {
2346                                                                 berekeny(v1[1], v2[1], v3[1], v4[1], opl, 1);
2347                                                                 cvalue = opl[0];
2348                                                                 /* break; */
2349                                                         }
2350                                                         else {
2351                                                                 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]);
2352                                                         }
2353                                                 }
2354                                                 break;
2355                                                 
2356                                         case BEZT_IPO_LIN:
2357                                                 /* linear - simply linearly interpolate between values of the two keyframes */
2358                                                 cvalue = BLI_easing_linear_ease(time, begin, change, duration);
2359                                                 break;
2360                                                 
2361                                         /* easing ............................................ */
2362                                         case BEZT_IPO_BACK:
2363                                                 switch (prevbezt->easing) {
2364                                                         case BEZT_IPO_EASE_IN:
2365                                                                 cvalue = BLI_easing_back_ease_in(time, begin, change, duration, prevbezt->back);
2366                                                                 break;
2367                                                         case BEZT_IPO_EASE_OUT:
2368                                                                 cvalue = BLI_easing_back_ease_out(time, begin, change, duration, prevbezt->back);
2369                                                                 break;
2370                                                         case BEZT_IPO_EASE_IN_OUT:
2371                                                                 cvalue = BLI_easing_back_ease_in_out(time, begin, change, duration, prevbezt->back);
2372                                                                 break;
2373                                                                 
2374                                                         default: /* default/auto: same as ease out */
2375                                                                 cvalue = BLI_easing_back_ease_out(time, begin, change, duration, prevbezt->back);
2376                                                                 break;
2377                                                 }
2378                                                 break;
2379                                         
2380                                         case BEZT_IPO_BOUNCE:
2381                                                 switch (prevbezt->easing) {
2382                                                         case BEZT_IPO_EASE_IN:
2383                                                                 cvalue = BLI_easing_bounce_ease_in(time, begin, change, duration);
2384                                                                 break;
2385                                                         case BEZT_IPO_EASE_OUT:
2386                                                                 cvalue = BLI_easing_bounce_ease_out(time, begin, change, duration);
2387                                                                 break;
2388                                                         case BEZT_IPO_EASE_IN_OUT:
2389                                                                 cvalue = BLI_easing_bounce_ease_in_out(time, begin, change, duration);
2390                                                                 break;
2391                                                                 
2392                                                         default: /* default/auto: same as ease out */
2393                                                                 cvalue = BLI_easing_bounce_ease_out(time, begin, change, duration);
2394                                                                 break;
2395                                                 }
2396                                                 break;
2397                                         
2398                                         case BEZT_IPO_CIRC:
2399                                                 switch (prevbezt->easing) {
2400                                                         case BEZT_IPO_EASE_IN:
2401                                                                 cvalue = BLI_easing_circ_ease_in(time, begin, change, duration);
2402                                                                 break;
2403                                                         case BEZT_IPO_EASE_OUT:
2404                                                                 cvalue = BLI_easing_circ_ease_out(time, begin, change, duration);
2405                                                                 break;
2406                                                         case BEZT_IPO_EASE_IN_OUT:
2407                                                                 cvalue = BLI_easing_circ_ease_in_out(time, begin, change, duration);
2408                                                                 break;
2409                                                                 
2410                                                         default: /* default/auto: same as ease in */
2411                                                                 cvalue = BLI_easing_circ_ease_in(time, begin, change, duration);
2412                                                                 break;
2413                                                 }
2414                                                 break;
2415
2416                                         case BEZT_IPO_CUBIC:
2417                                                 switch (prevbezt->easing) {
2418                                                         case BEZT_IPO_EASE_IN:
2419                                                                 cvalue = BLI_easing_cubic_ease_in(time, begin, change, duration);
2420                                                                 break;
2421                                                         case BEZT_IPO_EASE_OUT:
2422                                                                 cvalue = BLI_easing_cubic_ease_out(time, begin, change, duration);
2423                                                                 break;
2424                                                         case BEZT_IPO_EASE_IN_OUT:
2425                                                                 cvalue = BLI_easing_cubic_ease_in_out(time, begin, change, duration);
2426                                                                 break;
2427                                                                 
2428                                                         default: /* default/auto: same as ease in */
2429                                                                 cvalue = BLI_easing_cubic_ease_in(time, begin, change, duration);
2430                                                                 break;
2431                                                 }
2432                                                 break;
2433                                         
2434                                         case BEZT_IPO_ELASTIC:
2435                                                 switch (prevbezt->easing) {
2436                                                         case BEZT_IPO_EASE_IN:
2437                                                                 cvalue = BLI_easing_elastic_ease_in(time, begin, change, duration, amplitude, period);
2438                                                                 break;
2439                                                         case BEZT_IPO_EASE_OUT:
2440                                                                 cvalue = BLI_easing_elastic_ease_out(time, begin, change, duration, amplitude, period);
2441                                                                 break;
2442                                                         case BEZT_IPO_EASE_IN_OUT:
2443                                                                 cvalue = BLI_easing_elastic_ease_in_out(time, begin, change, duration, amplitude, period);
2444                                                                 break;
2445                                                                 
2446                                                         default: /* default/auto: same as ease out */
2447                                                                 cvalue = BLI_easing_elastic_ease_out(time, begin, change, duration, amplitude, period);
2448                                                                 break;
2449                                                 }
2450                                                 break;
2451                                         
2452                                         case BEZT_IPO_EXPO:
2453                                                 switch (prevbezt->easing) {
2454                                                         case BEZT_IPO_EASE_IN:
2455                                                                 cvalue = BLI_easing_expo_ease_in(time, begin, change, duration);
2456                                                                 break;
2457                                                         case BEZT_IPO_EASE_OUT:
2458                                                                 cvalue = BLI_easing_expo_ease_out(time, begin, change, duration);
2459                                                                 break;
2460                                                         case BEZT_IPO_EASE_IN_OUT:
2461                                                                 cvalue = BLI_easing_expo_ease_in_out(time, begin, change, duration);
2462                                                                 break;
2463                                                                 
2464                                                         default: /* default/auto: same as ease in */
2465                                                                 cvalue = BLI_easing_expo_ease_in(time, begin, change, duration);
2466                                                                 break;
2467                                                 }
2468                                                 break;
2469                                         
2470                                         case BEZT_IPO_QUAD:
2471                                                 switch (prevbezt->easing) {
2472                                                         case BEZT_IPO_EASE_IN:
2473                                                                 cvalue = BLI_easing_quad_ease_in(time, begin, change, duration);
2474                                                                 break;
2475                                                         case BEZT_IPO_EASE_OUT:
2476                                                                 cvalue = BLI_easing_quad_ease_out(time, begin, change, duration);
2477                                                                 break;
2478                                                         case BEZT_IPO_EASE_IN_OUT:
2479                                                                 cvalue = BLI_easing_quad_ease_in_out(time, begin, change, duration);
2480                                                                 break;
2481                                                         
2482                                                         default: /* default/auto: same as ease in */
2483                                                                 cvalue = BLI_easing_quad_ease_in(time, begin, change, duration);
2484                                                                 break;
2485                                                 }
2486                                                 break;
2487                                         
2488                                         case BEZT_IPO_QUART:
2489                                                 switch (prevbezt->easing) {
2490                                                         case BEZT_IPO_EASE_IN:
2491                                                                 cvalue = BLI_easing_quart_ease_in(time, begin, change, duration);
2492                                                                 break;
2493                                                         case BEZT_IPO_EASE_OUT:
2494                                                                 cvalue = BLI_easing_quart_ease_out(time, begin, change, duration);
2495                                                                 break;
2496                                                         case BEZT_IPO_EASE_IN_OUT:
2497                                                                 cvalue = BLI_easing_quart_ease_in_out(time, begin, change, duration);
2498                                                                 break;
2499                                                                 
2500                                                         default: /* default/auto: same as ease in */
2501                                                                 cvalue = BLI_easing_quart_ease_in(time, begin, change, duration);
2502                                                                 break;
2503                                                 }
2504                                                 break;
2505                                         
2506                                         case BEZT_IPO_QUINT:
2507                                                 switch (prevbezt->easing) {
2508                                                         case BEZT_IPO_EASE_IN:
2509                                                                 cvalue = BLI_easing_quint_ease_in(time, begin, change, duration);
2510                                                                 break;
2511                                                         case BEZT_IPO_EASE_OUT:
2512                                                                 cvalue = BLI_easing_quint_ease_out(time, begin, change, duration);
2513                                                                 break;
2514                                                         case BEZT_IPO_EASE_IN_OUT:
2515                                                                 cvalue = BLI_easing_quint_ease_in_out(time, begin, change, duration);
2516                                                                 break;
2517                                                                 
2518                                                         default: /* default/auto: same as ease in */
2519                                                                 cvalue = BLI_easing_quint_ease_in(time, begin, change, duration);
2520                                                                 break;
2521                                                 }
2522                                                 break;
2523                                         
2524                                         case BEZT_IPO_SINE:
2525                                                 switch (prevbezt->easing) {
2526                                                         case BEZT_IPO_EASE_IN:
2527                                                                 cvalue = BLI_easing_sine_ease_in(time, begin, change, duration);
2528                                                                 break;
2529                                                         case BEZT_IPO_EASE_OUT:
2530                                                                 cvalue = BLI_easing_sine_ease_out(time, begin, change, duration);
2531                                                                 break;
2532                                                         case BEZT_IPO_EASE_IN_OUT:
2533                                                                 cvalue = BLI_easing_sine_ease_in_out(time, begin, change, duration);
2534                                                                 break;
2535                                                                 
2536                                                         default: /* default/auto: same as ease in */
2537                                                                 cvalue = BLI_easing_sine_ease_in(time, begin, change, duration);
2538                                                                 break;
2539                                                 }
2540                                                 break;
2541                                         
2542                                         
2543                                         default:
2544                                                 cvalue = prevbezt->vec[1][1];
2545                                                 break;
2546                                 }
2547                         }
2548                 }
2549                 else {
2550                         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));
2551                 }
2552         }
2553         
2554         /* return value */
2555         return cvalue;
2556 }
2557
2558 /* Calculate F-Curve value for 'evaltime' using FPoint samples */
2559 static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime)
2560 {
2561         FPoint *prevfpt, *lastfpt, *fpt;
2562         float cvalue = 0.0f;
2563         
2564         /* get pointers */
2565         prevfpt = fpts;
2566         lastfpt = prevfpt + fcu->totvert - 1;
2567         
2568         /* evaluation time at or past endpoints? */
2569         if (prevfpt->vec[0] >= evaltime) {
2570                 /* before or on first sample, so just extend value */
2571                 cvalue = prevfpt->vec[1];
2572         }
2573         else if (lastfpt->vec[0] <= evaltime) {
2574                 /* after or on last sample, so just extend value */
2575                 cvalue = lastfpt->vec[1];
2576         }
2577         else {
2578                 float t = fabsf(evaltime - floorf(evaltime));
2579                 
2580                 /* find the one on the right frame (assume that these are spaced on 1-frame intervals) */
2581                 fpt = prevfpt + ((int)evaltime - (int)prevfpt->vec[0]);
2582                 
2583                 /* if not exactly on the frame, perform linear interpolation with the next one */
2584                 if ((t != 0.0f) && (t < 1.0f))
2585                         cvalue = interpf(fpt->vec[1], (fpt + 1)->vec[1], 1.0f - t);
2586                 else
2587                         cvalue = fpt->vec[1];
2588         }
2589         
2590         /* return value */
2591         return cvalue;
2592 }
2593
2594 /* ***************************** F-Curve - Evaluation ********************************* */
2595
2596 /* Evaluate and return the value of the given F-Curve at the specified frame ("evaltime") 
2597  * Note: this is also used for drivers
2598  */
2599 static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue)
2600 {
2601         FModifierStackStorage *storage;
2602         float devaltime;
2603
2604         /* evaluate modifiers which modify time to evaluate the base curve at */
2605         storage = evaluate_fmodifiers_storage_new(&fcu->modifiers);
2606         devaltime = evaluate_time_fmodifiers(storage, &fcu->modifiers, fcu, cvalue, evaltime);
2607         
2608         /* evaluate curve-data 
2609          *      - 'devaltime' instead of 'evaltime', as this is the time that the last time-modifying 
2610          *        F-Curve modifier on the stack requested the curve to be evaluated at
2611          */
2612         if (fcu->bezt)
2613                 cvalue = fcurve_eval_keyframes(fcu, fcu->bezt, devaltime);
2614         else if (fcu->fpt)
2615                 cvalue = fcurve_eval_samples(fcu, fcu->fpt, devaltime);
2616         
2617         /* evaluate modifiers */
2618         evaluate_value_fmodifiers(storage, &fcu->modifiers, fcu, &cvalue, devaltime);
2619
2620         evaluate_fmodifiers_storage_free(storage);
2621
2622         /* if curve can only have integral values, perform truncation (i.e. drop the decimal part)
2623          * here so that the curve can be sampled correctly
2624          */
2625         if (fcu->flag & FCURVE_INT_VALUES)
2626                 cvalue = floorf(cvalue + 0.5f);
2627         
2628         /* return evaluated value */
2629         return cvalue;
2630 }
2631
2632 float evaluate_fcurve(FCurve *fcu, float evaltime)
2633 {
2634         BLI_assert(fcu->driver == NULL);
2635
2636         return evaluate_fcurve_ex(fcu, evaltime, 0.0);
2637 }
2638
2639 float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime)
2640 {
2641         BLI_assert(fcu->driver != NULL);
2642         float cvalue = 0.0f;
2643
2644         /* if there is a driver (only if this F-Curve is acting as 'driver'), evaluate it to find value to use as "evaltime"
2645          * since drivers essentially act as alternative input (i.e. in place of 'time') for F-Curves
2646          */
2647         if (fcu->driver) {
2648                 /* evaltime now serves as input for the curve */
2649                 evaltime = evaluate_driver(anim_rna, fcu->driver, evaltime);
2650
2651                 /* only do a default 1-1 mapping if it's unlikely that anything else will set a value... */
2652                 if (fcu->totvert == 0) {
2653                         FModifier *fcm;
2654                         bool do_linear = true;
2655
2656                         /* out-of-range F-Modifiers will block, as will those which just plain overwrite the values
2657                          * XXX: additive is a bit more dicey; it really depends then if things are in range or not...
2658                          */
2659                         for (fcm = fcu->modifiers.first; fcm; fcm = fcm->next) {
2660                                 /* if there are range-restrictions, we must definitely block [#36950] */
2661                                 if ((fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) == 0 ||
2662                                     ((fcm->sfra <= evaltime) && (fcm->efra >= evaltime)) )
2663                                 {
2664                                         /* within range: here it probably doesn't matter, though we'd want to check on additive... */
2665                                 }
2666                                 else {
2667                                         /* outside range: modifier shouldn't contribute to the curve here, though it does in other areas,
2668                                          * so neither should the driver!
2669                                          */
2670                                         do_linear = false;
2671                                 }
2672                         }
2673
2674                         /* only copy over results if none of the modifiers disagreed with this */
2675                         if (do_linear) {
2676                                 cvalue = evaltime;
2677                         }
2678                 }
2679         }
2680
2681         return evaluate_fcurve_ex(fcu, evaltime, cvalue);
2682 }
2683
2684 /* Calculate the value of the given F-Curve at the given frame, and set its curval */
2685 float calculate_fcurve(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime)
2686 {
2687         /* only calculate + set curval (overriding the existing value) if curve has 
2688          * any data which warrants this...
2689          */
2690         if ((fcu->totvert) || (fcu->driver && !(fcu->driver->flag & DRIVER_FLAG_INVALID)) ||
2691             list_has_suitable_fmodifier(&fcu->modifiers, 0, FMI_TYPE_GENERATE_CURVE))
2692         {
2693                 /* calculate and set curval (evaluates driver too if necessary) */
2694                 float curval;
2695                 if (fcu->driver) {
2696                         curval = evaluate_fcurve_driver(anim_rna, fcu, evaltime);
2697                 }
2698                 else {
2699                         curval = evaluate_fcurve(fcu, evaltime);
2700                 }
2701                 fcu->curval = curval;  /* debug display only, not thread safe! */
2702                 return curval;
2703         }
2704         else {
2705                 return 0.0f;
2706         }
2707 }
2708