added path traversal flag - BPATH_TRAVERSE_SKIP_MULTIFILE,
[blender.git] / source / blender / blenkernel / intern / action.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
22  *                               Full recode, Joshua Leung, 2009
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenkernel/intern/action.c
28  *  \ingroup bke
29  */
30
31
32 #include <string.h>
33 #include <math.h>
34 #include <stdlib.h>
35 #include <stddef.h>     
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_constraint_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_object_types.h"
44
45 #include "BLI_blenlib.h"
46 #include "BLI_bpath.h"
47 #include "BLI_math.h"
48 #include "BLI_utildefines.h"
49 #include "BLI_ghash.h"
50
51 #include "BKE_animsys.h"
52 #include "BKE_action.h"
53 #include "BKE_anim.h"
54 #include "BKE_constraint.h"
55 #include "BKE_global.h"
56 #include "BKE_fcurve.h"
57 #include "BKE_library.h"
58 #include "BKE_main.h"
59 #include "BKE_object.h"
60
61 #include "BKE_idprop.h"
62
63 #include "BIK_api.h"
64
65 #include "RNA_access.h"
66
67 /* *********************** NOTE ON POSE AND ACTION **********************
68
69   - Pose is the local (object level) component of armature. The current
70         object pose is saved in files, and (will be) is presorted for dependency
71   - Actions have fewer (or other) channels, and write data to a Pose
72   - Currently ob->pose data is controlled in where_is_pose only. The (recalc)
73         event system takes care of calling that
74   - The NLA system (here too) uses Poses as interpolation format for Actions
75   - Therefore we assume poses to be static, and duplicates of poses have channels in
76         same order, for quick interpolation reasons
77
78   ****************************** (ton) ************************************ */
79
80 /* ***************** Library data level operations on action ************** */
81
82 bAction *add_empty_action(const char name[])
83 {
84         bAction *act;
85         
86         act= alloc_libblock(&G.main->action, ID_AC, name);
87         
88         return act;
89 }       
90
91 /* .................................. */
92
93 /* temp data for make_local_action */
94 typedef struct tMakeLocalActionContext {
95         bAction *act;    /* original action */
96         bAction *actn;   /* new action */
97         
98         int is_lib;         /* some action users were libraries */
99         int is_local;       /* some action users were not libraries */
100 } tMakeLocalActionContext;
101
102 /* helper function for make_local_action() - local/lib init step */
103 static void make_localact_init_cb(ID *id, AnimData *adt, void *mlac_ptr)
104 {
105         tMakeLocalActionContext *mlac = (tMakeLocalActionContext *)mlac_ptr;
106         
107         if (adt->action == mlac->act) {
108                 if (id->lib) mlac->is_lib= TRUE;
109                 else mlac->is_local= TRUE;
110         }
111 }
112
113 /* helper function for make_local_action() - change references */
114 static void make_localact_apply_cb(ID *id, AnimData *adt, void *mlac_ptr)
115 {
116         tMakeLocalActionContext *mlac = (tMakeLocalActionContext *)mlac_ptr;
117         
118         if (adt->action == mlac->act) {
119                 if (id->lib == NULL) {
120                         adt->action = mlac->actn;
121                         
122                         id_us_plus(&mlac->actn->id);
123                         id_us_min(&mlac->act->id);
124                 }
125         }
126 }
127
128 // does copy_fcurve...
129 void make_local_action(bAction *act)
130 {
131         tMakeLocalActionContext mlac = {act, NULL, FALSE, FALSE};
132         Main *bmain= G.main;
133         
134         if (act->id.lib==NULL) 
135                 return;
136         
137         // XXX: double-check this; it used to be just single-user check, but that was when fake-users were still default
138         if ((act->id.flag & LIB_FAKEUSER) && (act->id.us<=1)) {
139                 id_clear_lib_data(bmain, &act->id);
140                 return;
141         }
142         
143         BKE_animdata_main_cb(bmain, make_localact_init_cb, &mlac);
144         
145         if (mlac.is_local && mlac.is_lib==FALSE) {
146                 id_clear_lib_data(bmain, &act->id);
147         }
148         else if (mlac.is_local && mlac.is_lib) {
149                 mlac.actn= copy_action(act);
150                 mlac.actn->id.us= 0;
151
152                 BKE_id_lib_local_paths(bmain, &mlac.actn->id);
153
154                 BKE_animdata_main_cb(bmain, make_localact_apply_cb, &mlac);
155         }
156 }
157
158 /* .................................. */
159
160 void free_action (bAction *act)
161 {
162         /* sanity check */
163         if (act == NULL)
164                 return;
165         
166         /* Free F-Curves */
167         free_fcurves(&act->curves);
168         
169         /* Free groups */
170         if (act->groups.first)
171                 BLI_freelistN(&act->groups);
172                 
173         /* Free pose-references (aka local markers) */
174         if (act->markers.first)
175                 BLI_freelistN(&act->markers);
176 }
177
178 /* .................................. */
179
180 bAction *copy_action (bAction *src)
181 {
182         bAction *dst = NULL;
183         bActionGroup *dgrp, *sgrp;
184         FCurve *dfcu, *sfcu;
185         
186         if (src == NULL) 
187                 return NULL;
188         dst= copy_libblock(src);
189         
190         /* duplicate the lists of groups and markers */
191         BLI_duplicatelist(&dst->groups, &src->groups);
192         BLI_duplicatelist(&dst->markers, &src->markers);
193         
194         /* copy F-Curves, fixing up the links as we go */
195         dst->curves.first= dst->curves.last= NULL;
196         
197         for (sfcu= src->curves.first; sfcu; sfcu= sfcu->next) {
198                 /* duplicate F-Curve */
199                 dfcu= copy_fcurve(sfcu);
200                 BLI_addtail(&dst->curves, dfcu);
201                 
202                 /* fix group links (kindof bad list-in-list search, but this is the most reliable way) */
203                 for (dgrp=dst->groups.first, sgrp=src->groups.first; dgrp && sgrp; dgrp=dgrp->next, sgrp=sgrp->next) {
204                         if (sfcu->grp == sgrp) {
205                                 dfcu->grp= dgrp;
206                                 
207                                 if (dgrp->channels.first == sfcu)
208                                         dgrp->channels.first= dfcu;
209                                 if (dgrp->channels.last == sfcu)
210                                         dgrp->channels.last= dfcu;
211                                         
212                                 break;
213                         }
214                 }
215         }
216         
217         return dst;
218 }
219
220 /* *************** Action Groups *************** */
221
222 /* Get the active action-group for an Action */
223 bActionGroup *get_active_actiongroup (bAction *act)
224 {
225         bActionGroup *agrp= NULL;
226         
227         if (act && act->groups.first) { 
228                 for (agrp= act->groups.first; agrp; agrp= agrp->next) {
229                         if (agrp->flag & AGRP_ACTIVE)
230                                 break;
231                 }
232         }
233         
234         return agrp;
235 }
236
237 /* Make the given Action-Group the active one */
238 void set_active_action_group (bAction *act, bActionGroup *agrp, short select)
239 {
240         bActionGroup *grp;
241         
242         /* sanity checks */
243         if (act == NULL)
244                 return;
245         
246         /* Deactive all others */
247         for (grp= act->groups.first; grp; grp= grp->next) {
248                 if ((grp==agrp) && (select))
249                         grp->flag |= AGRP_ACTIVE;
250                 else    
251                         grp->flag &= ~AGRP_ACTIVE;
252         }
253 }
254
255 /* Add a new action group with the given name to the action */
256 bActionGroup *action_groups_add_new (bAction *act, const char name[])
257 {
258         bActionGroup *agrp;
259         
260         /* sanity check: must have action and name */
261         if (ELEM(NULL, act, name))
262                 return NULL;
263         
264         /* allocate a new one */
265         agrp = MEM_callocN(sizeof(bActionGroup), "bActionGroup");
266         
267         /* make it selected, with default name */
268         agrp->flag = AGRP_SELECTED;
269         BLI_strncpy(agrp->name, name[0] ? name : "Group", sizeof(agrp->name));
270         
271         /* add to action, and validate */
272         BLI_addtail(&act->groups, agrp);
273         BLI_uniquename(&act->groups, agrp, "Group", '.', offsetof(bActionGroup, name), sizeof(agrp->name));     
274         
275         /* return the new group */
276         return agrp;
277 }
278
279 /* Add given channel into (active) group 
280  *      - assumes that channel is not linked to anything anymore
281  *      - always adds at the end of the group 
282  */
283 void action_groups_add_channel (bAction *act, bActionGroup *agrp, FCurve *fcurve)
284 {       
285         /* sanity checks */
286         if (ELEM3(NULL, act, agrp, fcurve))
287                 return;
288         
289         /* if no channels anywhere, just add to two lists at the same time */
290         if (act->curves.first == NULL) {
291                 fcurve->next = fcurve->prev = NULL;
292                 
293                 agrp->channels.first = agrp->channels.last = fcurve;
294                 act->curves.first = act->curves.last = fcurve;
295         }
296         
297         /* if the group already has channels, the F-Curve can simply be added to the list 
298          * (i.e. as the last channel in the group)
299          */
300         else if (agrp->channels.first) {
301                 /* if the group's last F-Curve is the action's last F-Curve too, 
302                  * then set the F-Curve as the last for the action first so that
303                  * the lists will be in sync after linking
304                  */
305                 if (agrp->channels.last == act->curves.last)
306                         act->curves.last= fcurve;
307                         
308                 /* link in the given F-Curve after the last F-Curve in the group,
309                  * which means that it should be able to fit in with the rest of the
310                  * list seamlessly
311                  */
312                 BLI_insertlinkafter(&agrp->channels, agrp->channels.last, fcurve);
313         }
314         
315         /* otherwise, need to find the nearest F-Curve in group before/after current to link with */
316         else {
317                 bActionGroup *grp;
318                 
319                 /* firstly, link this F-Curve to the group */
320                 agrp->channels.first = agrp->channels.last = fcurve;
321                 
322                 /* step through the groups preceding this one, finding the F-Curve there to attach this one after */
323                 for (grp= agrp->prev; grp; grp= grp->prev) {
324                         /* if this group has F-Curves, we want weave the given one in right after the last channel there,
325                          * but via the Action's list not this group's list
326                          *      - this is so that the F-Curve is in the right place in the Action,
327                          *        but won't be included in the previous group
328                          */
329                         if (grp->channels.last) {
330                                 /* once we've added, break here since we don't need to search any further... */
331                                 BLI_insertlinkafter(&act->curves, grp->channels.last, fcurve);
332                                 break;
333                         }
334                 }
335                 
336                 /* if grp is NULL, that means we fell through, and this F-Curve should be added as the new first
337                  * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the 
338                  * second in the chain, etc. etc.
339                  */
340                 if (grp == NULL)
341                         BLI_insertlinkbefore(&act->curves, act->curves.first, fcurve);
342         }
343         
344         /* set the F-Curve's new group */
345         fcurve->grp= agrp;
346 }       
347
348 /* Remove the given channel from all groups */
349 void action_groups_remove_channel (bAction *act, FCurve *fcu)
350 {
351         /* sanity checks */
352         if (ELEM(NULL, act, fcu))       
353                 return;
354         
355         /* check if any group used this directly */
356         if (fcu->grp) {
357                 bActionGroup *agrp= fcu->grp;
358                 
359                 if (agrp->channels.first == agrp->channels.last) {
360                         if (agrp->channels.first == fcu) {
361                                 agrp->channels.first= NULL;
362                                 agrp->channels.last= NULL;
363                         }
364                 }
365                 else if (agrp->channels.first == fcu) {
366                         if ((fcu->next) && (fcu->next->grp==agrp))
367                                 agrp->channels.first= fcu->next;
368                         else
369                                 agrp->channels.first= NULL;
370                 }
371                 else if (agrp->channels.last == fcu) {
372                         if ((fcu->prev) && (fcu->prev->grp==agrp))
373                                 agrp->channels.last= fcu->prev;
374                         else
375                                 agrp->channels.last= NULL;
376                 }
377                 
378                 fcu->grp= NULL;
379         }
380         
381         /* now just remove from list */
382         BLI_remlink(&act->curves, fcu);
383 }
384
385 /* Find a group with the given name */
386 bActionGroup *action_groups_find_named (bAction *act, const char name[])
387 {
388         /* sanity checks */
389         if (ELEM3(NULL, act, act->groups.first, name) || (name[0] == 0))
390                 return NULL;
391                 
392         /* do string comparisons */
393         return BLI_findstring(&act->groups, name, offsetof(bActionGroup, name));
394 }
395
396 /* Clear all 'temp' flags on all groups */
397 void action_groups_clear_tempflags (bAction *act)
398 {
399         bActionGroup *agrp;
400         
401         /* sanity checks */
402         if (ELEM(NULL, act, act->groups.first))
403                 return;
404                 
405         /* flag clearing loop */
406         for (agrp = act->groups.first; agrp; agrp = agrp->next)
407                 agrp->flag &= ~AGRP_TEMP;
408 }
409
410 /* *************** Pose channels *************** */
411
412 /* usually used within a loop, so we got a N^2 slowdown */
413 bPoseChannel *get_pose_channel(const bPose *pose, const char *name)
414 {
415         if (ELEM(NULL, pose, name) || (name[0] == 0))
416                 return NULL;
417         
418         if(pose->chanhash)
419                 return BLI_ghash_lookup(pose->chanhash, (void *)name);
420         
421         return BLI_findstring(&((bPose *)pose)->chanbase, name, offsetof(bPoseChannel, name));
422 }
423
424 /* Use with care, not on Armature poses but for temporal ones */
425 /* (currently used for action constraints and in rebuild_pose) */
426 bPoseChannel *verify_pose_channel(bPose *pose, const char *name)
427 {
428         bPoseChannel *chan;
429         
430         if (pose == NULL)
431                 return NULL;
432         
433         /* See if this channel exists */
434         chan= BLI_findstring(&pose->chanbase, name, offsetof(bPoseChannel, name));
435         if(chan) {
436                 return chan;
437         }
438
439         /* If not, create it and add it */
440         chan = MEM_callocN(sizeof(bPoseChannel), "verifyPoseChannel");
441         
442         BLI_strncpy(chan->name, name, sizeof(chan->name));
443         /* init vars to prevent math errors */
444         unit_qt(chan->quat);
445         unit_axis_angle(chan->rotAxis, &chan->rotAngle);
446         chan->size[0] = chan->size[1] = chan->size[2] = 1.0f;
447         
448         chan->limitmin[0]= chan->limitmin[1]= chan->limitmin[2]= -180.0f;
449         chan->limitmax[0]= chan->limitmax[1]= chan->limitmax[2]= 180.0f;
450         chan->stiffness[0]= chan->stiffness[1]= chan->stiffness[2]= 0.0f;
451         chan->ikrotweight = chan->iklinweight = 0.0f;
452         unit_m4(chan->constinv);
453         
454         chan->protectflag = OB_LOCK_ROT4D;      /* lock by components by default */
455         
456         BLI_addtail(&pose->chanbase, chan);
457         free_pose_channels_hash(pose);
458         
459         return chan;
460 }
461
462 /* Find the active posechannel for an object (we can't just use pose, as layer info is in armature) */
463 bPoseChannel *get_active_posechannel (Object *ob)
464 {
465         bArmature *arm= (ob) ? ob->data : NULL;
466         bPoseChannel *pchan;
467         
468         if ELEM3(NULL, ob, ob->pose, arm)
469                 return NULL;
470         
471         /* find active */
472         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
473                 if ((pchan->bone) && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
474                         return pchan;
475         }
476         
477         return NULL;
478 }
479
480 const char *get_ikparam_name(bPose *pose)
481 {
482         if (pose) {
483                 switch (pose->iksolver) {
484                 case IKSOLVER_LEGACY:
485                         return NULL;
486                 case IKSOLVER_ITASC:
487                         return "bItasc";
488                 }
489         }
490         return NULL;
491 }
492 /* dst should be freed already, makes entire duplicate */
493 void copy_pose (bPose **dst, bPose *src, int copycon)
494 {
495         bPose *outPose;
496         bPoseChannel *pchan;
497         ListBase listb;
498         
499         if (!src) {
500                 *dst=NULL;
501                 return;
502         }
503         
504         if (*dst==src) {
505                 printf("copy_pose source and target are the same\n");
506                 *dst=NULL;
507                 return;
508         }
509         
510         outPose= MEM_callocN(sizeof(bPose), "pose");
511         
512         BLI_duplicatelist(&outPose->chanbase, &src->chanbase);
513         
514         outPose->iksolver = src->iksolver;
515         outPose->ikdata = NULL;
516         outPose->ikparam = MEM_dupallocN(src->ikparam);
517         
518         for (pchan=outPose->chanbase.first; pchan; pchan=pchan->next) {
519                 // TODO: rename this argument...
520                 if (copycon) {
521                         copy_constraints(&listb, &pchan->constraints, TRUE);  // copy_constraints NULLs listb
522                         pchan->constraints= listb;
523                         pchan->mpath= NULL; /* motion paths should not get copied yet... */
524                 }
525                 
526                 if(pchan->prop) {
527                         pchan->prop= IDP_CopyProperty(pchan->prop);
528                 }
529         }
530
531         /* for now, duplicate Bone Groups too when doing this */
532         if (copycon)
533                 BLI_duplicatelist(&outPose->agroups, &src->agroups);
534         
535         *dst=outPose;
536 }
537
538 void init_pose_itasc(bItasc *itasc)
539 {
540         if (itasc) {
541                 itasc->iksolver = IKSOLVER_ITASC;
542                 itasc->minstep = 0.01f;
543                 itasc->maxstep = 0.06f;
544                 itasc->numiter = 100;
545                 itasc->numstep = 4;
546                 itasc->precision = 0.005f;
547                 itasc->flag = ITASC_AUTO_STEP|ITASC_INITIAL_REITERATION;
548                 itasc->feedback = 20.f;
549                 itasc->maxvel = 50.f;
550                 itasc->solver = ITASC_SOLVER_SDLS;
551                 itasc->dampmax = 0.5;
552                 itasc->dampeps = 0.15;
553         }
554 }
555 void init_pose_ikparam(bPose *pose)
556 {
557         bItasc *itasc;
558         switch (pose->iksolver) {
559         case IKSOLVER_ITASC:
560                 itasc = MEM_callocN(sizeof(bItasc), "itasc");
561                 init_pose_itasc(itasc);
562                 pose->ikparam = itasc;
563                 break;
564         case IKSOLVER_LEGACY:
565         default:
566                 pose->ikparam = NULL;
567                 break;
568         }
569 }
570
571 void make_pose_channels_hash(bPose *pose) 
572 {
573         if(!pose->chanhash) {
574                 bPoseChannel *pchan;
575
576                 pose->chanhash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "make_pose_chan gh");
577                 for(pchan=pose->chanbase.first; pchan; pchan=pchan->next)
578                         BLI_ghash_insert(pose->chanhash, pchan->name, pchan);
579         }
580 }
581
582 void free_pose_channels_hash(bPose *pose) 
583 {
584         if(pose->chanhash) {
585                 BLI_ghash_free(pose->chanhash, NULL, NULL);
586                 pose->chanhash= NULL;
587         }
588 }
589
590
591 void free_pose_channel(bPoseChannel *pchan)
592 {
593
594         if (pchan->mpath) {
595                 animviz_free_motionpath(pchan->mpath);
596                 pchan->mpath= NULL;
597         }
598
599         free_constraints(&pchan->constraints);
600         
601         if (pchan->prop) {
602                 IDP_FreeProperty(pchan->prop);
603                 MEM_freeN(pchan->prop);
604         }
605 }
606
607 void free_pose_channels(bPose *pose) 
608 {
609         bPoseChannel *pchan;
610         
611         if (pose->chanbase.first) {
612                 for (pchan = pose->chanbase.first; pchan; pchan=pchan->next)
613                         free_pose_channel(pchan);
614                 
615                 BLI_freelistN(&pose->chanbase);
616         }
617
618         free_pose_channels_hash(pose);
619 }
620
621 void free_pose(bPose *pose)
622 {
623         if (pose) {
624                 /* free pose-channels */
625                 free_pose_channels(pose);
626                 
627                 /* free pose-groups */
628                 if (pose->agroups.first)
629                         BLI_freelistN(&pose->agroups);
630                 
631                 /* free IK solver state */
632                 BIK_clear_data(pose);
633                 
634                 /* free IK solver param */
635                 if (pose->ikparam)
636                         MEM_freeN(pose->ikparam);
637                 
638                 /* free pose */
639                 MEM_freeN(pose);
640         }
641 }
642
643 static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan)
644 {
645         bConstraint *pcon, *con;
646         
647         copy_v3_v3(pchan->loc, chan->loc);
648         copy_v3_v3(pchan->size, chan->size);
649         copy_v3_v3(pchan->eul, chan->eul);
650         copy_v3_v3(pchan->rotAxis, chan->rotAxis);
651         pchan->rotAngle= chan->rotAngle;
652         copy_qt_qt(pchan->quat, chan->quat);
653         pchan->rotmode= chan->rotmode;
654         copy_m4_m4(pchan->chan_mat, (float(*)[4])chan->chan_mat);
655         copy_m4_m4(pchan->pose_mat, (float(*)[4])chan->pose_mat);
656         pchan->flag= chan->flag;
657         
658         con= chan->constraints.first;
659         for(pcon= pchan->constraints.first; pcon && con; pcon= pcon->next, con= con->next) {
660                 pcon->enforce= con->enforce;
661                 pcon->headtail= con->headtail;
662         }
663 }
664
665 /* makes copies of internal data, unlike copy_pose_channel_data which only
666  * copies the pose state.
667  * hint: use when copying bones in editmode (on returned value from verify_pose_channel) */
668 void duplicate_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *pchan_from)
669 {
670         /* copy transform locks */
671         pchan->protectflag = pchan_from->protectflag;
672
673         /* copy rotation mode */
674         pchan->rotmode = pchan_from->rotmode;
675
676         /* copy bone group */
677         pchan->agrp_index= pchan_from->agrp_index;
678
679         /* ik (dof) settings */
680         pchan->ikflag = pchan_from->ikflag;
681         copy_v3_v3(pchan->limitmin, pchan_from->limitmin);
682         copy_v3_v3(pchan->limitmax, pchan_from->limitmax);
683         copy_v3_v3(pchan->stiffness, pchan_from->stiffness);
684         pchan->ikstretch= pchan_from->ikstretch;
685         pchan->ikrotweight= pchan_from->ikrotweight;
686         pchan->iklinweight= pchan_from->iklinweight;
687
688         /* constraints */
689         copy_constraints(&pchan->constraints, &pchan_from->constraints, TRUE);
690
691         /* id-properties */
692         if(pchan->prop) {
693                 /* unlikely but possible it exists */
694                 IDP_FreeProperty(pchan->prop);
695                 MEM_freeN(pchan->prop);
696                 pchan->prop= NULL;
697         }
698         if(pchan_from->prop) {
699                 pchan->prop= IDP_CopyProperty(pchan_from->prop);
700         }
701
702         /* custom shape */
703         pchan->custom= pchan_from->custom;
704 }
705
706
707 /* checks for IK constraint, Spline IK, and also for Follow-Path constraint.
708  * can do more constraints flags later 
709  */
710 /* pose should be entirely OK */
711 void update_pose_constraint_flags(bPose *pose)
712 {
713         bPoseChannel *pchan, *parchan;
714         bConstraint *con;
715         
716         /* clear */
717         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
718                 pchan->constflag= 0;
719         }
720         pose->flag &= ~POSE_CONSTRAINTS_TIMEDEPEND;
721         
722         /* detect */
723         for (pchan= pose->chanbase.first; pchan; pchan=pchan->next) {
724                 for (con= pchan->constraints.first; con; con= con->next) {
725                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
726                                 bKinematicConstraint *data = (bKinematicConstraint*)con->data;
727                                 
728                                 pchan->constflag |= PCHAN_HAS_IK;
729                                 
730                                 if(data->tar==NULL || (data->tar->type==OB_ARMATURE && data->subtarget[0]==0))
731                                         pchan->constflag |= PCHAN_HAS_TARGET;
732                                 
733                                 /* negative rootbone = recalc rootbone index. used in do_versions */
734                                 if(data->rootbone<0) {
735                                         data->rootbone= 0;
736                                         
737                                         if(data->flag & CONSTRAINT_IK_TIP) parchan= pchan;
738                                         else parchan= pchan->parent;
739                                         
740                                         while(parchan) {
741                                                 data->rootbone++;
742                                                 if((parchan->bone->flag & BONE_CONNECTED)==0)
743                                                         break;
744                                                 parchan= parchan->parent;
745                                         }
746                                 }
747                         }
748                         else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) {
749                                 bFollowPathConstraint *data= (bFollowPathConstraint *)con->data;
750                                 
751                                 /* for drawing constraint colors when color set allows this */
752                                 pchan->constflag |= PCHAN_HAS_CONST;
753                                 
754                                 /* if we have a valid target, make sure that this will get updated on frame-change
755                                  * (needed for when there is no anim-data for this pose)
756                                  */
757                                 if ((data->tar) && (data->tar->type==OB_CURVE))
758                                         pose->flag |= POSE_CONSTRAINTS_TIMEDEPEND;
759                         }
760                         else if (con->type == CONSTRAINT_TYPE_SPLINEIK)
761                                 pchan->constflag |= PCHAN_HAS_SPLINEIK;
762                         else 
763                                 pchan->constflag |= PCHAN_HAS_CONST;
764                 }
765         }
766 }
767
768 /* Clears all BONE_UNKEYED flags for every pose channel in every pose 
769  * This should only be called on frame changing, when it is acceptable to
770  * do this. Otherwise, these flags should not get cleared as poses may get lost.
771  */
772 void framechange_poses_clear_unkeyed(void)
773 {
774         Object *ob;
775         bPose *pose;
776         bPoseChannel *pchan;
777         
778         /* This needs to be done for each object that has a pose */
779         // TODO: proxies may/may not be correctly handled here... (this needs checking) 
780         for (ob= G.main->object.first; ob; ob= ob->id.next) {
781                 /* we only need to do this on objects with a pose */
782                 if ( (pose= ob->pose) ) {
783                         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
784                                 if (pchan->bone) 
785                                         pchan->bone->flag &= ~BONE_UNKEYED;
786                         }
787                 }
788         }
789 }
790
791 /* ************************** Bone Groups ************************** */
792
793 /* Adds a new bone-group */
794 void pose_add_group (Object *ob)
795 {
796         bPose *pose= (ob) ? ob->pose : NULL;
797         bActionGroup *grp;
798         
799         if (ELEM(NULL, ob, ob->pose))
800                 return;
801         
802         grp= MEM_callocN(sizeof(bActionGroup), "PoseGroup");
803         BLI_strncpy(grp->name, "Group", sizeof(grp->name));
804         BLI_addtail(&pose->agroups, grp);
805         BLI_uniquename(&pose->agroups, grp, "Group", '.', offsetof(bActionGroup, name), sizeof(grp->name));
806         
807         pose->active_group= BLI_countlist(&pose->agroups);
808 }
809
810 /* Remove the active bone-group */
811 void pose_remove_group (Object *ob)
812 {
813         bPose *pose= (ob) ? ob->pose : NULL;
814         bActionGroup *grp = NULL;
815         bPoseChannel *pchan;
816         
817         /* sanity checks */
818         if (ELEM(NULL, ob, pose))
819                 return;
820         if (pose->active_group <= 0)
821                 return;
822         
823         /* get group to remove */
824         grp= BLI_findlink(&pose->agroups, pose->active_group-1);
825         if (grp) {
826                 /* adjust group references (the trouble of using indices!):
827                  *      - firstly, make sure nothing references it 
828                  *      - also, make sure that those after this item get corrected
829                  */
830                 for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
831                         if (pchan->agrp_index == pose->active_group)
832                                 pchan->agrp_index= 0;
833                         else if (pchan->agrp_index > pose->active_group)
834                                 pchan->agrp_index--;
835                 }
836                 
837                 /* now, remove it from the pose */
838                 BLI_freelinkN(&pose->agroups, grp);
839                 pose->active_group--;
840                 if(pose->active_group < 0 || pose->agroups.first == NULL) {
841                         pose->active_group= 0;
842                 }
843         }
844 }
845
846 /* ************** F-Curve Utilities for Actions ****************** */
847
848 /* Check if the given action has any keyframes */
849 short action_has_motion(const bAction *act)
850 {
851         FCurve *fcu;
852         
853         /* return on the first F-Curve that has some keyframes/samples defined */
854         if (act) {
855                 for (fcu= act->curves.first; fcu; fcu= fcu->next) {
856                         if (fcu->totvert)
857                                 return 1;
858                 }
859         }
860         
861         /* nothing found */
862         return 0;
863 }
864
865 /* Calculate the extents of given action */
866 void calc_action_range(const bAction *act, float *start, float *end, short incl_modifiers)
867 {
868         FCurve *fcu;
869         float min=999999999.0f, max=-999999999.0f;
870         short foundvert=0, foundmod=0;
871
872         if (act) {
873                 for (fcu= act->curves.first; fcu; fcu= fcu->next) {
874                         /* if curve has keyframes, consider them first */
875                         if (fcu->totvert) {
876                                 float nmin, nmax;
877                                 
878                                 /* get extents for this curve */
879                                 // TODO: allow enabling/disabling this?
880                                 calc_fcurve_range(fcu, &nmin, &nmax, FALSE, TRUE);
881                                 
882                                 /* compare to the running tally */
883                                 min= MIN2(min, nmin);
884                                 max= MAX2(max, nmax);
885                                 
886                                 foundvert= 1;
887                         }
888                         
889                         /* if incl_modifiers is enabled, need to consider modifiers too
890                          *      - only really care about the last modifier
891                          */
892                         if ((incl_modifiers) && (fcu->modifiers.last)) {
893                                 FModifier *fcm= fcu->modifiers.last;
894                                 
895                                 /* only use the maximum sensible limits of the modifiers if they are more extreme */
896                                 switch (fcm->type) {
897                                         case FMODIFIER_TYPE_LIMITS: /* Limits F-Modifier */
898                                         {
899                                                 FMod_Limits *fmd= (FMod_Limits *)fcm->data;
900                                                 
901                                                 if (fmd->flag & FCM_LIMIT_XMIN) {
902                                                         min= MIN2(min, fmd->rect.xmin);
903                                                 }
904                                                 if (fmd->flag & FCM_LIMIT_XMAX) {
905                                                         max= MAX2(max, fmd->rect.xmax);
906                                                 }
907                                         }
908                                                 break;
909                                                 
910                                         case FMODIFIER_TYPE_CYCLES: /* Cycles F-Modifier */
911                                         {
912                                                 FMod_Cycles *fmd= (FMod_Cycles *)fcm->data;
913                                                 
914                                                 if (fmd->before_mode != FCM_EXTRAPOLATE_NONE)
915                                                         min= MINAFRAMEF;
916                                                 if (fmd->after_mode != FCM_EXTRAPOLATE_NONE)
917                                                         max= MAXFRAMEF;
918                                         }
919                                                 break;
920                                                 
921                                         // TODO: function modifier may need some special limits
922                                                 
923                                         default: /* all other standard modifiers are on the infinite range... */
924                                                 min= MINAFRAMEF;
925                                                 max= MAXFRAMEF;
926                                                 break;
927                                 }
928                                 
929                                 foundmod= 1;
930                         }
931                 }
932         }       
933         
934         if (foundvert || foundmod) {
935                 if(min==max) max+= 1.0f;
936                 *start= min;
937                 *end= max;
938         }
939         else {
940                 *start= 0.0f;
941                 *end= 1.0f;
942         }
943 }
944
945 /* Return flags indicating which transforms the given object/posechannel has 
946  *      - if 'curves' is provided, a list of links to these curves are also returned
947  */
948 short action_get_item_transforms (bAction *act, Object *ob, bPoseChannel *pchan, ListBase *curves)
949 {
950         PointerRNA ptr;
951         FCurve *fcu;
952         char *basePath=NULL;
953         short flags=0;
954         
955         /* build PointerRNA from provided data to obtain the paths to use */
956         if (pchan)
957                 RNA_pointer_create((ID *)ob, &RNA_PoseBone, pchan, &ptr);
958         else if (ob)
959                 RNA_id_pointer_create((ID *)ob, &ptr);
960         else    
961                 return 0;
962                 
963         /* get the basic path to the properties of interest */
964         basePath= RNA_path_from_ID_to_struct(&ptr);
965         if (basePath == NULL)
966                 return 0;
967                 
968         /* search F-Curves for the given properties 
969          *      - we cannot use the groups, since they may not be grouped in that way...
970          */
971         for (fcu= act->curves.first; fcu; fcu= fcu->next) {
972                 char *bPtr=NULL, *pPtr=NULL;
973                 
974                 /* if enough flags have been found, we can stop checking unless we're also getting the curves */
975                 if ((flags == ACT_TRANS_ALL) && (curves == NULL))
976                         break;
977                         
978                 /* just in case... */
979                 if (fcu->rna_path == NULL)
980                         continue;
981                 
982                 /* step 1: check for matching base path */
983                 bPtr= strstr(fcu->rna_path, basePath);
984                 
985                 if (bPtr) {
986                         /* we must add len(basePath) bytes to the match so that we are at the end of the 
987                          * base path so that we don't get false positives with these strings in the names
988                          */
989                         bPtr += strlen(basePath);
990                         
991                         /* step 2: check for some property with transforms 
992                          *      - to speed things up, only check for the ones not yet found 
993                          *        unless we're getting the curves too
994                          *      - if we're getting the curves, the BLI_genericNodeN() creates a LinkData
995                          *        node wrapping the F-Curve, which then gets added to the list
996                          *      - once a match has been found, the curve cannot possibly be any other one
997                          */
998                         if ((curves) || (flags & ACT_TRANS_LOC) == 0) {
999                                 pPtr= strstr(bPtr, "location");
1000                                 if (pPtr) {
1001                                         flags |= ACT_TRANS_LOC;
1002                                         
1003                                         if (curves) 
1004                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1005                                         continue;
1006                                 }
1007                         }
1008                         
1009                         if ((curves) || (flags & ACT_TRANS_SCALE) == 0) {
1010                                 pPtr= strstr(bPtr, "scale");
1011                                 if (pPtr) {
1012                                         flags |= ACT_TRANS_SCALE;
1013                                         
1014                                         if (curves) 
1015                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1016                                         continue;
1017                                 }
1018                         }
1019                         
1020                         if ((curves) || (flags & ACT_TRANS_ROT) == 0) {
1021                                 pPtr= strstr(bPtr, "rotation");
1022                                 if (pPtr) {
1023                                         flags |= ACT_TRANS_ROT;
1024                                         
1025                                         if (curves) 
1026                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1027                                         continue;
1028                                 }
1029                         }
1030                         
1031                         if ((curves) || (flags & ACT_TRANS_PROP) == 0) {
1032                                 /* custom properties only */
1033                                 pPtr= strstr(bPtr, "[\""); /* extra '"' comment here to keep my texteditor functionlist working :) */  
1034                                 if (pPtr) {
1035                                         flags |= ACT_TRANS_PROP;
1036                                         
1037                                         if (curves)
1038                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1039                                         continue;
1040                                 }
1041                         }
1042                 }
1043         }
1044         
1045         /* free basePath */
1046         MEM_freeN(basePath);
1047         
1048         /* return flags found */
1049         return flags;
1050 }
1051
1052 /* ************** Pose Management Tools ****************** */
1053
1054 /* Copy the data from the action-pose (src) into the pose */
1055 /* both args are assumed to be valid */
1056 /* exported to game engine */
1057 /* Note! this assumes both poses are aligned, this isnt always true when dealing with user poses */
1058 void extract_pose_from_pose(bPose *pose, const bPose *src)
1059 {
1060         const bPoseChannel *schan;
1061         bPoseChannel *pchan= pose->chanbase.first;
1062
1063         if (pose==src) {
1064                 printf("extract_pose_from_pose source and target are the same\n");
1065                 return;
1066         }
1067
1068         for (schan=src->chanbase.first; (schan && pchan); schan=schan->next, pchan= pchan->next) {
1069                 copy_pose_channel_data(pchan, schan);
1070         }
1071 }
1072
1073 /* for do_all_pose_actions, clears the pose. Now also exported for proxy and tools */
1074 void rest_pose(bPose *pose)
1075 {
1076         bPoseChannel *pchan;
1077         
1078         if (!pose)
1079                 return;
1080         
1081         memset(pose->stride_offset, 0, sizeof(pose->stride_offset));
1082         memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset));
1083         
1084         for (pchan=pose->chanbase.first; pchan; pchan= pchan->next) {
1085                 zero_v3(pchan->loc);
1086                 zero_v3(pchan->eul);
1087                 unit_qt(pchan->quat);
1088                 unit_axis_angle(pchan->rotAxis, &pchan->rotAngle);
1089                 pchan->size[0]= pchan->size[1]= pchan->size[2]= 1.0f;
1090
1091                 pchan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1092         }
1093 }
1094
1095 /* both poses should be in sync */
1096 void copy_pose_result(bPose *to, bPose *from)
1097 {
1098         bPoseChannel *pchanto, *pchanfrom;
1099         
1100         if(to==NULL || from==NULL) {
1101                 printf("pose result copy error to:%p from:%p\n", (void *)to, (void *)from); // debug temp
1102                 return;
1103         }
1104
1105         if (to==from) {
1106                 printf("copy_pose_result source and target are the same\n");
1107                 return;
1108         }
1109
1110
1111         for(pchanfrom= from->chanbase.first; pchanfrom; pchanfrom= pchanfrom->next) {
1112                 pchanto= get_pose_channel(to, pchanfrom->name);
1113                 if(pchanto) {
1114                         copy_m4_m4(pchanto->pose_mat, pchanfrom->pose_mat);
1115                         copy_m4_m4(pchanto->chan_mat, pchanfrom->chan_mat);
1116                         
1117                         /* used for local constraints */
1118                         copy_v3_v3(pchanto->loc, pchanfrom->loc);
1119                         copy_qt_qt(pchanto->quat, pchanfrom->quat);
1120                         copy_v3_v3(pchanto->eul, pchanfrom->eul);
1121                         copy_v3_v3(pchanto->size, pchanfrom->size);
1122                         
1123                         copy_v3_v3(pchanto->pose_head, pchanfrom->pose_head);
1124                         copy_v3_v3(pchanto->pose_tail, pchanfrom->pose_tail);
1125                         
1126                         pchanto->rotmode= pchanfrom->rotmode;
1127                         pchanto->flag= pchanfrom->flag;
1128                         pchanto->protectflag= pchanfrom->protectflag;
1129                 }
1130         }
1131 }
1132
1133 /* For the calculation of the effects of an Action at the given frame on an object 
1134  * This is currently only used for the Action Constraint 
1135  */
1136 void what_does_obaction (Object *ob, Object *workob, bPose *pose, bAction *act, char groupname[], float cframe)
1137 {
1138         bActionGroup *agrp= action_groups_find_named(act, groupname);
1139         
1140         /* clear workob */
1141         clear_workob(workob);
1142         
1143         /* init workob */
1144         copy_m4_m4(workob->obmat, ob->obmat);
1145         copy_m4_m4(workob->parentinv, ob->parentinv);
1146         copy_m4_m4(workob->constinv, ob->constinv);
1147         workob->parent= ob->parent;
1148         
1149         workob->rotmode= ob->rotmode;
1150         
1151         workob->trackflag= ob->trackflag;
1152         workob->upflag= ob->upflag;
1153         
1154         workob->partype= ob->partype;
1155         workob->par1= ob->par1;
1156         workob->par2= ob->par2;
1157         workob->par3= ob->par3;
1158
1159         workob->constraints.first = ob->constraints.first;
1160         workob->constraints.last = ob->constraints.last;
1161         
1162         workob->pose= pose;     /* need to set pose too, since this is used for both types of Action Constraint */
1163
1164         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
1165         BLI_strncpy(workob->id.name, "OB<ConstrWorkOb>", sizeof(workob->id.name)); /* we don't use real object name, otherwise RNA screws with the real thing */
1166         
1167         /* if we're given a group to use, it's likely to be more efficient (though a bit more dangerous) */
1168         if (agrp) {
1169                 /* specifically evaluate this group only */
1170                 PointerRNA id_ptr;
1171                 
1172                 /* get RNA-pointer for the workob's ID */
1173                 RNA_id_pointer_create(&workob->id, &id_ptr);
1174                 
1175                 /* execute action for this group only */
1176                 animsys_evaluate_action_group(&id_ptr, act, agrp, NULL, cframe);
1177         }
1178         else {
1179                 AnimData adt= {NULL};
1180                 
1181                 /* init animdata, and attach to workob */
1182                 workob->adt= &adt;
1183                 
1184                 adt.recalc= ADT_RECALC_ANIM;
1185                 adt.action= act;
1186                 
1187                 /* execute effects of Action on to workob (or it's PoseChannels) */
1188                 BKE_animsys_evaluate_animdata(NULL, &workob->id, &adt, cframe, ADT_RECALC_ANIM);
1189         }
1190 }
1191
1192 /* ********** NLA with non-poses works with ipo channels ********** */
1193
1194 #if 0 // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)
1195
1196 /* ************************ Blending with NLA *************** */
1197
1198 static void blend_pose_strides(bPose *dst, bPose *src, float srcweight, short mode)
1199 {
1200         float dstweight;
1201         
1202         switch (mode){
1203                 case ACTSTRIPMODE_BLEND:
1204                         dstweight = 1.0F - srcweight;
1205                         break;
1206                 case ACTSTRIPMODE_ADD:
1207                         dstweight = 1.0F;
1208                         break;
1209                 default :
1210                         dstweight = 1.0F;
1211         }
1212         
1213         interp_v3_v3v3(dst->stride_offset, dst->stride_offset, src->stride_offset, srcweight);
1214 }
1215
1216
1217 /* 
1218
1219 bone matching diagram, strips A and B
1220
1221                                  .------------------------.
1222                                  |         A              |
1223                                  '------------------------'
1224                                  .          .             b2
1225                                  .          .-------------v----------.
1226                                  .              |         B   .          |
1227                                  .          '------------------------'
1228                                  .          .             .
1229                                  .          .             .
1230 offset:          .    0     .    A-B      .  A-b2+B     
1231                                  .          .             .
1232
1233 */
1234
1235
1236 static void blend_pose_offset_bone(bActionStrip *strip, bPose *dst, bPose *src, float srcweight, short mode)
1237 {
1238         /* matching offset bones */
1239         /* take dst offset, and put src on on that location */
1240         
1241         if(strip->offs_bone[0]==0)
1242                 return;
1243         
1244         /* are we also blending with matching bones? */
1245         if(strip->prev && strip->start>=strip->prev->start) {
1246                 bPoseChannel *dpchan= get_pose_channel(dst, strip->offs_bone);
1247                 if(dpchan) {
1248                         bPoseChannel *spchan= get_pose_channel(src, strip->offs_bone);
1249                         if(spchan) {
1250                                 float vec[3];
1251                                 
1252                                 /* dst->ctime has the internal strip->prev action time */
1253                                 /* map this time to nla time */
1254                                 
1255                                 float ctime= get_actionstrip_frame(strip, src->ctime, 1);
1256                                 
1257                                 if( ctime > strip->prev->end) {
1258                                         bActionChannel *achan;
1259                                         
1260                                         /* add src to dest, minus the position of src on strip->prev->end */
1261                                         
1262                                         ctime= get_actionstrip_frame(strip, strip->prev->end, 0);
1263                                         
1264                                         achan= get_action_channel(strip->act, strip->offs_bone);
1265                                         if(achan && achan->ipo) {
1266                                                 bPoseChannel pchan;
1267                                                 /* Evaluates and sets the internal ipo value */
1268                                                 calc_ipo(achan->ipo, ctime);
1269                                                 /* This call also sets the pchan flags */
1270                                                 execute_action_ipo(achan, &pchan);
1271                                                 
1272                                                 /* store offset that moves src to location of pchan */
1273                                                 sub_v3_v3v3(vec, dpchan->loc, pchan.loc);
1274                                                 
1275                                                 mul_mat3_m4_v3(dpchan->bone->arm_mat, vec);
1276                                         }
1277                                 }
1278                                 else {
1279                                         /* store offset that moves src to location of dst */
1280                                         
1281                                         sub_v3_v3v3(vec, dpchan->loc, spchan->loc);
1282                                         mul_mat3_m4_v3(dpchan->bone->arm_mat, vec);
1283                                 }
1284                                 
1285                                 /* if blending, we only add with factor scrweight */
1286                                 mul_v3_fl(vec, srcweight);
1287                                 
1288                                 add_v3_v3(dst->cyclic_offset, vec);
1289                         }
1290                 }
1291         }
1292         
1293         add_v3_v3(dst->cyclic_offset, src->cyclic_offset);
1294 }
1295
1296 /* added "sizecorr" here, to allow armatures to be scaled and still have striding.
1297    Only works for uniform scaling. In general I'd advise against scaling armatures ever though! (ton)
1298 */
1299 static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
1300 {
1301         bAction *act= strip->act;
1302         const char *name= strip->stridechannel;
1303         bActionChannel *achan= get_action_channel(act, name);
1304         int stride_axis= strip->stride_axis;
1305
1306         if(achan && achan->ipo) {
1307                 IpoCurve *icu= NULL;
1308                 float minx=0.0f, maxx=0.0f, miny=0.0f, maxy=0.0f;
1309                 int foundvert= 0;
1310                 
1311                 if(stride_axis==0) stride_axis= AC_LOC_X;
1312                 else if(stride_axis==1) stride_axis= AC_LOC_Y;
1313                 else stride_axis= AC_LOC_Z;
1314                 
1315                 /* calculate the min/max */
1316                 for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
1317                         if(icu->adrcode==stride_axis) {
1318                                 if(icu->totvert>1) {
1319                                         foundvert= 1;
1320                                         minx= icu->bezt[0].vec[1][0];
1321                                         maxx= icu->bezt[icu->totvert-1].vec[1][0];
1322                                         
1323                                         miny= icu->bezt[0].vec[1][1];
1324                                         maxy= icu->bezt[icu->totvert-1].vec[1][1];
1325                                 }
1326                                 break;
1327                         }
1328                 }
1329                 
1330                 if(foundvert && miny!=maxy) {
1331                         float stridelen= sizecorr*fabs(maxy-miny), striptime;
1332                         float actiondist, pdist, pdistNewNormalized, offs;
1333                         float vec1[4], vec2[4], dir[3];
1334                         
1335                         /* internal cycling, actoffs is in frames */
1336                         offs= stridelen*strip->actoffs/(maxx-minx);
1337                         
1338                         /* amount path moves object */
1339                         pdist = (float)fmod (pathdist+offs, stridelen);
1340                         striptime= pdist/stridelen;
1341                         
1342                         /* amount stride bone moves */
1343                         actiondist= sizecorr*eval_icu(icu, minx + striptime*(maxx-minx)) - miny;
1344                         
1345                         pdist = fabs(actiondist) - pdist;
1346                         pdistNewNormalized = (pathdist+pdist)/path->totdist;
1347                         
1348                         /* now we need to go pdist further (or less) on cu path */
1349                         where_on_path(ob, (pathdist)/path->totdist, vec1, dir); /* vec needs size 4 */
1350                         if (pdistNewNormalized <= 1) {
1351                                 // search for correction in positive path-direction
1352                                 where_on_path(ob, pdistNewNormalized, vec2, dir);       /* vec needs size 4 */
1353                                 sub_v3_v3v3(stride_offset, vec2, vec1);
1354                         }
1355                         else {
1356                                 // we reached the end of the path, search backwards instead
1357                                 where_on_path(ob, (pathdist-pdist)/path->totdist, vec2, dir);   /* vec needs size 4 */
1358                                 sub_v3_v3v3(stride_offset, vec1, vec2);
1359                         }
1360                         mul_mat3_m4_v3(ob->obmat, stride_offset);
1361                         return striptime;
1362                 }
1363         }
1364         return 0.0f;
1365 }
1366
1367 static void cyclic_offs_bone(Object *ob, bPose *pose, bActionStrip *strip, float time)
1368 {
1369         /* only called when strip has cyclic, so >= 1.0f works... */
1370         if(time >= 1.0f) {
1371                 bActionChannel *achan= get_action_channel(strip->act, strip->offs_bone);
1372
1373                 if(achan && achan->ipo) {
1374                         IpoCurve *icu= NULL;
1375                         Bone *bone;
1376                         float min[3]={0.0f, 0.0f, 0.0f}, max[3]={0.0f, 0.0f, 0.0f};
1377                         int index=0, foundvert= 0;
1378                         
1379                         /* calculate the min/max */
1380                         for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
1381                                 if(icu->totvert>1) {
1382                                         
1383                                         if(icu->adrcode==AC_LOC_X)
1384                                                 index= 0;
1385                                         else if(icu->adrcode==AC_LOC_Y)
1386                                                 index= 1;
1387                                         else if(icu->adrcode==AC_LOC_Z)
1388                                                 index= 2;
1389                                         else
1390                                                 continue;
1391                                 
1392                                         foundvert= 1;
1393                                         min[index]= icu->bezt[0].vec[1][1];
1394                                         max[index]= icu->bezt[icu->totvert-1].vec[1][1];
1395                                 }
1396                         }
1397                         if(foundvert) {
1398                                 /* bring it into armature space */
1399                                 sub_v3_v3v3(min, max, min);
1400                                 bone= get_named_bone(ob->data, strip->offs_bone);       /* weak */
1401                                 if(bone) {
1402                                         mul_mat3_m4_v3(bone->arm_mat, min);
1403                                         
1404                                         /* dominant motion, cyclic_offset was cleared in rest_pose */
1405                                         if (strip->flag & (ACTSTRIP_CYCLIC_USEX | ACTSTRIP_CYCLIC_USEY | ACTSTRIP_CYCLIC_USEZ)) {
1406                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEX) pose->cyclic_offset[0]= time*min[0];
1407                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEY) pose->cyclic_offset[1]= time*min[1];
1408                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEZ) pose->cyclic_offset[2]= time*min[2];
1409                                         } else {
1410                                                 if( fabs(min[0]) >= fabs(min[1]) && fabs(min[0]) >= fabs(min[2]))
1411                                                         pose->cyclic_offset[0]= time*min[0];
1412                                                 else if( fabs(min[1]) >= fabs(min[0]) && fabs(min[1]) >= fabs(min[2]))
1413                                                         pose->cyclic_offset[1]= time*min[1];
1414                                                 else
1415                                                         pose->cyclic_offset[2]= time*min[2];
1416                                         }
1417                                 }
1418                         }
1419                 }
1420         }
1421 }
1422
1423 /* simple case for now; only the curve path with constraint value > 0.5 */
1424 /* blending we might do later... */
1425 static Object *get_parent_path(Object *ob)
1426 {
1427         bConstraint *con;
1428         
1429         if(ob->parent && ob->parent->type==OB_CURVE)
1430                 return ob->parent;
1431         
1432         for (con = ob->constraints.first; con; con=con->next) {
1433                 if(con->type==CONSTRAINT_TYPE_FOLLOWPATH) {
1434                         if(con->enforce>0.5f) {
1435                                 bFollowPathConstraint *data= con->data;
1436                                 return data->tar;
1437                         }
1438                 }
1439         }
1440         return NULL;
1441 }
1442
1443 /* ************** do the action ************ */
1444
1445 /* ----- nla, etc. --------- */
1446
1447 static void do_nla(Scene *scene, Object *ob, int blocktype)
1448 {
1449         bPose *tpose= NULL;
1450         Key *key= NULL;
1451         ListBase tchanbase={NULL, NULL}, chanbase={NULL, NULL};
1452         bActionStrip *strip, *striplast=NULL, *stripfirst=NULL;
1453         float striptime, frametime, length, actlength;
1454         float blendfac, stripframe;
1455         float scene_cfra= BKE_curframe(scene);
1456         int     doit, dostride;
1457         
1458         if(blocktype==ID_AR) {
1459                 copy_pose(&tpose, ob->pose, 1);
1460                 rest_pose(ob->pose);            // potentially destroying current not-keyed pose
1461         }
1462         else {
1463                 key= ob_get_key(ob);
1464         }
1465         
1466         /* check on extend to left or right, when no strip is hit by 'cfra' */
1467         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1468                 /* escape loop on a hit */
1469                 if( scene_cfra >= strip->start && scene_cfra <= strip->end + 0.1f)      /* note 0.1 comes back below */
1470                         break;
1471                 if(scene_cfra < strip->start) {
1472                         if(stripfirst==NULL)
1473                                 stripfirst= strip;
1474                         else if(stripfirst->start > strip->start)
1475                                 stripfirst= strip;
1476                 }
1477                 else if(scene_cfra > strip->end) {
1478                         if(striplast==NULL)
1479                                 striplast= strip;
1480                         else if(striplast->end < strip->end)
1481                                 striplast= strip;
1482                 }
1483         }
1484         if(strip==NULL) {       /* extend */
1485                 if(striplast)
1486                         scene_cfra= striplast->end;
1487                 else if(stripfirst)
1488                         scene_cfra= stripfirst->start;
1489         }
1490         
1491         /* and now go over all strips */
1492         for (strip=ob->nlastrips.first; strip; strip=strip->next){
1493                 doit=dostride= 0;
1494                 
1495                 if (strip->act && !(strip->flag & ACTSTRIP_MUTE)) {     /* so theres an action */
1496                         
1497                         /* Determine if the current frame is within the strip's range */
1498                         length = strip->end-strip->start;
1499                         actlength = strip->actend-strip->actstart;
1500                         striptime = (scene_cfra-(strip->start)) / length;
1501                         stripframe = (scene_cfra-(strip->start)) ;
1502
1503                         if (striptime>=0.0){
1504                                 
1505                                 if(blocktype==ID_AR) 
1506                                         rest_pose(tpose);
1507                                 
1508                                 /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1509                                 if (striptime < 1.0f + 0.1f/length) {
1510                                         
1511                                         /* Handle path */
1512                                         if ((strip->flag & ACTSTRIP_USESTRIDE) && (blocktype==ID_AR) && (ob->ipoflag & OB_DISABLE_PATH)==0){
1513                                                 Object *parent= get_parent_path(ob);
1514                                                 
1515                                                 if (parent) {
1516                                                         Curve *cu = parent->data;
1517                                                         float ctime, pdist;
1518                                                         
1519                                                         if (cu->flag & CU_PATH){
1520                                                                 /* Ensure we have a valid path */
1521                                                                 if(cu->path==NULL || cu->path->data==NULL) makeDispListCurveTypes(scene, parent, 0);
1522                                                                 if(cu->path) {
1523                                                                         
1524                                                                         /* Find the position on the path */
1525                                                                         ctime= bsystem_time(scene, ob, scene_cfra, 0.0);
1526                                                                         
1527                                                                         if(calc_ipo_spec(cu->ipo, CU_SPEED, &ctime)==0) {
1528                                                                                 /* correct for actions not starting on zero */
1529                                                                                 ctime= (ctime - strip->actstart)/cu->pathlen;
1530                                                                                 CLAMP(ctime, 0.0, 1.0);
1531                                                                         }
1532                                                                         pdist = ctime*cu->path->totdist;
1533                                                                         
1534                                                                         if(tpose && strip->stridechannel[0]) {
1535                                                                                 striptime= stridechannel_frame(parent, ob->size[0], strip, cu->path, pdist, tpose->stride_offset);
1536                                                                         }                                                                       
1537                                                                         else {
1538                                                                                 if (strip->stridelen) {
1539                                                                                         striptime = pdist / strip->stridelen;
1540                                                                                         striptime = (float)fmod (striptime+strip->actoffs, 1.0);
1541                                                                                 }
1542                                                                                 else
1543                                                                                         striptime = 0;
1544                                                                         }
1545                                                                         
1546                                                                         frametime = (striptime * actlength) + strip->actstart;
1547                                                                         frametime= bsystem_time(scene, ob, frametime, 0.0);
1548                                                                         
1549                                                                         if(blocktype==ID_AR) {
1550                                                                                 extract_pose_from_action (tpose, strip->act, frametime);
1551                                                                         }
1552                                                                         else if(blocktype==ID_OB) {
1553                                                                                 extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1554                                                                                 if(key)
1555                                                                                         extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1556                                                                         }
1557                                                                         doit=dostride= 1;
1558                                                                 }
1559                                                         }
1560                                                 }
1561                                         }
1562                                         /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1563                                         else  {
1564                                                 
1565                                                 /* Mod to repeat */
1566                                                 if(strip->repeat!=1.0f) {
1567                                                         float cycle= striptime*strip->repeat;
1568                                                         
1569                                                         striptime = (float)fmod (cycle, 1.0f + 0.1f/length);
1570                                                         cycle-= striptime;
1571                                                         
1572                                                         if(blocktype==ID_AR)
1573                                                                 cyclic_offs_bone(ob, tpose, strip, cycle);
1574                                                 }
1575
1576                                                 frametime = (striptime * actlength) + strip->actstart;
1577                                                 frametime= nla_time(scene, frametime, (float)strip->repeat);
1578                                                         
1579                                                 if(blocktype==ID_AR) {
1580                                                         extract_pose_from_action (tpose, strip->act, frametime);
1581                                                 }
1582                                                 else if(blocktype==ID_OB) {
1583                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1584                                                         if(key)
1585                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1586                                                 }
1587                                                 
1588                                                 doit=1;
1589                                         }
1590                                 }
1591                                 /* Handle extend */
1592                                 else {
1593                                         if (strip->flag & ACTSTRIP_HOLDLASTFRAME){
1594                                                 /* we want the strip to hold on the exact fraction of the repeat value */
1595                                                 
1596                                                 frametime = actlength * (strip->repeat-(int)strip->repeat);
1597                                                 if(frametime<=0.000001f) frametime= actlength;  /* rounding errors... */
1598                                                 frametime= bsystem_time(scene, ob, frametime+strip->actstart, 0.0);
1599                                                 
1600                                                 if(blocktype==ID_AR)
1601                                                         extract_pose_from_action (tpose, strip->act, frametime);
1602                                                 else if(blocktype==ID_OB) {
1603                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1604                                                         if(key)
1605                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1606                                                 }
1607                                                 
1608                                                 /* handle cycle hold */
1609                                                 if(strip->repeat!=1.0f) {
1610                                                         if(blocktype==ID_AR)
1611                                                                 cyclic_offs_bone(ob, tpose, strip, strip->repeat-1.0f);
1612                                                 }
1613                                                 
1614                                                 doit=1;
1615                                         }
1616                                 }
1617                                 
1618                                 /* Handle blendin & blendout */
1619                                 if (doit){
1620                                         /* Handle blendin */
1621                                         
1622                                         if (strip->blendin>0.0 && stripframe<=strip->blendin && scene_cfra>=strip->start){
1623                                                 blendfac = stripframe/strip->blendin;
1624                                         }
1625                                         else if (strip->blendout>0.0 && stripframe>=(length-strip->blendout) && scene_cfra<=strip->end){
1626                                                 blendfac = (length-stripframe)/(strip->blendout);
1627                                         }
1628                                         else
1629                                                 blendfac = 1;
1630                                         
1631                                         if(blocktype==ID_AR) {/* Blend this pose with the accumulated pose */
1632                                                 /* offset bone, for matching cycles */
1633                                                 blend_pose_offset_bone (strip, ob->pose, tpose, blendfac, strip->mode);
1634                                                 
1635                                                 blend_poses (ob->pose, tpose, blendfac, strip->mode);
1636                                                 if(dostride)
1637                                                         blend_pose_strides (ob->pose, tpose, blendfac, strip->mode);
1638                                         }
1639                                         else {
1640                                                 blend_ipochannels(&chanbase, &tchanbase, blendfac, strip->mode);
1641                                                 BLI_freelistN(&tchanbase);
1642                                         }
1643                                 }
1644                         }                                       
1645                 }
1646         }
1647         
1648         if(blocktype==ID_OB) {
1649                 execute_ipochannels(&chanbase);
1650         }
1651         else if(blocktype==ID_AR) {
1652                 /* apply stride offset to object */
1653                 add_v3_v3(ob->obmat[3], ob->pose->stride_offset);
1654         }
1655         
1656         /* free */
1657         if (tpose)
1658                 free_pose(tpose);
1659         if(chanbase.first)
1660                 BLI_freelistN(&chanbase);
1661 }
1662
1663 #endif // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)