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