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