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