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