Patch #34204: [Render Animation] Fails with "Error: Specified sample_fmt is not suppo...
[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_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 BKE_pose_where_is 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(Main *bmain, const char name[])
82 {
83         bAction *act;
84         
85         act = BKE_libblock_alloc(&bmain->action, ID_AC, name);
86         
87         return act;
88 }       
89
90 /* .................................. */
91
92 /* temp data for BKE_action_make_local */
93 typedef struct tMakeLocalActionContext {
94         bAction *act;       /* original action */
95         bAction *act_new;   /* new action */
96         
97         int is_lib;         /* some action users were libraries */
98         int is_local;       /* some action users were not libraries */
99 } tMakeLocalActionContext;
100
101 /* helper function for BKE_action_make_local() - 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) mlac->is_lib = TRUE;
108                 else mlac->is_local = TRUE;
109         }
110 }
111
112 /* helper function for BKE_action_make_local() - change references */
113 static void make_localact_apply_cb(ID *id, AnimData *adt, void *mlac_ptr)
114 {
115         tMakeLocalActionContext *mlac = (tMakeLocalActionContext *)mlac_ptr;
116         
117         if (adt->action == mlac->act) {
118                 if (id->lib == NULL) {
119                         adt->action = mlac->act_new;
120                         
121                         id_us_plus(&mlac->act_new->id);
122                         id_us_min(&mlac->act->id);
123                 }
124         }
125 }
126
127 // does copy_fcurve...
128 void BKE_action_make_local(bAction *act)
129 {
130         tMakeLocalActionContext mlac = {act, NULL, FALSE, FALSE};
131         Main *bmain = G.main;
132         
133         if (act->id.lib == NULL)
134                 return;
135         
136         /* XXX: double-check this; it used to be just single-user check, but that was when fake-users were still default */
137         if ((act->id.flag & LIB_FAKEUSER) && (act->id.us <= 1)) {
138                 id_clear_lib_data(bmain, &act->id);
139                 return;
140         }
141         
142         BKE_animdata_main_cb(bmain, make_localact_init_cb, &mlac);
143         
144         if (mlac.is_local && mlac.is_lib == FALSE) {
145                 id_clear_lib_data(bmain, &act->id);
146         }
147         else if (mlac.is_local && mlac.is_lib) {
148                 mlac.act_new = BKE_action_copy(act);
149                 mlac.act_new->id.us = 0;
150
151                 BKE_id_lib_local_paths(bmain, act->id.lib, &mlac.act_new->id);
152
153                 BKE_animdata_main_cb(bmain, make_localact_apply_cb, &mlac);
154         }
155 }
156
157 /* .................................. */
158
159 void BKE_action_free(bAction *act)
160 {
161         /* sanity check */
162         if (act == NULL)
163                 return;
164         
165         /* Free F-Curves */
166         free_fcurves(&act->curves);
167         
168         /* Free groups */
169         if (act->groups.first)
170                 BLI_freelistN(&act->groups);
171                 
172         /* Free pose-references (aka local markers) */
173         if (act->markers.first)
174                 BLI_freelistN(&act->markers);
175 }
176
177 /* .................................. */
178
179 bAction *BKE_action_copy(bAction *src)
180 {
181         bAction *dst = NULL;
182         bActionGroup *dgrp, *sgrp;
183         FCurve *dfcu, *sfcu;
184         
185         if (src == NULL) 
186                 return NULL;
187         dst = BKE_libblock_copy(&src->id);
188         
189         /* duplicate the lists of groups and markers */
190         BLI_duplicatelist(&dst->groups, &src->groups);
191         BLI_duplicatelist(&dst->markers, &src->markers);
192         
193         /* copy F-Curves, fixing up the links as we go */
194         dst->curves.first = dst->curves.last = NULL;
195         
196         for (sfcu = src->curves.first; sfcu; sfcu = sfcu->next) {
197                 /* duplicate F-Curve */
198                 dfcu = copy_fcurve(sfcu);
199                 BLI_addtail(&dst->curves, dfcu);
200                 
201                 /* fix group links (kindof bad list-in-list search, but this is the most reliable way) */
202                 for (dgrp = dst->groups.first, sgrp = src->groups.first; dgrp && sgrp; dgrp = dgrp->next, sgrp = sgrp->next) {
203                         if (sfcu->grp == sgrp) {
204                                 dfcu->grp = dgrp;
205                                 
206                                 if (dgrp->channels.first == sfcu)
207                                         dgrp->channels.first = dfcu;
208                                 if (dgrp->channels.last == sfcu)
209                                         dgrp->channels.last = dfcu;
210                                         
211                                 break;
212                         }
213                 }
214         }
215         
216         return dst;
217 }
218
219 /* *************** Action Groups *************** */
220
221 /* Get the active action-group for an Action */
222 bActionGroup *get_active_actiongroup(bAction *act)
223 {
224         bActionGroup *agrp = NULL;
225         
226         if (act && act->groups.first) {
227                 for (agrp = act->groups.first; agrp; agrp = agrp->next) {
228                         if (agrp->flag & AGRP_ACTIVE)
229                                 break;
230                 }
231         }
232         
233         return agrp;
234 }
235
236 /* Make the given Action-Group the active one */
237 void set_active_action_group(bAction *act, bActionGroup *agrp, short select)
238 {
239         bActionGroup *grp;
240         
241         /* sanity checks */
242         if (act == NULL)
243                 return;
244         
245         /* Deactive all others */
246         for (grp = act->groups.first; grp; grp = grp->next) {
247                 if ((grp == agrp) && (select))
248                         grp->flag |= AGRP_ACTIVE;
249                 else
250                         grp->flag &= ~AGRP_ACTIVE;
251         }
252 }
253
254 /* Sync colors used for action/bone group with theme settings */
255 void action_group_colors_sync(bActionGroup *grp, const bActionGroup *ref_grp)
256 {
257         /* only do color copying if using a custom color (i.e. not default color)  */
258         if (grp->customCol) {
259                 if (grp->customCol > 0) {
260                         /* copy theme colors on-to group's custom color in case user tries to edit color */
261                         bTheme *btheme = U.themes.first;
262                         ThemeWireColor *col_set = &btheme->tarm[(grp->customCol - 1)];
263                         
264                         memcpy(&grp->cs, col_set, sizeof(ThemeWireColor));
265                 }
266                 else {
267                         /* if a reference group is provided, use the custom color from there... */
268                         if (ref_grp) {
269                                 /* assumption: reference group has a color set */
270                                 memcpy(&grp->cs, &ref_grp->cs, sizeof(ThemeWireColor));
271                         }
272                         /* otherwise, init custom color with a generic/placeholder color set if
273                          * no previous theme color was used that we can just keep using
274                          */
275                         else if (grp->cs.solid[0] == 0) {
276                                 /* define for setting colors in theme below */
277                                 rgba_char_args_set(grp->cs.solid, 0xff, 0x00, 0x00, 255);
278                                 rgba_char_args_set(grp->cs.select, 0x81, 0xe6, 0x14, 255);
279                                 rgba_char_args_set(grp->cs.active, 0x18, 0xb6, 0xe0, 255);
280                         }
281                 }
282         }
283 }
284
285 /* Add a new action group with the given name to the action */
286 bActionGroup *action_groups_add_new(bAction *act, const char name[])
287 {
288         bActionGroup *agrp;
289         
290         /* sanity check: must have action and name */
291         if (ELEM(NULL, act, name))
292                 return NULL;
293         
294         /* allocate a new one */
295         agrp = MEM_callocN(sizeof(bActionGroup), "bActionGroup");
296         
297         /* make it selected, with default name */
298         agrp->flag = AGRP_SELECTED;
299         BLI_strncpy(agrp->name, name[0] ? name : "Group", sizeof(agrp->name));
300         
301         /* add to action, and validate */
302         BLI_addtail(&act->groups, agrp);
303         BLI_uniquename(&act->groups, agrp, "Group", '.', offsetof(bActionGroup, name), sizeof(agrp->name));
304         
305         /* return the new group */
306         return agrp;
307 }
308
309 /* Add given channel into (active) group 
310  *      - assumes that channel is not linked to anything anymore
311  *      - always adds at the end of the group 
312  */
313 void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve)
314 {       
315         /* sanity checks */
316         if (ELEM3(NULL, act, agrp, fcurve))
317                 return;
318         
319         /* if no channels anywhere, just add to two lists at the same time */
320         if (act->curves.first == NULL) {
321                 fcurve->next = fcurve->prev = NULL;
322                 
323                 agrp->channels.first = agrp->channels.last = fcurve;
324                 act->curves.first = act->curves.last = fcurve;
325         }
326         
327         /* if the group already has channels, the F-Curve can simply be added to the list 
328          * (i.e. as the last channel in the group)
329          */
330         else if (agrp->channels.first) {
331                 /* if the group's last F-Curve is the action's last F-Curve too, 
332                  * then set the F-Curve as the last for the action first so that
333                  * the lists will be in sync after linking
334                  */
335                 if (agrp->channels.last == act->curves.last)
336                         act->curves.last = fcurve;
337                         
338                 /* link in the given F-Curve after the last F-Curve in the group,
339                  * which means that it should be able to fit in with the rest of the
340                  * list seamlessly
341                  */
342                 BLI_insertlinkafter(&agrp->channels, agrp->channels.last, fcurve);
343         }
344         
345         /* otherwise, need to find the nearest F-Curve in group before/after current to link with */
346         else {
347                 bActionGroup *grp;
348                 
349                 /* firstly, link this F-Curve to the group */
350                 agrp->channels.first = agrp->channels.last = fcurve;
351                 
352                 /* step through the groups preceding this one, finding the F-Curve there to attach this one after */
353                 for (grp = agrp->prev; grp; grp = grp->prev) {
354                         /* if this group has F-Curves, we want weave the given one in right after the last channel there,
355                          * but via the Action's list not this group's list
356                          *      - this is so that the F-Curve is in the right place in the Action,
357                          *        but won't be included in the previous group
358                          */
359                         if (grp->channels.last) {
360                                 /* once we've added, break here since we don't need to search any further... */
361                                 BLI_insertlinkafter(&act->curves, grp->channels.last, fcurve);
362                                 break;
363                         }
364                 }
365                 
366                 /* if grp is NULL, that means we fell through, and this F-Curve should be added as the new first
367                  * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the 
368                  * second in the chain, etc. etc.
369                  */
370                 if (grp == NULL)
371                         BLI_insertlinkbefore(&act->curves, act->curves.first, fcurve);
372         }
373         
374         /* set the F-Curve's new group */
375         fcurve->grp = agrp;
376 }       
377
378 /* Remove the given channel from all groups */
379 void action_groups_remove_channel(bAction *act, FCurve *fcu)
380 {
381         /* sanity checks */
382         if (ELEM(NULL, act, fcu))
383                 return;
384         
385         /* check if any group used this directly */
386         if (fcu->grp) {
387                 bActionGroup *agrp = fcu->grp;
388                 
389                 if (agrp->channels.first == agrp->channels.last) {
390                         if (agrp->channels.first == fcu) {
391                                 agrp->channels.first = NULL;
392                                 agrp->channels.last = NULL;
393                         }
394                 }
395                 else if (agrp->channels.first == fcu) {
396                         if ((fcu->next) && (fcu->next->grp == agrp))
397                                 agrp->channels.first = fcu->next;
398                         else
399                                 agrp->channels.first = NULL;
400                 }
401                 else if (agrp->channels.last == fcu) {
402                         if ((fcu->prev) && (fcu->prev->grp == agrp))
403                                 agrp->channels.last = fcu->prev;
404                         else
405                                 agrp->channels.last = NULL;
406                 }
407                 
408                 fcu->grp = NULL;
409         }
410         
411         /* now just remove from list */
412         BLI_remlink(&act->curves, fcu);
413 }
414
415 /* Find a group with the given name */
416 bActionGroup *BKE_action_group_find_name(bAction *act, const char name[])
417 {
418         /* sanity checks */
419         if (ELEM3(NULL, act, act->groups.first, name) || (name[0] == 0))
420                 return NULL;
421                 
422         /* do string comparisons */
423         return BLI_findstring(&act->groups, name, offsetof(bActionGroup, name));
424 }
425
426 /* Clear all 'temp' flags on all groups */
427 void action_groups_clear_tempflags(bAction *act)
428 {
429         bActionGroup *agrp;
430         
431         /* sanity checks */
432         if (ELEM(NULL, act, act->groups.first))
433                 return;
434                 
435         /* flag clearing loop */
436         for (agrp = act->groups.first; agrp; agrp = agrp->next)
437                 agrp->flag &= ~AGRP_TEMP;
438 }
439
440 /* *************** Pose channels *************** */
441
442 bPoseChannel *BKE_pose_channel_find_name(const bPose *pose, const char *name)
443 {
444         if (ELEM(NULL, pose, name) || (name[0] == '\0'))
445                 return NULL;
446         
447         if (pose->chanhash)
448                 return BLI_ghash_lookup(pose->chanhash, (void *)name);
449         
450         return BLI_findstring(&((bPose *)pose)->chanbase, name, offsetof(bPoseChannel, name));
451 }
452
453 /* Use with care, not on Armature poses but for temporal ones */
454 /* (currently used for action constraints and in rebuild_pose) */
455 bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name)
456 {
457         bPoseChannel *chan;
458         
459         if (pose == NULL)
460                 return NULL;
461         
462         /* See if this channel exists */
463         chan = BLI_findstring(&pose->chanbase, name, offsetof(bPoseChannel, name));
464         if (chan) {
465                 return chan;
466         }
467
468         /* If not, create it and add it */
469         chan = MEM_callocN(sizeof(bPoseChannel), "verifyPoseChannel");
470         
471         BLI_strncpy(chan->name, name, sizeof(chan->name));
472         /* init vars to prevent math errors */
473         unit_qt(chan->quat);
474         unit_axis_angle(chan->rotAxis, &chan->rotAngle);
475         chan->size[0] = chan->size[1] = chan->size[2] = 1.0f;
476         
477         chan->limitmin[0] = chan->limitmin[1] = chan->limitmin[2] = -180.0f;
478         chan->limitmax[0] = chan->limitmax[1] = chan->limitmax[2] = 180.0f;
479         chan->stiffness[0] = chan->stiffness[1] = chan->stiffness[2] = 0.0f;
480         chan->ikrotweight = chan->iklinweight = 0.0f;
481         unit_m4(chan->constinv);
482         
483         chan->protectflag = OB_LOCK_ROT4D;  /* lock by components by default */
484         
485         BLI_addtail(&pose->chanbase, chan);
486         BKE_pose_channels_hash_free(pose);
487         
488         return chan;
489 }
490
491 /* Find the active posechannel for an object (we can't just use pose, as layer info is in armature) */
492 bPoseChannel *BKE_pose_channel_active(Object *ob)
493 {
494         bArmature *arm = (ob) ? ob->data : NULL;
495         bPoseChannel *pchan;
496
497         if (ELEM3(NULL, ob, ob->pose, arm)) {
498                 return NULL;
499         }
500
501         /* find active */
502         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
503                 if ((pchan->bone) && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
504                         return pchan;
505         }
506         
507         return NULL;
508 }
509
510 const char *BKE_pose_ikparam_get_name(bPose *pose)
511 {
512         if (pose) {
513                 switch (pose->iksolver) {
514                         case IKSOLVER_STANDARD:
515                                 return NULL;
516                         case IKSOLVER_ITASC:
517                                 return "bItasc";
518                 }
519         }
520         return NULL;
521 }
522 /* dst should be freed already, makes entire duplicate */
523 void BKE_pose_copy_data(bPose **dst, bPose *src, int copycon)
524 {
525         bPose *outPose;
526         bPoseChannel *pchan;
527         ListBase listb;
528
529         if (!src) {
530                 *dst = NULL;
531                 return;
532         }
533         
534         outPose = MEM_callocN(sizeof(bPose), "pose");
535         
536         BLI_duplicatelist(&outPose->chanbase, &src->chanbase);
537         
538         outPose->iksolver = src->iksolver;
539         outPose->ikdata = NULL;
540         outPose->ikparam = MEM_dupallocN(src->ikparam);
541         outPose->avs = src->avs;
542         
543         for (pchan = outPose->chanbase.first; pchan; pchan = pchan->next) {
544                 /* TODO: rename this argument... */
545                 if (copycon) {
546                         BKE_copy_constraints(&listb, &pchan->constraints, TRUE);  // BKE_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_STANDARD:
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         BKE_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         BKE_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 = min_ff(min, nmin);
909                                 max = max_ff(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 = min_ff(min, fmd->rect.xmin);
928                                                 }
929                                                 if (fmd->flag & FCM_LIMIT_XMAX) {
930                                                         max = max_ff(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 bool BKE_pose_copy_result(bPose *to, bPose *from)
1122 {
1123         bPoseChannel *pchanto, *pchanfrom;
1124         
1125         if (to == NULL || from == NULL) {
1126                 printf("Pose copy error, pose to:%p from:%p\n", (void *)to, (void *)from); /* debug temp */
1127                 return false;
1128         }
1129
1130         if (to == from) {
1131                 printf("BKE_pose_copy_result source and target are the same\n");
1132                 return false;
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         return true;
1157 }
1158
1159 /* For the calculation of the effects of an Action at the given frame on an object 
1160  * This is currently only used for the Action Constraint 
1161  */
1162 void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, char groupname[], float cframe)
1163 {
1164         bActionGroup *agrp = BKE_action_group_find_name(act, groupname);
1165         
1166         /* clear workob */
1167         BKE_object_workob_clear(workob);
1168         
1169         /* init workob */
1170         copy_m4_m4(workob->obmat, ob->obmat);
1171         copy_m4_m4(workob->parentinv, ob->parentinv);
1172         copy_m4_m4(workob->constinv, ob->constinv);
1173         workob->parent = ob->parent;
1174         
1175         workob->rotmode = ob->rotmode;
1176         
1177         workob->trackflag = ob->trackflag;
1178         workob->upflag = ob->upflag;
1179         
1180         workob->partype = ob->partype;
1181         workob->par1 = ob->par1;
1182         workob->par2 = ob->par2;
1183         workob->par3 = ob->par3;
1184
1185         workob->constraints.first = ob->constraints.first;
1186         workob->constraints.last = ob->constraints.last;
1187         
1188         workob->pose = pose; /* need to set pose too, since this is used for both types of Action Constraint */
1189
1190         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
1191         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 */
1192         
1193         /* if we're given a group to use, it's likely to be more efficient (though a bit more dangerous) */
1194         if (agrp) {
1195                 /* specifically evaluate this group only */
1196                 PointerRNA id_ptr;
1197                 
1198                 /* get RNA-pointer for the workob's ID */
1199                 RNA_id_pointer_create(&workob->id, &id_ptr);
1200                 
1201                 /* execute action for this group only */
1202                 animsys_evaluate_action_group(&id_ptr, act, agrp, NULL, cframe);
1203         }
1204         else {
1205                 AnimData adt = {NULL};
1206                 
1207                 /* init animdata, and attach to workob */
1208                 workob->adt = &adt;
1209                 
1210                 adt.recalc = ADT_RECALC_ANIM;
1211                 adt.action = act;
1212                 
1213                 /* execute effects of Action on to workob (or it's PoseChannels) */
1214                 BKE_animsys_evaluate_animdata(NULL, &workob->id, &adt, cframe, ADT_RECALC_ANIM);
1215         }
1216 }
1217