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