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