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