2.5 - Animation Utility Function
[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 /* *************** Action Groups *************** */
216
217 /* Get the active action-group for an Action */
218 bActionGroup *get_active_actiongroup (bAction *act)
219 {
220         bActionGroup *agrp= NULL;
221         
222         if (act && act->groups.first) { 
223                 for (agrp= act->groups.first; agrp; agrp= agrp->next) {
224                         if (agrp->flag & AGRP_ACTIVE)
225                                 break;
226                 }
227         }
228         
229         return agrp;
230 }
231
232 /* Make the given Action-Group the active one */
233 void set_active_action_group (bAction *act, bActionGroup *agrp, short select)
234 {
235         bActionGroup *grp;
236         
237         /* sanity checks */
238         if (act == NULL)
239                 return;
240         
241         /* Deactive all others */
242         for (grp= act->groups.first; grp; grp= grp->next) {
243                 if ((grp==agrp) && (select))
244                         grp->flag |= AGRP_ACTIVE;
245                 else    
246                         grp->flag &= ~AGRP_ACTIVE;
247         }
248 }
249
250 /* Add given channel into (active) group 
251  *      - assumes that channel is not linked to anything anymore
252  *      - always adds at the end of the group 
253  */
254 void action_groups_add_channel (bAction *act, bActionGroup *agrp, FCurve *fcurve)
255 {
256         FCurve *fcu;
257         short done=0;
258         
259         /* sanity checks */
260         if (ELEM3(NULL, act, agrp, fcurve))
261                 return;
262         
263         /* if no channels, just add to two lists at the same time */
264         if (act->curves.first == NULL) {
265                 fcurve->next = fcurve->prev = NULL;
266                 
267                 agrp->channels.first = agrp->channels.last = fcurve;
268                 act->curves.first = act->curves.last = fcurve;
269                 
270                 fcurve->grp= agrp;
271                 return;
272         }
273         
274         /* try to find a channel to slot this in before/after */
275         for (fcu= act->curves.first; fcu; fcu= fcu->next) {
276                 /* if channel has no group, then we have ungrouped channels, which should always occur after groups */
277                 if (fcu->grp == NULL) {
278                         BLI_insertlinkbefore(&act->curves, fcu, fcurve);
279                         
280                         if (agrp->channels.first == NULL)
281                                 agrp->channels.first= fcurve;
282                         agrp->channels.last= fcurve;
283                         
284                         done= 1;
285                         break;
286                 }
287                 
288                 /* if channel has group after current, we can now insert (otherwise we have gone too far) */
289                 else if (fcu->grp == agrp->next) {
290                         BLI_insertlinkbefore(&act->curves, fcu, fcurve);
291                         
292                         if (agrp->channels.first == NULL)
293                                 agrp->channels.first= fcurve;
294                         agrp->channels.last= fcurve;
295                         
296                         done= 1;
297                         break;
298                 }
299                 
300                 /* if channel has group we're targeting, check whether it is the last one of these */
301                 else if (fcu->grp == agrp) {
302                         if ((fcu->next) && (fcu->next->grp != agrp)) {
303                                 BLI_insertlinkafter(&act->curves, fcu, fcurve);
304                                 agrp->channels.last= fcurve;
305                                 done= 1;
306                                 break;
307                         }
308                         else if (fcu->next == NULL) {
309                                 BLI_addtail(&act->curves, fcurve);
310                                 agrp->channels.last= fcurve;
311                                 done= 1;
312                                 break;
313                         }
314                 }
315                 
316                 /* if channel has group before target, check whether the next one is something after target */
317                 else if (fcu->grp == agrp->prev) {
318                         if (fcu->next) {
319                                 if ((fcu->next->grp != fcu->grp) && (fcu->next->grp != agrp)) {
320                                         BLI_insertlinkafter(&act->curves, fcu, fcurve);
321                                         
322                                         agrp->channels.first= fcurve;
323                                         agrp->channels.last= fcurve;
324                                         
325                                         done= 1;
326                                         break;
327                                 }
328                         }
329                         else {
330                                 BLI_insertlinkafter(&act->curves, fcu, fcurve);
331                                 
332                                 agrp->channels.first= fcurve;
333                                 agrp->channels.last= fcurve;
334                                 
335                                 done= 1;
336                                 break;
337                         }
338                 }
339         }
340         
341         /* only if added, set channel as belonging to this group */
342         if (done) {
343                 //printf("FCurve added to group \n");
344                 fcurve->grp= agrp;
345         }
346         else {
347                 printf("Error: FCurve '%s' couldn't be added to Group '%s' \n", fcurve->rna_path, agrp->name);
348                 BLI_addtail(&act->curves, fcurve);
349         }
350 }       
351
352 /* Remove the given channel from all groups */
353 void action_groups_remove_channel (bAction *act, FCurve *fcu)
354 {
355         /* sanity checks */
356         if (ELEM(NULL, act, fcu))       
357                 return;
358         
359         /* check if any group used this directly */
360         if (fcu->grp) {
361                 bActionGroup *agrp= fcu->grp;
362                 
363                 if (agrp->channels.first == agrp->channels.last) {
364                         if (agrp->channels.first == fcu) {
365                                 agrp->channels.first= NULL;
366                                 agrp->channels.last= NULL;
367                         }
368                 }
369                 else if (agrp->channels.first == fcu) {
370                         if ((fcu->next) && (fcu->next->grp==agrp))
371                                 agrp->channels.first= fcu->next;
372                         else
373                                 agrp->channels.first= NULL;
374                 }
375                 else if (agrp->channels.last == fcu) {
376                         if ((fcu->prev) && (fcu->prev->grp==agrp))
377                                 agrp->channels.last= fcu->prev;
378                         else
379                                 agrp->channels.last= NULL;
380                 }
381                 
382                 fcu->grp= NULL;
383         }
384         
385         /* now just remove from list */
386         BLI_remlink(&act->curves, fcu);
387 }
388
389 /* Find a group with the given name */
390 bActionGroup *action_groups_find_named (bAction *act, const char name[])
391 {
392         bActionGroup *grp;
393         
394         /* sanity checks */
395         if (ELEM3(NULL, act, act->groups.first, name) || (name[0] == 0))
396                 return NULL;
397                 
398         /* do string comparisons */
399         for (grp= act->groups.first; grp; grp= grp->next) {
400                 if (strcmp(grp->name, name) == 0)
401                         return grp;
402         }
403         
404         /* not found */
405         return NULL;
406 }
407
408 /* *************** Pose channels *************** */
409
410 /* usually used within a loop, so we got a N^2 slowdown */
411 bPoseChannel *get_pose_channel(const bPose *pose, const char *name)
412 {
413         bPoseChannel *chan;
414         
415         if (ELEM(NULL, pose, name) || (name[0] == 0))
416                 return NULL;
417         
418         for (chan=pose->chanbase.first; chan; chan=chan->next) {
419                 if (chan->name[0] == name[0]) {
420                         if (!strcmp (chan->name, name))
421                                 return chan;
422                 }
423         }
424
425         return NULL;
426 }
427
428 /* Use with care, not on Armature poses but for temporal ones */
429 /* (currently used for action constraints and in rebuild_pose) */
430 bPoseChannel *verify_pose_channel(bPose* pose, const char* name)
431 {
432         bPoseChannel *chan;
433         
434         if (pose == NULL)
435                 return NULL;
436         
437         /* See if this channel exists */
438         for (chan=pose->chanbase.first; chan; chan=chan->next) {
439                 if (!strcmp (name, chan->name))
440                         return chan;
441         }
442         
443         /* If not, create it and add it */
444         chan = MEM_callocN(sizeof(bPoseChannel), "verifyPoseChannel");
445         
446         strncpy(chan->name, name, 31);
447         /* init vars to prevent math errors */
448         chan->quat[0] = 1.0f;
449         chan->size[0] = chan->size[1] = chan->size[2] = 1.0f;
450         
451         chan->limitmin[0]= chan->limitmin[1]= chan->limitmin[2]= -180.0f;
452         chan->limitmax[0]= chan->limitmax[1]= chan->limitmax[2]= 180.0f;
453         chan->stiffness[0]= chan->stiffness[1]= chan->stiffness[2]= 0.0f;
454         
455         Mat4One(chan->constinv);
456         
457         BLI_addtail(&pose->chanbase, chan);
458         
459         return chan;
460 }
461
462 /* Find the active posechannel for an object (we can't just use pose, as layer info is in armature) */
463 bPoseChannel *get_active_posechannel (Object *ob)
464 {
465         bArmature *arm= (ob) ? ob->data : NULL;
466         bPoseChannel *pchan;
467         
468         if ELEM3(NULL, ob, ob->pose, arm)
469                 return NULL;
470         
471         /* find active */
472         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
473                 if ((pchan->bone) && (pchan->bone->flag & BONE_ACTIVE) && (pchan->bone->layer & arm->layer))
474                         return pchan;
475         }
476         
477         return NULL;
478 }
479
480
481 /* dst should be freed already, makes entire duplicate */
482 void copy_pose (bPose **dst, bPose *src, int copycon)
483 {
484         bPose *outPose;
485         bPoseChannel    *pchan;
486         ListBase listb;
487         
488         if (!src){
489                 *dst=NULL;
490                 return;
491         }
492         
493         if (*dst==src) {
494                 printf("copy_pose source and target are the same\n");
495                 *dst=NULL;
496                 return;
497         }
498         
499         outPose= MEM_callocN(sizeof(bPose), "pose");
500         
501         BLI_duplicatelist(&outPose->chanbase, &src->chanbase);
502         
503         if (copycon) {
504                 for (pchan=outPose->chanbase.first; pchan; pchan=pchan->next) {
505                         copy_constraints(&listb, &pchan->constraints);  // copy_constraints NULLs listb
506                         pchan->constraints= listb;
507                         pchan->path= NULL;
508                 }
509         }
510         
511         *dst=outPose;
512 }
513
514 void free_pose_channels(bPose *pose) 
515 {
516         bPoseChannel *pchan;
517         
518         if (pose->chanbase.first) {
519                 for (pchan = pose->chanbase.first; pchan; pchan=pchan->next){
520                         if (pchan->path)
521                                 MEM_freeN(pchan->path);
522                         free_constraints(&pchan->constraints);
523                 }
524                 BLI_freelistN(&pose->chanbase);
525         }
526 }
527
528 void free_pose(bPose *pose)
529 {
530         if (pose) {
531                 /* free pose-channels */
532                 free_pose_channels(pose);
533                 
534                 /* free pose-groups */
535                 if (pose->agroups.first)
536                         BLI_freelistN(&pose->agroups);
537                 
538                 /* free pose */
539                 MEM_freeN(pose);
540         }
541 }
542
543 void game_copy_pose(bPose **dst, bPose *src)
544 {
545         bPose *out;
546         bPoseChannel *pchan, *outpchan;
547         GHash *ghash;
548         
549         /* the game engine copies the current armature pose and then swaps
550          * the object pose pointer. this makes it possible to change poses
551          * without affecting the original blender data. */
552
553         if (!src) {
554                 *dst=NULL;
555                 return;
556         }
557         else if (*dst==src) {
558                 printf("copy_pose source and target are the same\n");
559                 *dst=NULL;
560                 return;
561         }
562         
563         out= MEM_dupallocN(src);
564         out->agroups.first= out->agroups.last= NULL;
565         BLI_duplicatelist(&out->chanbase, &src->chanbase);
566
567         /* remap pointers */
568         ghash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
569
570         pchan= src->chanbase.first;
571         outpchan= out->chanbase.first;
572         for (; pchan; pchan=pchan->next, outpchan=outpchan->next)
573                 BLI_ghash_insert(ghash, pchan, outpchan);
574
575         for (pchan=out->chanbase.first; pchan; pchan=pchan->next) {
576                 pchan->parent= BLI_ghash_lookup(ghash, pchan->parent);
577                 pchan->child= BLI_ghash_lookup(ghash, pchan->child);
578                 pchan->path= NULL;
579         }
580
581         BLI_ghash_free(ghash, NULL, NULL);
582         
583         *dst=out;
584 }
585
586
587 /* Only allowed for Poses with identical channels */
588 void game_blend_poses(bPose *dst, bPose *src, float srcweight/*, short mode*/)
589 {
590         short mode= ACTSTRIPMODE_BLEND;
591         
592         bPoseChannel *dchan;
593         const bPoseChannel *schan;
594         bConstraint *dcon, *scon;
595         float dstweight;
596         int i;
597
598         switch (mode){
599         case ACTSTRIPMODE_BLEND:
600                 dstweight = 1.0F - srcweight;
601                 break;
602         case ACTSTRIPMODE_ADD:
603                 dstweight = 1.0F;
604                 break;
605         default :
606                 dstweight = 1.0F;
607         }
608         
609         schan= src->chanbase.first;
610         for (dchan = dst->chanbase.first; dchan; dchan=dchan->next, schan= schan->next){
611                 if (schan->flag & (POSE_ROT|POSE_LOC|POSE_SIZE)) {
612                         /* replaced quat->matrix->quat conversion with decent quaternion interpol (ton) */
613                         
614                         /* Do the transformation blend */
615                         if (schan->flag & POSE_ROT) {
616                                 /* quat interpolation done separate */
617                                 if (schan->rotmode == PCHAN_ROT_QUAT) {
618                                         float dquat[4], squat[4];
619                                         
620                                         QUATCOPY(dquat, dchan->quat);
621                                         QUATCOPY(squat, schan->quat);
622                                         if (mode==ACTSTRIPMODE_BLEND)
623                                                 QuatInterpol(dchan->quat, dquat, squat, srcweight);
624                                         else {
625                                                 QuatMulFac(squat, srcweight);
626                                                 QuatMul(dchan->quat, dquat, squat);
627                                         }
628                                         
629                                         NormalQuat(dchan->quat);
630                                 }
631                         }
632
633                         for (i=0; i<3; i++) {
634                                 /* blending for loc and scale are pretty self-explanatory... */
635                                 if (schan->flag & POSE_LOC)
636                                         dchan->loc[i] = (dchan->loc[i]*dstweight) + (schan->loc[i]*srcweight);
637                                 if (schan->flag & POSE_SIZE)
638                                         dchan->size[i] = 1.0f + ((dchan->size[i]-1.0f)*dstweight) + ((schan->size[i]-1.0f)*srcweight);
639                                 
640                                 /* euler-rotation interpolation done here instead... */
641                                 // FIXME: are these results decent?
642                                 if ((schan->flag & POSE_ROT) && (schan->rotmode))
643                                         dchan->eul[i] = (dchan->eul[i]*dstweight) + (schan->eul[i]*srcweight);
644                         }
645                         dchan->flag |= schan->flag;
646                 }
647                 for(dcon= dchan->constraints.first, scon= schan->constraints.first; dcon && scon; dcon= dcon->next, scon= scon->next) {
648                         /* no 'add' option for constraint blending */
649                         dcon->enforce= dcon->enforce*(1.0f-srcweight) + scon->enforce*srcweight;
650                 }
651         }
652         
653         /* this pose is now in src time */
654         dst->ctime= src->ctime;
655 }
656
657 void game_free_pose(bPose *pose)
658 {
659         if (pose) {
660                 /* we don't free constraints, those are owned by the original pose */
661                 if(pose->chanbase.first)
662                         BLI_freelistN(&pose->chanbase);
663                 
664                 MEM_freeN(pose);
665         }
666 }
667
668 static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan)
669 {
670         bConstraint *pcon, *con;
671         
672         VECCOPY(pchan->loc, chan->loc);
673         VECCOPY(pchan->size, chan->size);
674         VECCOPY(pchan->eul, chan->eul);
675         QUATCOPY(pchan->quat, chan->quat);
676         pchan->rotmode= chan->rotmode;
677         Mat4CpyMat4(pchan->chan_mat, (float(*)[4])chan->chan_mat);
678         Mat4CpyMat4(pchan->pose_mat, (float(*)[4])chan->pose_mat);
679         pchan->flag= chan->flag;
680         
681         con= chan->constraints.first;
682         for(pcon= pchan->constraints.first; pcon; pcon= pcon->next, con= con->next) {
683                 pcon->enforce= con->enforce;
684                 pcon->headtail= con->headtail;
685         }
686 }
687
688 /* checks for IK constraint, and also for Follow-Path constraint.
689  * can do more constraints flags later 
690  */
691 /* pose should be entirely OK */
692 void update_pose_constraint_flags(bPose *pose)
693 {
694         bPoseChannel *pchan, *parchan;
695         bConstraint *con;
696         
697         /* clear */
698         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
699                 pchan->constflag= 0;
700         }
701         pose->flag &= ~POSE_CONSTRAINTS_TIMEDEPEND;
702         
703         /* detect */
704         for (pchan= pose->chanbase.first; pchan; pchan=pchan->next) {
705                 for (con= pchan->constraints.first; con; con= con->next) {
706                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
707                                 bKinematicConstraint *data = (bKinematicConstraint*)con->data;
708                                 
709                                 pchan->constflag |= PCHAN_HAS_IK;
710                                 
711                                 if(data->tar==NULL || (data->tar->type==OB_ARMATURE && data->subtarget[0]==0))
712                                         pchan->constflag |= PCHAN_HAS_TARGET;
713                                 
714                                 /* negative rootbone = recalc rootbone index. used in do_versions */
715                                 if(data->rootbone<0) {
716                                         data->rootbone= 0;
717                                         
718                                         if(data->flag & CONSTRAINT_IK_TIP) parchan= pchan;
719                                         else parchan= pchan->parent;
720                                         
721                                         while(parchan) {
722                                                 data->rootbone++;
723                                                 if((parchan->bone->flag & BONE_CONNECTED)==0)
724                                                         break;
725                                                 parchan= parchan->parent;
726                                         }
727                                 }
728                         }
729                         else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) {
730                                 bFollowPathConstraint *data= (bFollowPathConstraint *)con->data;
731                                 
732                                 /* for drawing constraint colors when color set allows this */
733                                 pchan->constflag |= PCHAN_HAS_CONST;
734                                 
735                                 /* if we have a valid target, make sure that this will get updated on frame-change
736                                  * (needed for when there is no anim-data for this pose)
737                                  */
738                                 if ((data->tar) && (data->tar->type==OB_CURVE))
739                                         pose->flag |= POSE_CONSTRAINTS_TIMEDEPEND;
740                         }
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
921 /* Return flags indicating which transforms the given object/posechannel has 
922  *      - if 'curves' is provided, a list of links to these curves are also returned
923  */
924 short action_get_item_transforms (bAction *act, Object *ob, bPoseChannel *pchan, ListBase *curves)
925 {
926         PointerRNA ptr;
927         FCurve *fcu;
928         char *basePath=NULL;
929         short flags=0;
930         
931         /* build PointerRNA from provided data to obtain the paths to use */
932         if (pchan)
933                 RNA_pointer_create((ID *)ob, &RNA_PoseChannel, pchan, &ptr);
934         else if (ob)
935                 RNA_id_pointer_create((ID *)ob, &ptr);
936         else    
937                 return 0;
938                 
939         /* get the basic path to the properties of interest */
940         basePath= RNA_path_from_ID_to_struct(&ptr);
941         if (basePath == NULL)
942                 return 0;
943                 
944         /* search F-Curves for the given properties 
945          *      - we cannot use the groups, since they may not be grouped in that way...
946          */
947         for (fcu= act->curves.first; fcu; fcu= fcu->next) {
948                 char *bPtr=NULL, *pPtr=NULL;
949                 
950                 /* if enough flags have been found, we can stop checking unless we're also getting the curves */
951                 if ((flags == ACT_TRANS_ALL) && (curves == NULL))
952                         break;
953                         
954                 /* just in case... */
955                 if (fcu->rna_path == NULL)
956                         continue;
957                 
958                 /* step 1: check for matching base path */
959                 bPtr= strstr(fcu->rna_path, basePath);
960                 
961                 if (bPtr) {
962                         /* step 2: check for some property with transforms 
963                          *      - to speed things up, only check for the ones not yet found 
964                          *        unless we're getting the curves too
965                          *      - if we're getting the curves, the BLI_genericNodeN() creates a LinkData
966                          *        node wrapping the F-Curve, which then gets added to the list
967                          *      - once a match has been found, the curve cannot possibly be any other one
968                          */
969                         if ((curves) || (flags & ACT_TRANS_LOC) == 0) {
970                                 pPtr= strstr(fcu->rna_path, "location");
971                                 if ((pPtr) && (pPtr >= bPtr)) {
972                                         flags |= ACT_TRANS_LOC;
973                                         
974                                         if (curves) 
975                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
976                                         continue;
977                                 }
978                         }
979                         
980                         if ((curves) || (flags & ACT_TRANS_SCALE) == 0) {
981                                 pPtr= strstr(fcu->rna_path, "scale");
982                                 if ((pPtr) && (pPtr >= bPtr)) {
983                                         flags |= ACT_TRANS_SCALE;
984                                         
985                                         if (curves) 
986                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
987                                         continue;
988                                 }
989                         }
990                         
991                         if ((curves) || (flags & ACT_TRANS_ROT) == 0) {
992                                 pPtr= strstr(fcu->rna_path, "rotation");
993                                 if ((pPtr) && (pPtr >= bPtr)) {
994                                         flags |= ACT_TRANS_ROT;
995                                         
996                                         if (curves) 
997                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
998                                         continue;
999                                 }
1000                         }
1001                 }
1002         }
1003         
1004         /* free basePath */
1005         MEM_freeN(basePath);
1006         
1007         /* return flags found */
1008         return flags;
1009 }
1010
1011 /* ************** Pose Management Tools ****************** */
1012
1013 /* Copy the data from the action-pose (src) into the pose */
1014 /* both args are assumed to be valid */
1015 /* exported to game engine */
1016 /* Note! this assumes both poses are aligned, this isnt always true when dealing with user poses */
1017 void extract_pose_from_pose(bPose *pose, const bPose *src)
1018 {
1019         const bPoseChannel *schan;
1020         bPoseChannel *pchan= pose->chanbase.first;
1021
1022         if (pose==src) {
1023                 printf("extract_pose_from_pose source and target are the same\n");
1024                 return;
1025         }
1026
1027         for (schan=src->chanbase.first; (schan && pchan); schan=schan->next, pchan= pchan->next) {
1028                 copy_pose_channel_data(pchan, schan);
1029         }
1030 }
1031
1032 /* for do_all_pose_actions, clears the pose. Now also exported for proxy and tools */
1033 void rest_pose(bPose *pose)
1034 {
1035         bPoseChannel *pchan;
1036         int i;
1037         
1038         if (!pose)
1039                 return;
1040         
1041         memset(pose->stride_offset, 0, sizeof(pose->stride_offset));
1042         memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset));
1043         
1044         for (pchan=pose->chanbase.first; pchan; pchan= pchan->next){
1045                 for (i=0; i<3; i++) {
1046                         pchan->loc[i]= 0.0f;
1047                         pchan->quat[i+1]= 0.0f;
1048                         pchan->eul[i]= 0.0f;
1049                         pchan->size[i]= 1.0f;
1050                 }
1051                 pchan->quat[0]= 1.0f;
1052                 
1053                 pchan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1054         }
1055 }
1056
1057 /* both poses should be in sync */
1058 void copy_pose_result(bPose *to, bPose *from)
1059 {
1060         bPoseChannel *pchanto, *pchanfrom;
1061         
1062         if(to==NULL || from==NULL) {
1063                 printf("pose result copy error\n"); // debug temp
1064                 return;
1065         }
1066
1067         if (to==from) {
1068                 printf("copy_pose_result source and target are the same\n");
1069                 return;
1070         }
1071
1072
1073         for(pchanfrom= from->chanbase.first; pchanfrom; pchanfrom= pchanfrom->next) {
1074                 pchanto= get_pose_channel(to, pchanfrom->name);
1075                 if(pchanto) {
1076                         Mat4CpyMat4(pchanto->pose_mat, pchanfrom->pose_mat);
1077                         Mat4CpyMat4(pchanto->chan_mat, pchanfrom->chan_mat);
1078                         
1079                         /* used for local constraints */
1080                         VECCOPY(pchanto->loc, pchanfrom->loc);
1081                         QUATCOPY(pchanto->quat, pchanfrom->quat);
1082                         VECCOPY(pchanto->eul, pchanfrom->eul);
1083                         VECCOPY(pchanto->size, pchanfrom->size);
1084                         
1085                         VECCOPY(pchanto->pose_head, pchanfrom->pose_head);
1086                         VECCOPY(pchanto->pose_tail, pchanfrom->pose_tail);
1087                         pchanto->flag= pchanfrom->flag;
1088                 }
1089         }
1090 }
1091
1092 /* For the calculation of the effects of an Action at the given frame on an object 
1093  * This is currently only used for the Action Constraint 
1094  */
1095 void what_does_obaction (Scene *scene, Object *ob, Object *workob, bPose *pose, bAction *act, char groupname[], float cframe)
1096 {
1097         bActionGroup *agrp= action_groups_find_named(act, groupname);
1098         
1099         /* clear workob */
1100         clear_workob(workob);
1101         
1102         /* init workob */
1103         Mat4CpyMat4(workob->obmat, ob->obmat);
1104         Mat4CpyMat4(workob->parentinv, ob->parentinv);
1105         Mat4CpyMat4(workob->constinv, ob->constinv);
1106         workob->parent= ob->parent;
1107         workob->track= ob->track;
1108
1109         workob->trackflag= ob->trackflag;
1110         workob->upflag= ob->upflag;
1111         
1112         workob->partype= ob->partype;
1113         workob->par1= ob->par1;
1114         workob->par2= ob->par2;
1115         workob->par3= ob->par3;
1116
1117         workob->constraints.first = ob->constraints.first;
1118         workob->constraints.last = ob->constraints.last;
1119         
1120         workob->pose= pose;     /* need to set pose too, since this is used for both types of Action Constraint */
1121
1122         strcpy(workob->parsubstr, ob->parsubstr);
1123         strcpy(workob->id.name, "OB<ConstrWorkOb>"); /* we don't use real object name, otherwise RNA screws with the real thing */
1124         
1125         /* if we're given a group to use, it's likely to be more efficient (though a bit more dangerous) */
1126         if (agrp) {
1127                 /* specifically evaluate this group only */
1128                 PointerRNA id_ptr;
1129                 
1130                 /* get RNA-pointer for the workob's ID */
1131                 RNA_id_pointer_create(&workob->id, &id_ptr);
1132                 
1133                 /* execute action for this group only */
1134                 animsys_evaluate_action_group(&id_ptr, act, agrp, NULL, cframe);
1135         }
1136         else {
1137                 AnimData adt;
1138                 
1139                 /* init animdata, and attach to workob */
1140                 memset(&adt, 0, sizeof(AnimData));
1141                 workob->adt= &adt;
1142                 
1143                 adt.recalc= ADT_RECALC_ANIM;
1144                 adt.action= act;
1145                 
1146                 /* execute effects of Action on to workob (or it's PoseChannels) */
1147                 BKE_animsys_evaluate_animdata(&workob->id, &adt, cframe, ADT_RECALC_ANIM);
1148         }
1149 }
1150
1151 /* ********** NLA with non-poses works with ipo channels ********** */
1152
1153 #if 0 // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)
1154
1155 /* ************************ Blending with NLA *************** */
1156
1157 static void blend_pose_strides(bPose *dst, bPose *src, float srcweight, short mode)
1158 {
1159         float dstweight;
1160         
1161         switch (mode){
1162                 case ACTSTRIPMODE_BLEND:
1163                         dstweight = 1.0F - srcweight;
1164                         break;
1165                 case ACTSTRIPMODE_ADD:
1166                         dstweight = 1.0F;
1167                         break;
1168                 default :
1169                         dstweight = 1.0F;
1170         }
1171         
1172         VecLerpf(dst->stride_offset, dst->stride_offset, src->stride_offset, srcweight);
1173 }
1174
1175
1176 /* 
1177
1178 bone matching diagram, strips A and B
1179
1180                  .------------------------.
1181                  |         A              |
1182                  '------------------------'
1183                                  .          .             b2
1184                  .          .-------------v----------.
1185                  .              |         B   .          |
1186                  .          '------------------------'
1187                  .          .             .
1188                  .          .             .
1189 offset:          .    0     .    A-B      .  A-b2+B     
1190                  .          .             .
1191
1192 */
1193
1194
1195 static void blend_pose_offset_bone(bActionStrip *strip, bPose *dst, bPose *src, float srcweight, short mode)
1196 {
1197         /* matching offset bones */
1198         /* take dst offset, and put src on on that location */
1199         
1200         if(strip->offs_bone[0]==0)
1201                 return;
1202         
1203         /* are we also blending with matching bones? */
1204         if(strip->prev && strip->start>=strip->prev->start) {
1205                 bPoseChannel *dpchan= get_pose_channel(dst, strip->offs_bone);
1206                 if(dpchan) {
1207                         bPoseChannel *spchan= get_pose_channel(src, strip->offs_bone);
1208                         if(spchan) {
1209                                 float vec[3];
1210                                 
1211                                 /* dst->ctime has the internal strip->prev action time */
1212                                 /* map this time to nla time */
1213                                 
1214                                 float ctime= get_actionstrip_frame(strip, src->ctime, 1);
1215                                 
1216                                 if( ctime > strip->prev->end) {
1217                                         bActionChannel *achan;
1218                                         
1219                                         /* add src to dest, minus the position of src on strip->prev->end */
1220                                         
1221                                         ctime= get_actionstrip_frame(strip, strip->prev->end, 0);
1222                                         
1223                                         achan= get_action_channel(strip->act, strip->offs_bone);
1224                                         if(achan && achan->ipo) {
1225                                                 bPoseChannel pchan;
1226                                                 /* Evaluates and sets the internal ipo value */
1227                                                 calc_ipo(achan->ipo, ctime);
1228                                                 /* This call also sets the pchan flags */
1229                                                 execute_action_ipo(achan, &pchan);
1230                                                 
1231                                                 /* store offset that moves src to location of pchan */
1232                                                 VecSubf(vec, dpchan->loc, pchan.loc);
1233                                                 
1234                                                 Mat4Mul3Vecfl(dpchan->bone->arm_mat, vec);
1235                                         }
1236                                 }
1237                                 else {
1238                                         /* store offset that moves src to location of dst */
1239                                         
1240                                         VecSubf(vec, dpchan->loc, spchan->loc);
1241                                         Mat4Mul3Vecfl(dpchan->bone->arm_mat, vec);
1242                                 }
1243                                 
1244                                 /* if blending, we only add with factor scrweight */
1245                                 VecMulf(vec, srcweight);
1246                                 
1247                                 VecAddf(dst->cyclic_offset, dst->cyclic_offset, vec);
1248                         }
1249                 }
1250         }
1251         
1252         VecAddf(dst->cyclic_offset, dst->cyclic_offset, src->cyclic_offset);
1253 }
1254
1255 typedef struct NlaIpoChannel {
1256         struct NlaIpoChannel *next, *prev;
1257         float val;
1258         void *poin;
1259         int type;
1260 } NlaIpoChannel;
1261
1262 static void extract_ipochannels_from_action(ListBase *lb, ID *id, bAction *act, const char *name, float ctime)
1263 {
1264         bActionChannel *achan= get_action_channel(act, name);
1265         IpoCurve *icu;
1266         NlaIpoChannel *nic;
1267         
1268         if(achan==NULL) return;
1269         
1270         if(achan->ipo) {
1271                 calc_ipo(achan->ipo, ctime);
1272                 
1273                 for(icu= achan->ipo->curve.first; icu; icu= icu->next) {
1274                         /* skip IPO_BITS, is for layers and cannot be blended */
1275                         if(icu->vartype != IPO_BITS) {
1276                                 nic= MEM_callocN(sizeof(NlaIpoChannel), "NlaIpoChannel");
1277                                 BLI_addtail(lb, nic);
1278                                 nic->val= icu->curval;
1279                                 nic->poin= get_ipo_poin(id, icu, &nic->type);
1280                         }
1281                 }
1282         }
1283         
1284         /* constraint channels only for objects */
1285         if(GS(id->name)==ID_OB) {
1286                 Object *ob= (Object *)id;
1287                 bConstraint *con;
1288                 bConstraintChannel *conchan;
1289                 
1290                 for (con=ob->constraints.first; con; con=con->next) {
1291                         conchan = get_constraint_channel(&achan->constraintChannels, con->name);
1292                         
1293                         if(conchan && conchan->ipo) {
1294                                 calc_ipo(conchan->ipo, ctime);
1295                                 
1296                                 icu= conchan->ipo->curve.first; // only one ipo now
1297                                 if(icu) {
1298                                         nic= MEM_callocN(sizeof(NlaIpoChannel), "NlaIpoChannel constr");
1299                                         BLI_addtail(lb, nic);
1300                                         nic->val= icu->curval;
1301                                         nic->poin= &con->enforce;
1302                                         nic->type= IPO_FLOAT;
1303                                 }
1304                         }
1305                 }
1306         }
1307 }
1308
1309 static NlaIpoChannel *find_nla_ipochannel(ListBase *lb, void *poin)
1310 {
1311         NlaIpoChannel *nic;
1312         
1313         if(poin) {
1314                 for(nic= lb->first; nic; nic= nic->next) {
1315                         if(nic->poin==poin)
1316                                 return nic;
1317                 }
1318         }
1319         return NULL;
1320 }
1321
1322
1323 static void blend_ipochannels(ListBase *dst, ListBase *src, float srcweight, int mode)
1324 {
1325         NlaIpoChannel *snic, *dnic, *next;
1326         float dstweight;
1327         
1328         switch (mode){
1329                 case ACTSTRIPMODE_BLEND:
1330                         dstweight = 1.0F - srcweight;
1331                         break;
1332                 case ACTSTRIPMODE_ADD:
1333                         dstweight = 1.0F;
1334                         break;
1335                 default :
1336                         dstweight = 1.0F;
1337         }
1338         
1339         for(snic= src->first; snic; snic= next) {
1340                 next= snic->next;
1341                 
1342                 dnic= find_nla_ipochannel(dst, snic->poin);
1343                 if(dnic==NULL) {
1344                         /* remove from src list, and insert in dest */
1345                         BLI_remlink(src, snic);
1346                         BLI_addtail(dst, snic);
1347                 }
1348                 else {
1349                         /* we do the blend */
1350                         dnic->val= dstweight*dnic->val + srcweight*snic->val;
1351                 }
1352         }
1353 }
1354
1355 static int execute_ipochannels(ListBase *lb)
1356 {
1357         NlaIpoChannel *nic;
1358         int count = 0;
1359         
1360         for(nic= lb->first; nic; nic= nic->next) {
1361                 if(nic->poin) {
1362                         write_ipo_poin(nic->poin, nic->type, nic->val);
1363                         count++;
1364                 }
1365         }
1366         return count;
1367 }
1368
1369 /* nla timing */
1370
1371 /* this now only used for repeating cycles, to enable fields and blur. */
1372 /* the whole time control in blender needs serious thinking... */
1373 static float nla_time(Scene *scene, float cfra, float unit)
1374 {
1375         extern float bluroffs;  // bad construct, borrowed from object.c for now
1376         extern float fieldoffs;
1377         
1378         /* motion blur & fields */
1379         cfra+= unit*(bluroffs+fieldoffs);
1380         
1381         /* global time */
1382         cfra*= scene->r.framelen;       
1383         
1384         return cfra;
1385 }
1386
1387 /* added "sizecorr" here, to allow armatures to be scaled and still have striding.
1388    Only works for uniform scaling. In general I'd advise against scaling armatures ever though! (ton)
1389 */
1390 static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
1391 {
1392         bAction *act= strip->act;
1393         const char *name= strip->stridechannel;
1394         bActionChannel *achan= get_action_channel(act, name);
1395         int stride_axis= strip->stride_axis;
1396
1397         if(achan && achan->ipo) {
1398                 IpoCurve *icu= NULL;
1399                 float minx=0.0f, maxx=0.0f, miny=0.0f, maxy=0.0f;
1400                 int foundvert= 0;
1401                 
1402                 if(stride_axis==0) stride_axis= AC_LOC_X;
1403                 else if(stride_axis==1) stride_axis= AC_LOC_Y;
1404                 else stride_axis= AC_LOC_Z;
1405                 
1406                 /* calculate the min/max */
1407                 for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
1408                         if(icu->adrcode==stride_axis) {
1409                                 if(icu->totvert>1) {
1410                                         foundvert= 1;
1411                                         minx= icu->bezt[0].vec[1][0];
1412                                         maxx= icu->bezt[icu->totvert-1].vec[1][0];
1413                                         
1414                                         miny= icu->bezt[0].vec[1][1];
1415                                         maxy= icu->bezt[icu->totvert-1].vec[1][1];
1416                                 }
1417                                 break;
1418                         }
1419                 }
1420                 
1421                 if(foundvert && miny!=maxy) {
1422                         float stridelen= sizecorr*fabs(maxy-miny), striptime;
1423                         float actiondist, pdist, pdistNewNormalized, offs;
1424                         float vec1[4], vec2[4], dir[3];
1425                         
1426                         /* internal cycling, actoffs is in frames */
1427                         offs= stridelen*strip->actoffs/(maxx-minx);
1428                         
1429                         /* amount path moves object */
1430                         pdist = (float)fmod (pathdist+offs, stridelen);
1431                         striptime= pdist/stridelen;
1432                         
1433                         /* amount stride bone moves */
1434                         actiondist= sizecorr*eval_icu(icu, minx + striptime*(maxx-minx)) - miny;
1435                         
1436                         pdist = fabs(actiondist) - pdist;
1437                         pdistNewNormalized = (pathdist+pdist)/path->totdist;
1438                         
1439                         /* now we need to go pdist further (or less) on cu path */
1440                         where_on_path(ob, (pathdist)/path->totdist, vec1, dir); /* vec needs size 4 */
1441                         if (pdistNewNormalized <= 1) {
1442                                 // search for correction in positive path-direction
1443                                 where_on_path(ob, pdistNewNormalized, vec2, dir);       /* vec needs size 4 */
1444                                 VecSubf(stride_offset, vec2, vec1);
1445                         }
1446                         else {
1447                                 // we reached the end of the path, search backwards instead
1448                                 where_on_path(ob, (pathdist-pdist)/path->totdist, vec2, dir);   /* vec needs size 4 */
1449                                 VecSubf(stride_offset, vec1, vec2);
1450                         }
1451                         Mat4Mul3Vecfl(ob->obmat, stride_offset);
1452                         return striptime;
1453                 }
1454         }
1455         return 0.0f;
1456 }
1457
1458 static void cyclic_offs_bone(Object *ob, bPose *pose, bActionStrip *strip, float time)
1459 {
1460         /* only called when strip has cyclic, so >= 1.0f works... */
1461         if(time >= 1.0f) {
1462                 bActionChannel *achan= get_action_channel(strip->act, strip->offs_bone);
1463
1464                 if(achan && achan->ipo) {
1465                         IpoCurve *icu= NULL;
1466                         Bone *bone;
1467                         float min[3]={0.0f, 0.0f, 0.0f}, max[3]={0.0f, 0.0f, 0.0f};
1468                         int index=0, foundvert= 0;
1469                         
1470                         /* calculate the min/max */
1471                         for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
1472                                 if(icu->totvert>1) {
1473                                         
1474                                         if(icu->adrcode==AC_LOC_X)
1475                                                 index= 0;
1476                                         else if(icu->adrcode==AC_LOC_Y)
1477                                                 index= 1;
1478                                         else if(icu->adrcode==AC_LOC_Z)
1479                                                 index= 2;
1480                                         else
1481                                                 continue;
1482                                 
1483                                         foundvert= 1;
1484                                         min[index]= icu->bezt[0].vec[1][1];
1485                                         max[index]= icu->bezt[icu->totvert-1].vec[1][1];
1486                                 }
1487                         }
1488                         if(foundvert) {
1489                                 /* bring it into armature space */
1490                                 VecSubf(min, max, min);
1491                                 bone= get_named_bone(ob->data, strip->offs_bone);       /* weak */
1492                                 if(bone) {
1493                                         Mat4Mul3Vecfl(bone->arm_mat, min);
1494                                         
1495                                         /* dominant motion, cyclic_offset was cleared in rest_pose */
1496                                         if (strip->flag & (ACTSTRIP_CYCLIC_USEX | ACTSTRIP_CYCLIC_USEY | ACTSTRIP_CYCLIC_USEZ)) {
1497                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEX) pose->cyclic_offset[0]= time*min[0];
1498                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEY) pose->cyclic_offset[1]= time*min[1];
1499                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEZ) pose->cyclic_offset[2]= time*min[2];
1500                                         } else {
1501                                                 if( fabs(min[0]) >= fabs(min[1]) && fabs(min[0]) >= fabs(min[2]))
1502                                                         pose->cyclic_offset[0]= time*min[0];
1503                                                 else if( fabs(min[1]) >= fabs(min[0]) && fabs(min[1]) >= fabs(min[2]))
1504                                                         pose->cyclic_offset[1]= time*min[1];
1505                                                 else
1506                                                         pose->cyclic_offset[2]= time*min[2];
1507                                         }
1508                                 }
1509                         }
1510                 }
1511         }
1512 }
1513
1514 /* simple case for now; only the curve path with constraint value > 0.5 */
1515 /* blending we might do later... */
1516 static Object *get_parent_path(Object *ob)
1517 {
1518         bConstraint *con;
1519         
1520         if(ob->parent && ob->parent->type==OB_CURVE)
1521                 return ob->parent;
1522         
1523         for (con = ob->constraints.first; con; con=con->next) {
1524                 if(con->type==CONSTRAINT_TYPE_FOLLOWPATH) {
1525                         if(con->enforce>0.5f) {
1526                                 bFollowPathConstraint *data= con->data;
1527                                 return data->tar;
1528                         }
1529                 }
1530         }
1531         return NULL;
1532 }
1533
1534 /* ************** do the action ************ */
1535
1536 /* ----- nla, etc. --------- */
1537
1538 static void do_nla(Scene *scene, Object *ob, int blocktype)
1539 {
1540         bPose *tpose= NULL;
1541         Key *key= NULL;
1542         ListBase tchanbase={NULL, NULL}, chanbase={NULL, NULL};
1543         bActionStrip *strip, *striplast=NULL, *stripfirst=NULL;
1544         float striptime, frametime, length, actlength;
1545         float blendfac, stripframe;
1546         float scene_cfra= frame_to_float(scene, scene->r.cfra); 
1547         int     doit, dostride;
1548         
1549         if(blocktype==ID_AR) {
1550                 copy_pose(&tpose, ob->pose, 1);
1551                 rest_pose(ob->pose);            // potentially destroying current not-keyed pose
1552         }
1553         else {
1554                 key= ob_get_key(ob);
1555         }
1556         
1557         /* check on extend to left or right, when no strip is hit by 'cfra' */
1558         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1559                 /* escape loop on a hit */
1560                 if( scene_cfra >= strip->start && scene_cfra <= strip->end + 0.1f)      /* note 0.1 comes back below */
1561                         break;
1562                 if(scene_cfra < strip->start) {
1563                         if(stripfirst==NULL)
1564                                 stripfirst= strip;
1565                         else if(stripfirst->start > strip->start)
1566                                 stripfirst= strip;
1567                 }
1568                 else if(scene_cfra > strip->end) {
1569                         if(striplast==NULL)
1570                                 striplast= strip;
1571                         else if(striplast->end < strip->end)
1572                                 striplast= strip;
1573                 }
1574         }
1575         if(strip==NULL) {       /* extend */
1576                 if(striplast)
1577                         scene_cfra= striplast->end;
1578                 else if(stripfirst)
1579                         scene_cfra= stripfirst->start;
1580         }
1581         
1582         /* and now go over all strips */
1583         for (strip=ob->nlastrips.first; strip; strip=strip->next){
1584                 doit=dostride= 0;
1585                 
1586                 if (strip->act && !(strip->flag & ACTSTRIP_MUTE)) {     /* so theres an action */
1587                         
1588                         /* Determine if the current frame is within the strip's range */
1589                         length = strip->end-strip->start;
1590                         actlength = strip->actend-strip->actstart;
1591                         striptime = (scene_cfra-(strip->start)) / length;
1592                         stripframe = (scene_cfra-(strip->start)) ;
1593
1594                         if (striptime>=0.0){
1595                                 
1596                                 if(blocktype==ID_AR) 
1597                                         rest_pose(tpose);
1598                                 
1599                                 /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1600                                 if (striptime < 1.0f + 0.1f/length) {
1601                                         
1602                                         /* Handle path */
1603                                         if ((strip->flag & ACTSTRIP_USESTRIDE) && (blocktype==ID_AR) && (ob->ipoflag & OB_DISABLE_PATH)==0){
1604                                                 Object *parent= get_parent_path(ob);
1605                                                 
1606                                                 if (parent) {
1607                                                         Curve *cu = parent->data;
1608                                                         float ctime, pdist;
1609                                                         
1610                                                         if (cu->flag & CU_PATH){
1611                                                                 /* Ensure we have a valid path */
1612                                                                 if(cu->path==NULL || cu->path->data==NULL) makeDispListCurveTypes(scene, parent, 0);
1613                                                                 if(cu->path) {
1614                                                                         
1615                                                                         /* Find the position on the path */
1616                                                                         ctime= bsystem_time(scene, ob, scene_cfra, 0.0);
1617                                                                         
1618                                                                         if(calc_ipo_spec(cu->ipo, CU_SPEED, &ctime)==0) {
1619                                                                                 /* correct for actions not starting on zero */
1620                                                                                 ctime= (ctime - strip->actstart)/cu->pathlen;
1621                                                                                 CLAMP(ctime, 0.0, 1.0);
1622                                                                         }
1623                                                                         pdist = ctime*cu->path->totdist;
1624                                                                         
1625                                                                         if(tpose && strip->stridechannel[0]) {
1626                                                                                 striptime= stridechannel_frame(parent, ob->size[0], strip, cu->path, pdist, tpose->stride_offset);
1627                                                                         }                                                                       
1628                                                                         else {
1629                                                                                 if (strip->stridelen) {
1630                                                                                         striptime = pdist / strip->stridelen;
1631                                                                                         striptime = (float)fmod (striptime+strip->actoffs, 1.0);
1632                                                                                 }
1633                                                                                 else
1634                                                                                         striptime = 0;
1635                                                                         }
1636                                                                         
1637                                                                         frametime = (striptime * actlength) + strip->actstart;
1638                                                                         frametime= bsystem_time(scene, ob, frametime, 0.0);
1639                                                                         
1640                                                                         if(blocktype==ID_AR) {
1641                                                                                 extract_pose_from_action (tpose, strip->act, frametime);
1642                                                                         }
1643                                                                         else if(blocktype==ID_OB) {
1644                                                                                 extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1645                                                                                 if(key)
1646                                                                                         extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1647                                                                         }
1648                                                                         doit=dostride= 1;
1649                                                                 }
1650                                                         }
1651                                                 }
1652                                         }
1653                                         /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1654                                         else  {
1655                                                 
1656                                                 /* Mod to repeat */
1657                                                 if(strip->repeat!=1.0f) {
1658                                                         float cycle= striptime*strip->repeat;
1659                                                         
1660                                                         striptime = (float)fmod (cycle, 1.0f + 0.1f/length);
1661                                                         cycle-= striptime;
1662                                                         
1663                                                         if(blocktype==ID_AR)
1664                                                                 cyclic_offs_bone(ob, tpose, strip, cycle);
1665                                                 }
1666
1667                                                 frametime = (striptime * actlength) + strip->actstart;
1668                                                 frametime= nla_time(scene, frametime, (float)strip->repeat);
1669                                                         
1670                                                 if(blocktype==ID_AR) {
1671                                                         extract_pose_from_action (tpose, strip->act, frametime);
1672                                                 }
1673                                                 else if(blocktype==ID_OB) {
1674                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1675                                                         if(key)
1676                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1677                                                 }
1678                                                 
1679                                                 doit=1;
1680                                         }
1681                                 }
1682                                 /* Handle extend */
1683                                 else {
1684                                         if (strip->flag & ACTSTRIP_HOLDLASTFRAME){
1685                                                 /* we want the strip to hold on the exact fraction of the repeat value */
1686                                                 
1687                                                 frametime = actlength * (strip->repeat-(int)strip->repeat);
1688                                                 if(frametime<=0.000001f) frametime= actlength;  /* rounding errors... */
1689                                                 frametime= bsystem_time(scene, ob, frametime+strip->actstart, 0.0);
1690                                                 
1691                                                 if(blocktype==ID_AR)
1692                                                         extract_pose_from_action (tpose, strip->act, frametime);
1693                                                 else if(blocktype==ID_OB) {
1694                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1695                                                         if(key)
1696                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1697                                                 }
1698                                                 
1699                                                 /* handle cycle hold */
1700                                                 if(strip->repeat!=1.0f) {
1701                                                         if(blocktype==ID_AR)
1702                                                                 cyclic_offs_bone(ob, tpose, strip, strip->repeat-1.0f);
1703                                                 }
1704                                                 
1705                                                 doit=1;
1706                                         }
1707                                 }
1708                                 
1709                                 /* Handle blendin & blendout */
1710                                 if (doit){
1711                                         /* Handle blendin */
1712                                         
1713                                         if (strip->blendin>0.0 && stripframe<=strip->blendin && scene_cfra>=strip->start){
1714                                                 blendfac = stripframe/strip->blendin;
1715                                         }
1716                                         else if (strip->blendout>0.0 && stripframe>=(length-strip->blendout) && scene_cfra<=strip->end){
1717                                                 blendfac = (length-stripframe)/(strip->blendout);
1718                                         }
1719                                         else
1720                                                 blendfac = 1;
1721                                         
1722                                         if(blocktype==ID_AR) {/* Blend this pose with the accumulated pose */
1723                                                 /* offset bone, for matching cycles */
1724                                                 blend_pose_offset_bone (strip, ob->pose, tpose, blendfac, strip->mode);
1725                                                 
1726                                                 blend_poses (ob->pose, tpose, blendfac, strip->mode);
1727                                                 if(dostride)
1728                                                         blend_pose_strides (ob->pose, tpose, blendfac, strip->mode);
1729                                         }
1730                                         else {
1731                                                 blend_ipochannels(&chanbase, &tchanbase, blendfac, strip->mode);
1732                                                 BLI_freelistN(&tchanbase);
1733                                         }
1734                                 }
1735                         }                                       
1736                 }
1737         }
1738         
1739         if(blocktype==ID_OB) {
1740                 execute_ipochannels(&chanbase);
1741         }
1742         else if(blocktype==ID_AR) {
1743                 /* apply stride offset to object */
1744                 VecAddf(ob->obmat[3], ob->obmat[3], ob->pose->stride_offset);
1745         }
1746         
1747         /* free */
1748         if (tpose)
1749                 free_pose(tpose);
1750         if(chanbase.first)
1751                 BLI_freelistN(&chanbase);
1752 }
1753
1754 #endif // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)