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