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