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