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