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