1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup bke
22  */
23 
24 #include <ctype.h>
25 #include <float.h>
26 #include <math.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 
31 #include "MEM_guardedalloc.h"
32 
33 #include "BLI_alloca.h"
34 #include "BLI_ghash.h"
35 #include "BLI_listbase.h"
36 #include "BLI_math.h"
37 #include "BLI_string.h"
38 #include "BLI_utildefines.h"
39 #include "BLT_translation.h"
40 
41 #include "DNA_defaults.h"
42 
43 #include "DNA_armature_types.h"
44 #include "DNA_constraint_types.h"
45 #include "DNA_listBase.h"
46 #include "DNA_object_types.h"
47 #include "DNA_scene_types.h"
48 
49 #include "BKE_action.h"
50 #include "BKE_anim_data.h"
51 #include "BKE_anim_visualization.h"
52 #include "BKE_armature.h"
53 #include "BKE_constraint.h"
54 #include "BKE_curve.h"
55 #include "BKE_idprop.h"
56 #include "BKE_idtype.h"
57 #include "BKE_lib_id.h"
58 #include "BKE_lib_query.h"
59 #include "BKE_main.h"
60 #include "BKE_object.h"
61 #include "BKE_scene.h"
62 
63 #include "DEG_depsgraph_build.h"
64 #include "DEG_depsgraph_query.h"
65 
66 #include "BIK_api.h"
67 
68 #include "BLO_read_write.h"
69 
70 #include "CLG_log.h"
71 
72 static CLG_LogRef LOG = {"bke.armature"};
73 
74 /* -------------------------------------------------------------------- */
75 /** \name Prototypes
76  * \{ */
77 
78 static void copy_bonechildren(Bone *bone_dst,
79                               const Bone *bone_src,
80                               const Bone *bone_src_act,
81                               Bone **r_bone_dst_act,
82                               const int flag);
83 
84 static void copy_bonechildren_custom_handles(Bone *bone_dst, bArmature *arm_dst);
85 
86 /** \} */
87 
88 /* -------------------------------------------------------------------- */
89 /** \name Armature Data-block
90  * \{ */
91 
armature_init_data(ID * id)92 static void armature_init_data(ID *id)
93 {
94   bArmature *armature = (bArmature *)id;
95   BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(armature, id));
96 
97   MEMCPY_STRUCT_AFTER(armature, DNA_struct_default_get(bArmature), id);
98 }
99 
100 /**
101  * Only copy internal data of Armature ID from source
102  * to already allocated/initialized destination.
103  * You probably never want to use that directly,
104  * use #BKE_id_copy or #BKE_id_copy_ex for typical needs.
105  *
106  * WARNING! This function will not handle ID user count!
107  *
108  * \param flag: Copying options (see BKE_lib_id.h's LIB_ID_COPY_... flags for more).
109  */
armature_copy_data(Main * UNUSED (bmain),ID * id_dst,const ID * id_src,const int flag)110 static void armature_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, const int flag)
111 {
112   bArmature *armature_dst = (bArmature *)id_dst;
113   const bArmature *armature_src = (const bArmature *)id_src;
114 
115   Bone *bone_src, *bone_dst;
116   Bone *bone_dst_act = NULL;
117 
118   /* We never handle usercount here for own data. */
119   const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
120 
121   armature_dst->bonehash = NULL;
122 
123   BLI_duplicatelist(&armature_dst->bonebase, &armature_src->bonebase);
124 
125   /* Duplicate the childrens' lists */
126   bone_dst = armature_dst->bonebase.first;
127   for (bone_src = armature_src->bonebase.first; bone_src; bone_src = bone_src->next) {
128     bone_dst->parent = NULL;
129     copy_bonechildren(bone_dst, bone_src, armature_src->act_bone, &bone_dst_act, flag_subdata);
130     bone_dst = bone_dst->next;
131   }
132 
133   armature_dst->act_bone = bone_dst_act;
134 
135   BKE_armature_bone_hash_make(armature_dst);
136 
137   /* Fix custom handle references. */
138   for (bone_dst = armature_dst->bonebase.first; bone_dst; bone_dst = bone_dst->next) {
139     copy_bonechildren_custom_handles(bone_dst, armature_dst);
140   }
141 
142   armature_dst->edbo = NULL;
143   armature_dst->act_edbone = NULL;
144 }
145 
146 /** Free (or release) any data used by this armature (does not free the armature itself). */
armature_free_data(struct ID * id)147 static void armature_free_data(struct ID *id)
148 {
149   bArmature *armature = (bArmature *)id;
150 
151   BKE_armature_bone_hash_free(armature);
152   BKE_armature_bonelist_free(&armature->bonebase, false);
153 
154   /* free editmode data */
155   if (armature->edbo) {
156     BKE_armature_editbonelist_free(armature->edbo, false);
157     MEM_freeN(armature->edbo);
158     armature->edbo = NULL;
159   }
160 }
161 
armature_foreach_id_bone(Bone * bone,LibraryForeachIDData * data)162 static void armature_foreach_id_bone(Bone *bone, LibraryForeachIDData *data)
163 {
164   IDP_foreach_property(
165       bone->prop, IDP_TYPE_FILTER_ID, BKE_lib_query_idpropertiesForeachIDLink_callback, data);
166 
167   LISTBASE_FOREACH (Bone *, curbone, &bone->childbase) {
168     armature_foreach_id_bone(curbone, data);
169   }
170 }
171 
armature_foreach_id_editbone(EditBone * edit_bone,LibraryForeachIDData * data)172 static void armature_foreach_id_editbone(EditBone *edit_bone, LibraryForeachIDData *data)
173 {
174   IDP_foreach_property(
175       edit_bone->prop, IDP_TYPE_FILTER_ID, BKE_lib_query_idpropertiesForeachIDLink_callback, data);
176 }
177 
armature_foreach_id(ID * id,LibraryForeachIDData * data)178 static void armature_foreach_id(ID *id, LibraryForeachIDData *data)
179 {
180   bArmature *arm = (bArmature *)id;
181   LISTBASE_FOREACH (Bone *, bone, &arm->bonebase) {
182     armature_foreach_id_bone(bone, data);
183   }
184 
185   if (arm->edbo != NULL) {
186     LISTBASE_FOREACH (EditBone *, edit_bone, arm->edbo) {
187       armature_foreach_id_editbone(edit_bone, data);
188     }
189   }
190 }
191 
write_bone(BlendWriter * writer,Bone * bone)192 static void write_bone(BlendWriter *writer, Bone *bone)
193 {
194   /* PATCH for upward compatibility after 2.37+ armature recode */
195   bone->size[0] = bone->size[1] = bone->size[2] = 1.0f;
196 
197   /* Write this bone */
198   BLO_write_struct(writer, Bone, bone);
199 
200   /* Write ID Properties -- and copy this comment EXACTLY for easy finding
201    * of library blocks that implement this.*/
202   if (bone->prop) {
203     IDP_BlendWrite(writer, bone->prop);
204   }
205 
206   /* Write Children */
207   LISTBASE_FOREACH (Bone *, cbone, &bone->childbase) {
208     write_bone(writer, cbone);
209   }
210 }
211 
armature_blend_write(BlendWriter * writer,ID * id,const void * id_address)212 static void armature_blend_write(BlendWriter *writer, ID *id, const void *id_address)
213 {
214   bArmature *arm = (bArmature *)id;
215   if (arm->id.us > 0 || BLO_write_is_undo(writer)) {
216     /* Clean up, important in undo case to reduce false detection of changed datablocks. */
217     arm->bonehash = NULL;
218     arm->edbo = NULL;
219     /* Must always be cleared (armatures don't have their own edit-data). */
220     arm->needs_flush_to_id = 0;
221     arm->act_edbone = NULL;
222 
223     BLO_write_id_struct(writer, bArmature, id_address, &arm->id);
224     BKE_id_blend_write(writer, &arm->id);
225 
226     if (arm->adt) {
227       BKE_animdata_blend_write(writer, arm->adt);
228     }
229 
230     /* Direct data */
231     LISTBASE_FOREACH (Bone *, bone, &arm->bonebase) {
232       write_bone(writer, bone);
233     }
234   }
235 }
236 
direct_link_bones(BlendDataReader * reader,Bone * bone)237 static void direct_link_bones(BlendDataReader *reader, Bone *bone)
238 {
239   BLO_read_data_address(reader, &bone->parent);
240   BLO_read_data_address(reader, &bone->prop);
241   IDP_BlendDataRead(reader, &bone->prop);
242 
243   BLO_read_data_address(reader, &bone->bbone_next);
244   BLO_read_data_address(reader, &bone->bbone_prev);
245 
246   bone->flag &= ~(BONE_DRAW_ACTIVE | BONE_DRAW_LOCKED_WEIGHT);
247 
248   BLO_read_list(reader, &bone->childbase);
249 
250   LISTBASE_FOREACH (Bone *, child, &bone->childbase) {
251     direct_link_bones(reader, child);
252   }
253 }
254 
armature_blend_read_data(BlendDataReader * reader,ID * id)255 static void armature_blend_read_data(BlendDataReader *reader, ID *id)
256 {
257   bArmature *arm = (bArmature *)id;
258   BLO_read_list(reader, &arm->bonebase);
259   arm->bonehash = NULL;
260   arm->edbo = NULL;
261   /* Must always be cleared (armatures don't have their own edit-data). */
262   arm->needs_flush_to_id = 0;
263 
264   BLO_read_data_address(reader, &arm->adt);
265   BKE_animdata_blend_read_data(reader, arm->adt);
266 
267   LISTBASE_FOREACH (Bone *, bone, &arm->bonebase) {
268     direct_link_bones(reader, bone);
269   }
270 
271   BLO_read_data_address(reader, &arm->act_bone);
272   arm->act_edbone = NULL;
273 
274   BKE_armature_bone_hash_make(arm);
275 }
276 
lib_link_bones(BlendLibReader * reader,Bone * bone)277 static void lib_link_bones(BlendLibReader *reader, Bone *bone)
278 {
279   IDP_BlendReadLib(reader, bone->prop);
280 
281   LISTBASE_FOREACH (Bone *, curbone, &bone->childbase) {
282     lib_link_bones(reader, curbone);
283   }
284 }
285 
armature_blend_read_lib(BlendLibReader * reader,ID * id)286 static void armature_blend_read_lib(BlendLibReader *reader, ID *id)
287 {
288   bArmature *arm = (bArmature *)id;
289   LISTBASE_FOREACH (Bone *, curbone, &arm->bonebase) {
290     lib_link_bones(reader, curbone);
291   }
292 }
293 
expand_bones(BlendExpander * expander,Bone * bone)294 static void expand_bones(BlendExpander *expander, Bone *bone)
295 {
296   IDP_BlendReadExpand(expander, bone->prop);
297 
298   LISTBASE_FOREACH (Bone *, curBone, &bone->childbase) {
299     expand_bones(expander, curBone);
300   }
301 }
302 
armature_blend_read_expand(BlendExpander * expander,ID * id)303 static void armature_blend_read_expand(BlendExpander *expander, ID *id)
304 {
305   bArmature *arm = (bArmature *)id;
306   LISTBASE_FOREACH (Bone *, curBone, &arm->bonebase) {
307     expand_bones(expander, curBone);
308   }
309 }
310 
311 IDTypeInfo IDType_ID_AR = {
312     .id_code = ID_AR,
313     .id_filter = FILTER_ID_AR,
314     .main_listbase_index = INDEX_ID_AR,
315     .struct_size = sizeof(bArmature),
316     .name = "Armature",
317     .name_plural = "armatures",
318     .translation_context = BLT_I18NCONTEXT_ID_ARMATURE,
319     .flags = 0,
320 
321     .init_data = armature_init_data,
322     .copy_data = armature_copy_data,
323     .free_data = armature_free_data,
324     .make_local = NULL,
325     .foreach_id = armature_foreach_id,
326     .foreach_cache = NULL,
327 
328     .blend_write = armature_blend_write,
329     .blend_read_data = armature_blend_read_data,
330     .blend_read_lib = armature_blend_read_lib,
331     .blend_read_expand = armature_blend_read_expand,
332 };
333 
334 /** \} */
335 
336 /* -------------------------------------------------------------------- */
337 /** \name Generic Data-Level Functions
338  * \{ */
339 
BKE_armature_add(Main * bmain,const char * name)340 bArmature *BKE_armature_add(Main *bmain, const char *name)
341 {
342   bArmature *arm;
343 
344   arm = BKE_id_new(bmain, ID_AR, name);
345   return arm;
346 }
347 
BKE_armature_from_object(Object * ob)348 bArmature *BKE_armature_from_object(Object *ob)
349 {
350   if (ob->type == OB_ARMATURE) {
351     return (bArmature *)ob->data;
352   }
353   return NULL;
354 }
355 
BKE_armature_bonelist_count(ListBase * lb)356 int BKE_armature_bonelist_count(ListBase *lb)
357 {
358   int i = 0;
359   LISTBASE_FOREACH (Bone *, bone, lb) {
360     i += 1 + BKE_armature_bonelist_count(&bone->childbase);
361   }
362 
363   return i;
364 }
365 
BKE_armature_bonelist_free(ListBase * lb,const bool do_id_user)366 void BKE_armature_bonelist_free(ListBase *lb, const bool do_id_user)
367 {
368   Bone *bone;
369 
370   for (bone = lb->first; bone; bone = bone->next) {
371     if (bone->prop) {
372       IDP_FreeProperty_ex(bone->prop, do_id_user);
373     }
374     BKE_armature_bonelist_free(&bone->childbase, do_id_user);
375   }
376 
377   BLI_freelistN(lb);
378 }
379 
BKE_armature_editbonelist_free(ListBase * lb,const bool do_id_user)380 void BKE_armature_editbonelist_free(ListBase *lb, const bool do_id_user)
381 {
382   LISTBASE_FOREACH_MUTABLE (EditBone *, edit_bone, lb) {
383     if (edit_bone->prop) {
384       IDP_FreeProperty_ex(edit_bone->prop, do_id_user);
385     }
386     BLI_remlink_safe(lb, edit_bone);
387     MEM_freeN(edit_bone);
388   }
389 }
390 
copy_bonechildren(Bone * bone_dst,const Bone * bone_src,const Bone * bone_src_act,Bone ** r_bone_dst_act,const int flag)391 static void copy_bonechildren(Bone *bone_dst,
392                               const Bone *bone_src,
393                               const Bone *bone_src_act,
394                               Bone **r_bone_dst_act,
395                               const int flag)
396 {
397   Bone *bone_src_child, *bone_dst_child;
398 
399   if (bone_src == bone_src_act) {
400     *r_bone_dst_act = bone_dst;
401   }
402 
403   if (bone_src->prop) {
404     bone_dst->prop = IDP_CopyProperty_ex(bone_src->prop, flag);
405   }
406 
407   /* Copy this bone's list */
408   BLI_duplicatelist(&bone_dst->childbase, &bone_src->childbase);
409 
410   /* For each child in the list, update its children */
411   for (bone_src_child = bone_src->childbase.first, bone_dst_child = bone_dst->childbase.first;
412        bone_src_child;
413        bone_src_child = bone_src_child->next, bone_dst_child = bone_dst_child->next) {
414     bone_dst_child->parent = bone_dst;
415     copy_bonechildren(bone_dst_child, bone_src_child, bone_src_act, r_bone_dst_act, flag);
416   }
417 }
418 
copy_bonechildren_custom_handles(Bone * bone_dst,bArmature * arm_dst)419 static void copy_bonechildren_custom_handles(Bone *bone_dst, bArmature *arm_dst)
420 {
421   Bone *bone_dst_child;
422 
423   if (bone_dst->bbone_prev) {
424     bone_dst->bbone_prev = BKE_armature_find_bone_name(arm_dst, bone_dst->bbone_prev->name);
425   }
426   if (bone_dst->bbone_next) {
427     bone_dst->bbone_next = BKE_armature_find_bone_name(arm_dst, bone_dst->bbone_next->name);
428   }
429 
430   for (bone_dst_child = bone_dst->childbase.first; bone_dst_child;
431        bone_dst_child = bone_dst_child->next) {
432     copy_bonechildren_custom_handles(bone_dst_child, arm_dst);
433   }
434 }
435 
436 /** \} */
437 
438 /* -------------------------------------------------------------------- */
439 /** \name Armature Transform Copy
440  * \{ */
441 
copy_bone_transform(Bone * bone_dst,const Bone * bone_src)442 static void copy_bone_transform(Bone *bone_dst, const Bone *bone_src)
443 {
444   bone_dst->roll = bone_src->roll;
445 
446   copy_v3_v3(bone_dst->head, bone_src->head);
447   copy_v3_v3(bone_dst->tail, bone_src->tail);
448 
449   copy_m3_m3(bone_dst->bone_mat, bone_src->bone_mat);
450 
451   copy_v3_v3(bone_dst->arm_head, bone_src->arm_head);
452   copy_v3_v3(bone_dst->arm_tail, bone_src->arm_tail);
453 
454   copy_m4_m4(bone_dst->arm_mat, bone_src->arm_mat);
455 
456   bone_dst->arm_roll = bone_src->arm_roll;
457 }
458 
BKE_armature_copy_bone_transforms(bArmature * armature_dst,const bArmature * armature_src)459 void BKE_armature_copy_bone_transforms(bArmature *armature_dst, const bArmature *armature_src)
460 {
461   Bone *bone_dst = armature_dst->bonebase.first;
462   const Bone *bone_src = armature_src->bonebase.first;
463   while (bone_dst != NULL) {
464     BLI_assert(bone_src != NULL);
465     copy_bone_transform(bone_dst, bone_src);
466     bone_dst = bone_dst->next;
467     bone_src = bone_src->next;
468   }
469 }
470 
471 /** \} */
472 
473 /* -------------------------------------------------------------------- */
474 /** \name Armature Transform by 4x4 Matrix
475  *
476  * \see #ED_armature_edit_transform for the edit-mode version of this function.
477  * \{ */
478 
479 /** Helper for #ED_armature_transform */
armature_transform_recurse(ListBase * bonebase,const float mat[4][4],const bool do_props,const float mat3[3][3],const float scale,const Bone * bone_parent,const float arm_mat_parent_inv[4][4])480 static void armature_transform_recurse(ListBase *bonebase,
481                                        const float mat[4][4],
482                                        const bool do_props,
483                                        /* Cached from 'mat'. */
484                                        const float mat3[3][3],
485                                        const float scale,
486                                        /* Child bones. */
487                                        const Bone *bone_parent,
488                                        const float arm_mat_parent_inv[4][4])
489 {
490   LISTBASE_FOREACH (Bone *, bone, bonebase) {
491 
492     /* Store the initial bone roll in a matrix, this is needed even for child bones
493      * so any change in head/tail doesn't cause the roll to change.
494      *
495      * Logic here is different to edit-mode because
496      * this is calculated in relative to the parent. */
497     float roll_mat3_pre[3][3];
498     {
499       float delta[3];
500       sub_v3_v3v3(delta, bone->tail, bone->head);
501       vec_roll_to_mat3(delta, bone->roll, roll_mat3_pre);
502       if (bone->parent == NULL) {
503         mul_m3_m3m3(roll_mat3_pre, mat3, roll_mat3_pre);
504       }
505     }
506     /* Optional, use this for predictable results since the roll is re-calculated below anyway. */
507     bone->roll = 0.0f;
508 
509     mul_m4_v3(mat, bone->arm_head);
510     mul_m4_v3(mat, bone->arm_tail);
511 
512     /* Get the new head and tail */
513     if (bone_parent) {
514       sub_v3_v3v3(bone->head, bone->arm_head, bone_parent->arm_tail);
515       sub_v3_v3v3(bone->tail, bone->arm_tail, bone_parent->arm_tail);
516 
517       mul_mat3_m4_v3(arm_mat_parent_inv, bone->head);
518       mul_mat3_m4_v3(arm_mat_parent_inv, bone->tail);
519     }
520     else {
521       copy_v3_v3(bone->head, bone->arm_head);
522       copy_v3_v3(bone->tail, bone->arm_tail);
523     }
524 
525     /* Now the head/tail have been updated, set the roll back, matching 'roll_mat3_pre'. */
526     {
527       float roll_mat3_post[3][3], delta_mat3[3][3];
528       float delta[3];
529       sub_v3_v3v3(delta, bone->tail, bone->head);
530       vec_roll_to_mat3(delta, 0.0f, roll_mat3_post);
531       invert_m3(roll_mat3_post);
532       mul_m3_m3m3(delta_mat3, roll_mat3_post, roll_mat3_pre);
533       bone->roll = atan2f(delta_mat3[2][0], delta_mat3[2][2]);
534     }
535 
536     BKE_armature_where_is_bone(bone, bone_parent, false);
537 
538     {
539       float arm_mat3[3][3];
540       copy_m3_m4(arm_mat3, bone->arm_mat);
541       mat3_to_vec_roll(arm_mat3, NULL, &bone->arm_roll);
542     }
543 
544     if (do_props) {
545       bone->rad_head *= scale;
546       bone->rad_tail *= scale;
547       bone->dist *= scale;
548 
549       /* we could be smarter and scale by the matrix along the x & z axis */
550       bone->xwidth *= scale;
551       bone->zwidth *= scale;
552     }
553 
554     if (!BLI_listbase_is_empty(&bone->childbase)) {
555       float arm_mat_inv[4][4];
556       invert_m4_m4(arm_mat_inv, bone->arm_mat);
557       armature_transform_recurse(&bone->childbase, mat, do_props, mat3, scale, bone, arm_mat_inv);
558     }
559   }
560 }
561 
BKE_armature_transform(bArmature * arm,const float mat[4][4],const bool do_props)562 void BKE_armature_transform(bArmature *arm, const float mat[4][4], const bool do_props)
563 {
564   /* Store the scale of the matrix here to use on envelopes. */
565   float scale = mat4_to_scale(mat);
566   float mat3[3][3];
567 
568   copy_m3_m4(mat3, mat);
569   normalize_m3(mat3);
570 
571   armature_transform_recurse(&arm->bonebase, mat, do_props, mat3, scale, NULL, NULL);
572 }
573 
574 /** \} */
575 
576 /* -------------------------------------------------------------------- */
577 /** \name Armature Bone Find by Name
578  *
579  * Using fast #GHash look-ups when available.
580  * \{ */
581 
get_named_bone_bonechildren(ListBase * lb,const char * name)582 static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name)
583 {
584   Bone *curBone, *rbone;
585 
586   for (curBone = lb->first; curBone; curBone = curBone->next) {
587     if (STREQ(curBone->name, name)) {
588       return curBone;
589     }
590 
591     rbone = get_named_bone_bonechildren(&curBone->childbase, name);
592     if (rbone) {
593       return rbone;
594     }
595   }
596 
597   return NULL;
598 }
599 
600 /**
601  * Walk the list until the bone is found (slow!),
602  * use #BKE_armature_bone_from_name_map for multiple lookups.
603  */
BKE_armature_find_bone_name(bArmature * arm,const char * name)604 Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name)
605 {
606   if (!arm) {
607     return NULL;
608   }
609 
610   if (arm->bonehash) {
611     return BLI_ghash_lookup(arm->bonehash, name);
612   }
613 
614   return get_named_bone_bonechildren(&arm->bonebase, name);
615 }
616 
armature_bone_from_name_insert_recursive(GHash * bone_hash,ListBase * lb)617 static void armature_bone_from_name_insert_recursive(GHash *bone_hash, ListBase *lb)
618 {
619   LISTBASE_FOREACH (Bone *, bone, lb) {
620     BLI_ghash_insert(bone_hash, bone->name, bone);
621     armature_bone_from_name_insert_recursive(bone_hash, &bone->childbase);
622   }
623 }
624 
625 /**
626  * Create a (name -> bone) map.
627  *
628  * \note typically #bPose.chanhash us used via #BKE_pose_channel_find_name
629  * this is for the cases we can't use pose channels.
630  */
armature_bone_from_name_map(bArmature * arm)631 static GHash *armature_bone_from_name_map(bArmature *arm)
632 {
633   const int bones_count = BKE_armature_bonelist_count(&arm->bonebase);
634   GHash *bone_hash = BLI_ghash_str_new_ex(__func__, bones_count);
635   armature_bone_from_name_insert_recursive(bone_hash, &arm->bonebase);
636   return bone_hash;
637 }
638 
BKE_armature_bone_hash_make(bArmature * arm)639 void BKE_armature_bone_hash_make(bArmature *arm)
640 {
641   if (!arm->bonehash) {
642     arm->bonehash = armature_bone_from_name_map(arm);
643   }
644 }
645 
BKE_armature_bone_hash_free(bArmature * arm)646 void BKE_armature_bone_hash_free(bArmature *arm)
647 {
648   if (arm->bonehash) {
649     BLI_ghash_free(arm->bonehash, NULL, NULL);
650     arm->bonehash = NULL;
651   }
652 }
653 
654 /** \} */
655 
656 /* -------------------------------------------------------------------- */
657 /** \name Armature Bone Flags
658  * \{ */
659 
BKE_armature_bone_flag_test_recursive(const Bone * bone,int flag)660 bool BKE_armature_bone_flag_test_recursive(const Bone *bone, int flag)
661 {
662   if (bone->flag & flag) {
663     return true;
664   }
665   if (bone->parent) {
666     return BKE_armature_bone_flag_test_recursive(bone->parent, flag);
667   }
668   return false;
669 }
670 
671 /** \} */
672 
673 /* -------------------------------------------------------------------- */
674 /** \name Armature Layer Refresh Used
675  * \{ */
676 
armature_refresh_layer_used_recursive(bArmature * arm,ListBase * bones)677 static void armature_refresh_layer_used_recursive(bArmature *arm, ListBase *bones)
678 {
679   LISTBASE_FOREACH (Bone *, bone, bones) {
680     arm->layer_used |= bone->layer;
681     armature_refresh_layer_used_recursive(arm, &bone->childbase);
682   }
683 }
684 
BKE_armature_refresh_layer_used(struct Depsgraph * depsgraph,struct bArmature * arm)685 void BKE_armature_refresh_layer_used(struct Depsgraph *depsgraph, struct bArmature *arm)
686 {
687   if (arm->edbo != NULL) {
688     /* Don't perform this update when the armature is in edit mode. In that case it should be
689      * handled by ED_armature_edit_refresh_layer_used(). */
690     return;
691   }
692 
693   arm->layer_used = 0;
694   armature_refresh_layer_used_recursive(arm, &arm->bonebase);
695 
696   if (depsgraph == NULL || DEG_is_active(depsgraph)) {
697     bArmature *arm_orig = (bArmature *)DEG_get_original_id(&arm->id);
698     arm_orig->layer_used = arm->layer_used;
699   }
700 }
701 
702 /** \} */
703 
704 /* -------------------------------------------------------------------- */
705 /** \name Armature Layer Refresh Used
706  * \{ */
707 
708 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for
709  * unique names afterwards) strip_number: removes number extensions  (TODO: not used)
710  * axis: the axis to name on
711  * head/tail: the head/tail co-ordinate of the bone on the specified axis */
bone_autoside_name(char name[MAXBONENAME],int UNUSED (strip_number),short axis,float head,float tail)712 bool bone_autoside_name(
713     char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
714 {
715   unsigned int len;
716   char basename[MAXBONENAME] = "";
717   char extension[5] = "";
718 
719   len = strlen(name);
720   if (len == 0) {
721     return false;
722   }
723   BLI_strncpy(basename, name, sizeof(basename));
724 
725   /* Figure out extension to append:
726    * - The extension to append is based upon the axis that we are working on.
727    * - If head happens to be on 0, then we must consider the tail position as well to decide
728    *   which side the bone is on
729    *   -> If tail is 0, then its bone is considered to be on axis, so no extension should be added
730    *   -> Otherwise, extension is added from perspective of object based on which side tail goes to
731    * - If head is non-zero, extension is added from perspective of object based on side head is on
732    */
733   if (axis == 2) {
734     /* z-axis - vertical (top/bottom) */
735     if (IS_EQF(head, 0.0f)) {
736       if (tail < 0) {
737         strcpy(extension, "Bot");
738       }
739       else if (tail > 0) {
740         strcpy(extension, "Top");
741       }
742     }
743     else {
744       if (head < 0) {
745         strcpy(extension, "Bot");
746       }
747       else {
748         strcpy(extension, "Top");
749       }
750     }
751   }
752   else if (axis == 1) {
753     /* y-axis - depth (front/back) */
754     if (IS_EQF(head, 0.0f)) {
755       if (tail < 0) {
756         strcpy(extension, "Fr");
757       }
758       else if (tail > 0) {
759         strcpy(extension, "Bk");
760       }
761     }
762     else {
763       if (head < 0) {
764         strcpy(extension, "Fr");
765       }
766       else {
767         strcpy(extension, "Bk");
768       }
769     }
770   }
771   else {
772     /* x-axis - horizontal (left/right) */
773     if (IS_EQF(head, 0.0f)) {
774       if (tail < 0) {
775         strcpy(extension, "R");
776       }
777       else if (tail > 0) {
778         strcpy(extension, "L");
779       }
780     }
781     else {
782       if (head < 0) {
783         strcpy(extension, "R");
784         /* XXX Shouldn't this be simple else, as for z and y axes? */
785       }
786       else if (head > 0) {
787         strcpy(extension, "L");
788       }
789     }
790   }
791 
792   /* Simple name truncation
793    * - truncate if there is an extension and it wouldn't be able to fit
794    * - otherwise, just append to end
795    */
796   if (extension[0]) {
797     bool changed = true;
798 
799     while (changed) { /* remove extensions */
800       changed = false;
801       if (len > 2 && basename[len - 2] == '.') {
802         if (basename[len - 1] == 'L' || basename[len - 1] == 'R') { /* L R */
803           basename[len - 2] = '\0';
804           len -= 2;
805           changed = true;
806         }
807       }
808       else if (len > 3 && basename[len - 3] == '.') {
809         if ((basename[len - 2] == 'F' && basename[len - 1] == 'r') || /* Fr */
810             (basename[len - 2] == 'B' && basename[len - 1] == 'k'))   /* Bk */
811         {
812           basename[len - 3] = '\0';
813           len -= 3;
814           changed = true;
815         }
816       }
817       else if (len > 4 && basename[len - 4] == '.') {
818         if ((basename[len - 3] == 'T' && basename[len - 2] == 'o' &&
819              basename[len - 1] == 'p') || /* Top */
820             (basename[len - 3] == 'B' && basename[len - 2] == 'o' &&
821              basename[len - 1] == 't')) /* Bot */
822         {
823           basename[len - 4] = '\0';
824           len -= 4;
825           changed = true;
826         }
827       }
828     }
829 
830     if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
831       strncpy(name, basename, len - strlen(extension));
832     }
833 
834     BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
835 
836     return true;
837   }
838   return false;
839 }
840 
841 /** \} */
842 
843 /* -------------------------------------------------------------------- */
844 /** \name Armature B-Bone Support
845  * \{ */
846 
847 /* Compute a set of bezier parameter values that produce approximately equally spaced points. */
equalize_cubic_bezier(const float control[4][3],int temp_segments,int final_segments,float * r_t_points)848 static void equalize_cubic_bezier(const float control[4][3],
849                                   int temp_segments,
850                                   int final_segments,
851                                   float *r_t_points)
852 {
853   float(*coords)[3] = BLI_array_alloca(coords, temp_segments + 1);
854   float *pdist = BLI_array_alloca(pdist, temp_segments + 1);
855 
856   /* Compute the first pass of bezier point coordinates. */
857   for (int i = 0; i < 3; i++) {
858     BKE_curve_forward_diff_bezier(control[0][i],
859                                   control[1][i],
860                                   control[2][i],
861                                   control[3][i],
862                                   &coords[0][i],
863                                   temp_segments,
864                                   sizeof(*coords));
865   }
866 
867   /* Calculate the length of the polyline at each point. */
868   pdist[0] = 0.0f;
869 
870   for (int i = 0; i < temp_segments; i++) {
871     pdist[i + 1] = pdist[i] + len_v3v3(coords[i], coords[i + 1]);
872   }
873 
874   /* Go over distances and calculate new parameter values. */
875   float dist_step = pdist[temp_segments] / final_segments;
876 
877   r_t_points[0] = 0.0f;
878 
879   for (int i = 1, nr = 1; i <= final_segments; i++) {
880     float dist = i * dist_step;
881 
882     /* We're looking for location (distance) 'dist' in the array. */
883     while ((nr < temp_segments) && (dist >= pdist[nr])) {
884       nr++;
885     }
886 
887     float fac = (pdist[nr] - dist) / (pdist[nr] - pdist[nr - 1]);
888 
889     r_t_points[i] = (nr - fac) / temp_segments;
890   }
891 
892   r_t_points[final_segments] = 1.0f;
893 }
894 
895 /* Evaluate bezier position and tangent at a specific parameter value
896  * using the De Casteljau algorithm. */
evaluate_cubic_bezier(const float control[4][3],float t,float r_pos[3],float r_tangent[3])897 static void evaluate_cubic_bezier(const float control[4][3],
898                                   float t,
899                                   float r_pos[3],
900                                   float r_tangent[3])
901 {
902   float layer1[3][3];
903   interp_v3_v3v3(layer1[0], control[0], control[1], t);
904   interp_v3_v3v3(layer1[1], control[1], control[2], t);
905   interp_v3_v3v3(layer1[2], control[2], control[3], t);
906 
907   float layer2[2][3];
908   interp_v3_v3v3(layer2[0], layer1[0], layer1[1], t);
909   interp_v3_v3v3(layer2[1], layer1[1], layer1[2], t);
910 
911   sub_v3_v3v3(r_tangent, layer2[1], layer2[0]);
912   madd_v3_v3v3fl(r_pos, layer2[0], r_tangent, t);
913 }
914 
915 /* Get "next" and "prev" bones - these are used for handle calculations. */
BKE_pchan_bbone_handles_get(bPoseChannel * pchan,bPoseChannel ** r_prev,bPoseChannel ** r_next)916 void BKE_pchan_bbone_handles_get(bPoseChannel *pchan, bPoseChannel **r_prev, bPoseChannel **r_next)
917 {
918   if (pchan->bone->bbone_prev_type == BBONE_HANDLE_AUTO) {
919     /* Use connected parent. */
920     if (pchan->bone->flag & BONE_CONNECTED) {
921       *r_prev = pchan->parent;
922     }
923     else {
924       *r_prev = NULL;
925     }
926   }
927   else {
928     /* Use the provided bone as prev - leave blank to eliminate this effect altogether. */
929     *r_prev = pchan->bbone_prev;
930   }
931 
932   if (pchan->bone->bbone_next_type == BBONE_HANDLE_AUTO) {
933     /* Use connected child. */
934     *r_next = pchan->child;
935   }
936   else {
937     /* Use the provided bone as next - leave blank to eliminate this effect altogether. */
938     *r_next = pchan->bbone_next;
939   }
940 }
941 
942 /* Compute B-Bone spline parameters for the given channel. */
BKE_pchan_bbone_spline_params_get(struct bPoseChannel * pchan,const bool rest,struct BBoneSplineParameters * param)943 void BKE_pchan_bbone_spline_params_get(struct bPoseChannel *pchan,
944                                        const bool rest,
945                                        struct BBoneSplineParameters *param)
946 {
947   bPoseChannel *next, *prev;
948   Bone *bone = pchan->bone;
949   float imat[4][4], posemat[4][4];
950   float delta[3];
951 
952   memset(param, 0, sizeof(*param));
953 
954   param->segments = bone->segments;
955   param->length = bone->length;
956 
957   if (!rest) {
958     float scale[3];
959 
960     /* Check if we need to take non-uniform bone scaling into account. */
961     mat4_to_size(scale, pchan->pose_mat);
962 
963     if (fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
964       param->do_scale = true;
965       copy_v3_v3(param->scale, scale);
966     }
967   }
968 
969   BKE_pchan_bbone_handles_get(pchan, &prev, &next);
970 
971   /* Find the handle points, since this is inside bone space, the
972    * first point = (0, 0, 0)
973    * last point =  (0, length, 0) */
974   if (rest) {
975     invert_m4_m4(imat, pchan->bone->arm_mat);
976   }
977   else if (param->do_scale) {
978     copy_m4_m4(posemat, pchan->pose_mat);
979     normalize_m4(posemat);
980     invert_m4_m4(imat, posemat);
981   }
982   else {
983     invert_m4_m4(imat, pchan->pose_mat);
984   }
985 
986   if (prev) {
987     float h1[3];
988     bool done = false;
989 
990     param->use_prev = true;
991 
992     /* Transform previous point inside this bone space. */
993     if (bone->bbone_prev_type == BBONE_HANDLE_RELATIVE) {
994       /* Use delta movement (from restpose), and apply this relative to the current bone's head. */
995       if (rest) {
996         /* In restpose, arm_head == pose_head */
997         zero_v3(param->prev_h);
998         done = true;
999       }
1000       else {
1001         sub_v3_v3v3(delta, prev->pose_head, prev->bone->arm_head);
1002         sub_v3_v3v3(h1, pchan->pose_head, delta);
1003       }
1004     }
1005     else if (bone->bbone_prev_type == BBONE_HANDLE_TANGENT) {
1006       /* Use bone direction by offsetting so that its tail meets current bone's head */
1007       if (rest) {
1008         sub_v3_v3v3(delta, prev->bone->arm_tail, prev->bone->arm_head);
1009         sub_v3_v3v3(h1, bone->arm_head, delta);
1010       }
1011       else {
1012         sub_v3_v3v3(delta, prev->pose_tail, prev->pose_head);
1013         sub_v3_v3v3(h1, pchan->pose_head, delta);
1014       }
1015     }
1016     else {
1017       /* Apply special handling for smoothly joining B-Bone chains */
1018       param->prev_bbone = (prev->bone->segments > 1);
1019 
1020       /* Use bone head as absolute position. */
1021       copy_v3_v3(h1, rest ? prev->bone->arm_head : prev->pose_head);
1022     }
1023 
1024     if (!done) {
1025       mul_v3_m4v3(param->prev_h, imat, h1);
1026     }
1027 
1028     if (!param->prev_bbone) {
1029       /* Find the previous roll to interpolate. */
1030       mul_m4_m4m4(param->prev_mat, imat, rest ? prev->bone->arm_mat : prev->pose_mat);
1031     }
1032   }
1033 
1034   if (next) {
1035     float h2[3];
1036     bool done = false;
1037 
1038     param->use_next = true;
1039 
1040     /* Transform next point inside this bone space. */
1041     if (bone->bbone_next_type == BBONE_HANDLE_RELATIVE) {
1042       /* Use delta movement (from restpose), and apply this relative to the current bone's tail. */
1043       if (rest) {
1044         /* In restpose, arm_head == pose_head */
1045         copy_v3_fl3(param->next_h, 0.0f, param->length, 0.0);
1046         done = true;
1047       }
1048       else {
1049         sub_v3_v3v3(delta, next->pose_head, next->bone->arm_head);
1050         add_v3_v3v3(h2, pchan->pose_tail, delta);
1051       }
1052     }
1053     else if (bone->bbone_next_type == BBONE_HANDLE_TANGENT) {
1054       /* Use bone direction by offsetting so that its head meets current bone's tail */
1055       if (rest) {
1056         sub_v3_v3v3(delta, next->bone->arm_tail, next->bone->arm_head);
1057         add_v3_v3v3(h2, bone->arm_tail, delta);
1058       }
1059       else {
1060         sub_v3_v3v3(delta, next->pose_tail, next->pose_head);
1061         add_v3_v3v3(h2, pchan->pose_tail, delta);
1062       }
1063     }
1064     else {
1065       /* Apply special handling for smoothly joining B-Bone chains */
1066       param->next_bbone = (next->bone->segments > 1);
1067 
1068       /* Use bone tail as absolute position. */
1069       copy_v3_v3(h2, rest ? next->bone->arm_tail : next->pose_tail);
1070     }
1071 
1072     if (!done) {
1073       mul_v3_m4v3(param->next_h, imat, h2);
1074     }
1075 
1076     /* Find the next roll to interpolate as well. */
1077     mul_m4_m4m4(param->next_mat, imat, rest ? next->bone->arm_mat : next->pose_mat);
1078   }
1079 
1080   /* Add effects from bbone properties over the top
1081    * - These properties allow users to hand-animate the
1082    *   bone curve/shape, without having to resort to using
1083    *   extra bones
1084    * - The "bone" level offsets are for defining the restpose
1085    *   shape of the bone (e.g. for curved eyebrows for example).
1086    *   -> In the viewport, it's needed to define what the rest pose
1087    *      looks like
1088    *   -> For "rest == 0", we also still need to have it present
1089    *      so that we can "cancel out" this restpose when it comes
1090    *      time to deform some geometry, it won't cause double transforms.
1091    * - The "pchan" level offsets are the ones that animators actually
1092    *   end up animating
1093    */
1094   {
1095     param->ease1 = bone->ease1 + (!rest ? pchan->ease1 : 0.0f);
1096     param->ease2 = bone->ease2 + (!rest ? pchan->ease2 : 0.0f);
1097 
1098     param->roll1 = bone->roll1 + (!rest ? pchan->roll1 : 0.0f);
1099     param->roll2 = bone->roll2 + (!rest ? pchan->roll2 : 0.0f);
1100 
1101     if (bone->flag & BONE_ADD_PARENT_END_ROLL) {
1102       if (prev) {
1103         if (prev->bone) {
1104           param->roll1 += prev->bone->roll2;
1105         }
1106 
1107         if (!rest) {
1108           param->roll1 += prev->roll2;
1109         }
1110       }
1111     }
1112 
1113     param->scale_in_x = bone->scale_in_x * (!rest ? pchan->scale_in_x : 1.0f);
1114     param->scale_in_y = bone->scale_in_y * (!rest ? pchan->scale_in_y : 1.0f);
1115     param->scale_out_x = bone->scale_out_x * (!rest ? pchan->scale_out_x : 1.0f);
1116     param->scale_out_y = bone->scale_out_y * (!rest ? pchan->scale_out_y : 1.0f);
1117 
1118     /* Extra curve x / y */
1119     param->curve_in_x = bone->curve_in_x + (!rest ? pchan->curve_in_x : 0.0f);
1120     param->curve_in_y = bone->curve_in_y + (!rest ? pchan->curve_in_y : 0.0f);
1121 
1122     param->curve_out_x = bone->curve_out_x + (!rest ? pchan->curve_out_x : 0.0f);
1123     param->curve_out_y = bone->curve_out_y + (!rest ? pchan->curve_out_y : 0.0f);
1124   }
1125 }
1126 
1127 /* Fills the array with the desired amount of bone->segments elements.
1128  * This calculation is done within unit bone space. */
BKE_pchan_bbone_spline_setup(bPoseChannel * pchan,const bool rest,const bool for_deform,Mat4 * result_array)1129 void BKE_pchan_bbone_spline_setup(bPoseChannel *pchan,
1130                                   const bool rest,
1131                                   const bool for_deform,
1132                                   Mat4 *result_array)
1133 {
1134   BBoneSplineParameters param;
1135 
1136   BKE_pchan_bbone_spline_params_get(pchan, rest, &param);
1137 
1138   pchan->bone->segments = BKE_pchan_bbone_spline_compute(&param, for_deform, result_array);
1139 }
1140 
1141 /* Computes the bezier handle vectors and rolls coming from custom handles. */
BKE_pchan_bbone_handles_compute(const BBoneSplineParameters * param,float h1[3],float * r_roll1,float h2[3],float * r_roll2,bool ease,bool offsets)1142 void BKE_pchan_bbone_handles_compute(const BBoneSplineParameters *param,
1143                                      float h1[3],
1144                                      float *r_roll1,
1145                                      float h2[3],
1146                                      float *r_roll2,
1147                                      bool ease,
1148                                      bool offsets)
1149 {
1150   float mat3[3][3];
1151   float length = param->length;
1152   float epsilon = 1e-5 * length;
1153 
1154   if (param->do_scale) {
1155     length *= param->scale[1];
1156   }
1157 
1158   *r_roll1 = *r_roll2 = 0.0f;
1159 
1160   if (param->use_prev) {
1161     copy_v3_v3(h1, param->prev_h);
1162 
1163     if (param->prev_bbone) {
1164       /* If previous bone is B-bone too, use average handle direction. */
1165       h1[1] -= length;
1166     }
1167 
1168     if (normalize_v3(h1) < epsilon) {
1169       copy_v3_fl3(h1, 0.0f, -1.0f, 0.0f);
1170     }
1171 
1172     negate_v3(h1);
1173 
1174     if (!param->prev_bbone) {
1175       /* Find the previous roll to interpolate. */
1176       copy_m3_m4(mat3, param->prev_mat);
1177       mat3_vec_to_roll(mat3, h1, r_roll1);
1178     }
1179   }
1180   else {
1181     h1[0] = 0.0f;
1182     h1[1] = 1.0;
1183     h1[2] = 0.0f;
1184   }
1185 
1186   if (param->use_next) {
1187     copy_v3_v3(h2, param->next_h);
1188 
1189     /* If next bone is B-bone too, use average handle direction. */
1190     if (param->next_bbone) {
1191       /* pass */
1192     }
1193     else {
1194       h2[1] -= length;
1195     }
1196 
1197     if (normalize_v3(h2) < epsilon) {
1198       copy_v3_fl3(h2, 0.0f, 1.0f, 0.0f);
1199     }
1200 
1201     /* Find the next roll to interpolate as well. */
1202     copy_m3_m4(mat3, param->next_mat);
1203     mat3_vec_to_roll(mat3, h2, r_roll2);
1204   }
1205   else {
1206     h2[0] = 0.0f;
1207     h2[1] = 1.0f;
1208     h2[2] = 0.0f;
1209   }
1210 
1211   if (ease) {
1212     const float circle_factor = length * (cubic_tangent_factor_circle_v3(h1, h2) / 0.75f);
1213 
1214     const float hlength1 = param->ease1 * circle_factor;
1215     const float hlength2 = param->ease2 * circle_factor;
1216 
1217     /* and only now negate h2 */
1218     mul_v3_fl(h1, hlength1);
1219     mul_v3_fl(h2, -hlength2);
1220   }
1221 
1222   /* Add effects from bbone properties over the top
1223    * - These properties allow users to hand-animate the
1224    *   bone curve/shape, without having to resort to using
1225    *   extra bones
1226    * - The "bone" level offsets are for defining the rest-pose
1227    *   shape of the bone (e.g. for curved eyebrows for example).
1228    *   -> In the viewport, it's needed to define what the rest pose
1229    *      looks like
1230    *   -> For "rest == 0", we also still need to have it present
1231    *      so that we can "cancel out" this rest-pose when it comes
1232    *      time to deform some geometry, it won't cause double transforms.
1233    * - The "pchan" level offsets are the ones that animators actually
1234    *   end up animating
1235    */
1236   if (offsets) {
1237     /* Add extra rolls. */
1238     *r_roll1 += param->roll1;
1239     *r_roll2 += param->roll2;
1240 
1241     /* Extra curve x / y */
1242     /* NOTE:
1243      * Scale correction factors here are to compensate for some random floating-point glitches
1244      * when scaling up the bone or its parent by a factor of approximately 8.15/6, which results
1245      * in the bone length getting scaled up too (from 1 to 8), causing the curve to flatten out.
1246      */
1247     const float xscale_correction = (param->do_scale) ? param->scale[0] : 1.0f;
1248     const float yscale_correction = (param->do_scale) ? param->scale[2] : 1.0f;
1249 
1250     h1[0] += param->curve_in_x * xscale_correction;
1251     h1[2] += param->curve_in_y * yscale_correction;
1252 
1253     h2[0] += param->curve_out_x * xscale_correction;
1254     h2[2] += param->curve_out_y * yscale_correction;
1255   }
1256 }
1257 
make_bbone_spline_matrix(BBoneSplineParameters * param,const float scalemats[2][4][4],const float pos[3],const float axis[3],float roll,float scalex,float scaley,float result[4][4])1258 static void make_bbone_spline_matrix(BBoneSplineParameters *param,
1259                                      const float scalemats[2][4][4],
1260                                      const float pos[3],
1261                                      const float axis[3],
1262                                      float roll,
1263                                      float scalex,
1264                                      float scaley,
1265                                      float result[4][4])
1266 {
1267   float mat3[3][3];
1268 
1269   vec_roll_to_mat3(axis, roll, mat3);
1270 
1271   copy_m4_m3(result, mat3);
1272   copy_v3_v3(result[3], pos);
1273 
1274   if (param->do_scale) {
1275     /* Correct for scaling when this matrix is used in scaled space. */
1276     mul_m4_series(result, scalemats[0], result, scalemats[1]);
1277   }
1278 
1279   /* BBone scale... */
1280   mul_v3_fl(result[0], scalex);
1281   mul_v3_fl(result[2], scaley);
1282 }
1283 
1284 /* Fade from first to second derivative when the handle is very short. */
ease_handle_axis(const float deriv1[3],const float deriv2[3],float r_axis[3])1285 static void ease_handle_axis(const float deriv1[3], const float deriv2[3], float r_axis[3])
1286 {
1287   const float gap = 0.1f;
1288 
1289   copy_v3_v3(r_axis, deriv1);
1290 
1291   float len1 = len_squared_v3(deriv1), len2 = len_squared_v3(deriv2);
1292   float ratio = len1 / len2;
1293 
1294   if (ratio < gap * gap) {
1295     madd_v3_v3fl(r_axis, deriv2, gap - sqrtf(ratio));
1296   }
1297 }
1298 
1299 /* Fills the array with the desired amount of bone->segments elements.
1300  * This calculation is done within unit bone space. */
BKE_pchan_bbone_spline_compute(BBoneSplineParameters * param,const bool for_deform,Mat4 * result_array)1301 int BKE_pchan_bbone_spline_compute(BBoneSplineParameters *param,
1302                                    const bool for_deform,
1303                                    Mat4 *result_array)
1304 {
1305   float scalemats[2][4][4];
1306   float bezt_controls[4][3];
1307   float h1[3], roll1, h2[3], roll2, prev[3], cur[3], axis[3];
1308   float length = param->length;
1309 
1310   if (param->do_scale) {
1311     size_to_mat4(scalemats[1], param->scale);
1312     invert_m4_m4(scalemats[0], scalemats[1]);
1313 
1314     length *= param->scale[1];
1315   }
1316 
1317   BKE_pchan_bbone_handles_compute(param, h1, &roll1, h2, &roll2, true, true);
1318 
1319   /* Make curve. */
1320   CLAMP_MAX(param->segments, MAX_BBONE_SUBDIV);
1321 
1322   copy_v3_fl3(bezt_controls[3], 0.0f, length, 0.0f);
1323   add_v3_v3v3(bezt_controls[2], bezt_controls[3], h2);
1324   copy_v3_v3(bezt_controls[1], h1);
1325   zero_v3(bezt_controls[0]);
1326 
1327   float bezt_points[MAX_BBONE_SUBDIV + 1];
1328 
1329   equalize_cubic_bezier(bezt_controls, MAX_BBONE_SUBDIV, param->segments, bezt_points);
1330 
1331   /* Deformation uses N+1 matrices computed at points between the segments. */
1332   if (for_deform) {
1333     /* Bezier derivatives. */
1334     float bezt_deriv1[3][3], bezt_deriv2[2][3];
1335 
1336     for (int i = 0; i < 3; i++) {
1337       sub_v3_v3v3(bezt_deriv1[i], bezt_controls[i + 1], bezt_controls[i]);
1338     }
1339     for (int i = 0; i < 2; i++) {
1340       sub_v3_v3v3(bezt_deriv2[i], bezt_deriv1[i + 1], bezt_deriv1[i]);
1341     }
1342 
1343     /* End points require special handling to fix zero length handles. */
1344     ease_handle_axis(bezt_deriv1[0], bezt_deriv2[0], axis);
1345     make_bbone_spline_matrix(param,
1346                              scalemats,
1347                              bezt_controls[0],
1348                              axis,
1349                              roll1,
1350                              param->scale_in_x,
1351                              param->scale_in_y,
1352                              result_array[0].mat);
1353 
1354     for (int a = 1; a < param->segments; a++) {
1355       evaluate_cubic_bezier(bezt_controls, bezt_points[a], cur, axis);
1356 
1357       float fac = ((float)a) / param->segments;
1358       float roll = interpf(roll2, roll1, fac);
1359       float scalex = interpf(param->scale_out_x, param->scale_in_x, fac);
1360       float scaley = interpf(param->scale_out_y, param->scale_in_y, fac);
1361 
1362       make_bbone_spline_matrix(
1363           param, scalemats, cur, axis, roll, scalex, scaley, result_array[a].mat);
1364     }
1365 
1366     negate_v3(bezt_deriv2[1]);
1367     ease_handle_axis(bezt_deriv1[2], bezt_deriv2[1], axis);
1368     make_bbone_spline_matrix(param,
1369                              scalemats,
1370                              bezt_controls[3],
1371                              axis,
1372                              roll2,
1373                              param->scale_out_x,
1374                              param->scale_out_y,
1375                              result_array[param->segments].mat);
1376   }
1377   /* Other code (e.g. display) uses matrices for the segments themselves. */
1378   else {
1379     zero_v3(prev);
1380 
1381     for (int a = 0; a < param->segments; a++) {
1382       evaluate_cubic_bezier(bezt_controls, bezt_points[a + 1], cur, axis);
1383 
1384       sub_v3_v3v3(axis, cur, prev);
1385 
1386       float fac = (a + 0.5f) / param->segments;
1387       float roll = interpf(roll2, roll1, fac);
1388       float scalex = interpf(param->scale_out_x, param->scale_in_x, fac);
1389       float scaley = interpf(param->scale_out_y, param->scale_in_y, fac);
1390 
1391       make_bbone_spline_matrix(
1392           param, scalemats, prev, axis, roll, scalex, scaley, result_array[a].mat);
1393       copy_v3_v3(prev, cur);
1394     }
1395   }
1396 
1397   return param->segments;
1398 }
1399 
allocate_bbone_cache(bPoseChannel * pchan,int segments)1400 static void allocate_bbone_cache(bPoseChannel *pchan, int segments)
1401 {
1402   bPoseChannel_Runtime *runtime = &pchan->runtime;
1403 
1404   if (runtime->bbone_segments != segments) {
1405     BKE_pose_channel_free_bbone_cache(runtime);
1406 
1407     runtime->bbone_segments = segments;
1408     runtime->bbone_rest_mats = MEM_malloc_arrayN(
1409         sizeof(Mat4), 1 + (uint)segments, "bPoseChannel_Runtime::bbone_rest_mats");
1410     runtime->bbone_pose_mats = MEM_malloc_arrayN(
1411         sizeof(Mat4), 1 + (uint)segments, "bPoseChannel_Runtime::bbone_pose_mats");
1412     runtime->bbone_deform_mats = MEM_malloc_arrayN(
1413         sizeof(Mat4), 2 + (uint)segments, "bPoseChannel_Runtime::bbone_deform_mats");
1414     runtime->bbone_dual_quats = MEM_malloc_arrayN(
1415         sizeof(DualQuat), 1 + (uint)segments, "bPoseChannel_Runtime::bbone_dual_quats");
1416   }
1417 }
1418 
1419 /** Compute and cache the B-Bone shape in the channel runtime struct. */
BKE_pchan_bbone_segments_cache_compute(bPoseChannel * pchan)1420 void BKE_pchan_bbone_segments_cache_compute(bPoseChannel *pchan)
1421 {
1422   bPoseChannel_Runtime *runtime = &pchan->runtime;
1423   Bone *bone = pchan->bone;
1424   int segments = bone->segments;
1425 
1426   BLI_assert(segments > 1);
1427 
1428   /* Allocate the cache if needed. */
1429   allocate_bbone_cache(pchan, segments);
1430 
1431   /* Compute the shape. */
1432   Mat4 *b_bone = runtime->bbone_pose_mats;
1433   Mat4 *b_bone_rest = runtime->bbone_rest_mats;
1434   Mat4 *b_bone_mats = runtime->bbone_deform_mats;
1435   DualQuat *b_bone_dual_quats = runtime->bbone_dual_quats;
1436   int a;
1437 
1438   BKE_pchan_bbone_spline_setup(pchan, false, true, b_bone);
1439   BKE_pchan_bbone_spline_setup(pchan, true, true, b_bone_rest);
1440 
1441   /* Compute deform matrices. */
1442   /* first matrix is the inverse arm_mat, to bring points in local bone space
1443    * for finding out which segment it belongs to */
1444   invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
1445 
1446   /* then we make the b_bone_mats:
1447    * - first transform to local bone space
1448    * - translate over the curve to the bbone mat space
1449    * - transform with b_bone matrix
1450    * - transform back into global space */
1451 
1452   for (a = 0; a <= bone->segments; a++) {
1453     float tmat[4][4];
1454 
1455     invert_m4_m4(tmat, b_bone_rest[a].mat);
1456     mul_m4_series(b_bone_mats[a + 1].mat,
1457                   pchan->chan_mat,
1458                   bone->arm_mat,
1459                   b_bone[a].mat,
1460                   tmat,
1461                   b_bone_mats[0].mat);
1462 
1463     mat4_to_dquat(&b_bone_dual_quats[a], bone->arm_mat, b_bone_mats[a + 1].mat);
1464   }
1465 }
1466 
1467 /** Copy cached B-Bone segments from one channel to another */
BKE_pchan_bbone_segments_cache_copy(bPoseChannel * pchan,bPoseChannel * pchan_from)1468 void BKE_pchan_bbone_segments_cache_copy(bPoseChannel *pchan, bPoseChannel *pchan_from)
1469 {
1470   bPoseChannel_Runtime *runtime = &pchan->runtime;
1471   bPoseChannel_Runtime *runtime_from = &pchan_from->runtime;
1472   int segments = runtime_from->bbone_segments;
1473 
1474   if (segments <= 1) {
1475     BKE_pose_channel_free_bbone_cache(&pchan->runtime);
1476   }
1477   else {
1478     allocate_bbone_cache(pchan, segments);
1479 
1480     memcpy(runtime->bbone_rest_mats, runtime_from->bbone_rest_mats, sizeof(Mat4) * (1 + segments));
1481     memcpy(runtime->bbone_pose_mats, runtime_from->bbone_pose_mats, sizeof(Mat4) * (1 + segments));
1482     memcpy(runtime->bbone_deform_mats,
1483            runtime_from->bbone_deform_mats,
1484            sizeof(Mat4) * (2 + segments));
1485     memcpy(runtime->bbone_dual_quats,
1486            runtime_from->bbone_dual_quats,
1487            sizeof(DualQuat) * (1 + segments));
1488   }
1489 }
1490 
1491 /**
1492  * Calculate index and blend factor for the two B-Bone segment nodes
1493  * affecting the point at 0 <= pos <= 1.
1494  */
BKE_pchan_bbone_deform_segment_index(const bPoseChannel * pchan,float pos,int * r_index,float * r_blend_next)1495 void BKE_pchan_bbone_deform_segment_index(const bPoseChannel *pchan,
1496                                           float pos,
1497                                           int *r_index,
1498                                           float *r_blend_next)
1499 {
1500   int segments = pchan->bone->segments;
1501 
1502   CLAMP(pos, 0.0f, 1.0f);
1503 
1504   /* Calculate the indices of the 2 affecting b_bone segments.
1505    * Integer part is the first segment's index.
1506    * Integer part plus 1 is the second segment's index.
1507    * Fractional part is the blend factor. */
1508   float pre_blend = pos * (float)segments;
1509 
1510   int index = (int)floorf(pre_blend);
1511   CLAMP(index, 0, segments - 1);
1512 
1513   float blend = pre_blend - index;
1514   CLAMP(blend, 0.0f, 1.0f);
1515 
1516   *r_index = index;
1517   *r_blend_next = blend;
1518 }
1519 
1520 /** \} */
1521 
1522 /* -------------------------------------------------------------------- */
1523 /** \name Bone Space to Space Conversion API
1524  * \{ */
1525 
get_objectspace_bone_matrix(struct Bone * bone,float M_accumulatedMatrix[4][4],int UNUSED (root),int UNUSED (posed))1526 void get_objectspace_bone_matrix(struct Bone *bone,
1527                                  float M_accumulatedMatrix[4][4],
1528                                  int UNUSED(root),
1529                                  int UNUSED(posed))
1530 {
1531   copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1532 }
1533 
1534 /* Convert World-Space Matrix to Pose-Space Matrix */
BKE_armature_mat_world_to_pose(Object * ob,const float inmat[4][4],float outmat[4][4])1535 void BKE_armature_mat_world_to_pose(Object *ob, const float inmat[4][4], float outmat[4][4])
1536 {
1537   float obmat[4][4];
1538 
1539   /* prevent crashes */
1540   if (ob == NULL) {
1541     return;
1542   }
1543 
1544   /* get inverse of (armature) object's matrix  */
1545   invert_m4_m4(obmat, ob->obmat);
1546 
1547   /* multiply given matrix by object's-inverse to find pose-space matrix */
1548   mul_m4_m4m4(outmat, inmat, obmat);
1549 }
1550 
1551 /* Convert World-Space Location to Pose-Space Location
1552  * NOTE: this cannot be used to convert to pose-space location of the supplied
1553  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
BKE_armature_loc_world_to_pose(Object * ob,const float inloc[3],float outloc[3])1554 void BKE_armature_loc_world_to_pose(Object *ob, const float inloc[3], float outloc[3])
1555 {
1556   float xLocMat[4][4];
1557   float nLocMat[4][4];
1558 
1559   /* build matrix for location */
1560   unit_m4(xLocMat);
1561   copy_v3_v3(xLocMat[3], inloc);
1562 
1563   /* get bone-space cursor matrix and extract location */
1564   BKE_armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1565   copy_v3_v3(outloc, nLocMat[3]);
1566 }
1567 
1568 /** \} */
1569 
1570 /* -------------------------------------------------------------------- */
1571 /** \name Bone Matrix Calculation API
1572  * \{ */
1573 
1574 /* Simple helper, computes the offset bone matrix.
1575  *     offs_bone = yoffs(b-1) + root(b) + bonemat(b). */
BKE_bone_offset_matrix_get(const Bone * bone,float offs_bone[4][4])1576 void BKE_bone_offset_matrix_get(const Bone *bone, float offs_bone[4][4])
1577 {
1578   BLI_assert(bone->parent != NULL);
1579 
1580   /* Bone transform itself. */
1581   copy_m4_m3(offs_bone, bone->bone_mat);
1582 
1583   /* The bone's root offset (is in the parent's coordinate system). */
1584   copy_v3_v3(offs_bone[3], bone->head);
1585 
1586   /* Get the length translation of parent (length along y axis). */
1587   offs_bone[3][1] += bone->parent->length;
1588 }
1589 
1590 /* Construct the matrices (rot/scale and loc)
1591  * to apply the PoseChannels into the armature (object) space.
1592  * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the
1593  *     pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1594  * ...function.
1595  *
1596  * This allows to get the transformations of a bone in its object space,
1597  * *before* constraints (and IK) get applied (used by pose evaluation code).
1598  * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale
1599  * in object space (used by interactive transform, and snapping code).
1600  *
1601  * Note that, with the HINGE/NO_SCALE/NO_LOCAL_LOCATION options, the location matrix
1602  * will differ from the rotation/scale matrix...
1603  *
1604  * NOTE: This cannot be used to convert to pose-space transforms of the supplied
1605  *       pose-channel into its local space (i.e. 'visual'-keyframing).
1606  *       (note: I don't understand that, so I keep it :p --mont29).
1607  */
BKE_bone_parent_transform_calc_from_pchan(const bPoseChannel * pchan,BoneParentTransform * r_bpt)1608 void BKE_bone_parent_transform_calc_from_pchan(const bPoseChannel *pchan,
1609                                                BoneParentTransform *r_bpt)
1610 {
1611   const Bone *bone, *parbone;
1612   const bPoseChannel *parchan;
1613 
1614   /* set up variables for quicker access below */
1615   bone = pchan->bone;
1616   parbone = bone->parent;
1617   parchan = pchan->parent;
1618 
1619   if (parchan) {
1620     float offs_bone[4][4];
1621     /* yoffs(b-1) + root(b) + bonemat(b). */
1622     BKE_bone_offset_matrix_get(bone, offs_bone);
1623 
1624     BKE_bone_parent_transform_calc_from_matrices(bone->flag,
1625                                                  bone->inherit_scale_mode,
1626                                                  offs_bone,
1627                                                  parbone->arm_mat,
1628                                                  parchan->pose_mat,
1629                                                  r_bpt);
1630   }
1631   else {
1632     BKE_bone_parent_transform_calc_from_matrices(
1633         bone->flag, bone->inherit_scale_mode, bone->arm_mat, NULL, NULL, r_bpt);
1634   }
1635 }
1636 
1637 /* Compute the parent transform using data decoupled from specific data structures.
1638  *
1639  * bone_flag: Bone->flag containing settings
1640  * offs_bone: delta from parent to current arm_mat (or just arm_mat if no parent)
1641  * parent_arm_mat, parent_pose_mat: arm_mat and pose_mat of parent, or NULL
1642  * r_bpt: OUTPUT parent transform */
BKE_bone_parent_transform_calc_from_matrices(int bone_flag,int inherit_scale_mode,const float offs_bone[4][4],const float parent_arm_mat[4][4],const float parent_pose_mat[4][4],BoneParentTransform * r_bpt)1643 void BKE_bone_parent_transform_calc_from_matrices(int bone_flag,
1644                                                   int inherit_scale_mode,
1645                                                   const float offs_bone[4][4],
1646                                                   const float parent_arm_mat[4][4],
1647                                                   const float parent_pose_mat[4][4],
1648                                                   BoneParentTransform *r_bpt)
1649 {
1650   copy_v3_fl(r_bpt->post_scale, 1.0f);
1651 
1652   if (parent_pose_mat) {
1653     const bool use_rotation = (bone_flag & BONE_HINGE) == 0;
1654     const bool full_transform = use_rotation && inherit_scale_mode == BONE_INHERIT_SCALE_FULL;
1655 
1656     /* Compose the rotscale matrix for this bone. */
1657     if (full_transform) {
1658       /* Parent pose rotation and scale. */
1659       mul_m4_m4m4(r_bpt->rotscale_mat, parent_pose_mat, offs_bone);
1660     }
1661     else {
1662       float tmat[4][4], tscale[3];
1663 
1664       /* If using parent pose rotation: */
1665       if (use_rotation) {
1666         copy_m4_m4(tmat, parent_pose_mat);
1667 
1668         /* Normalize the matrix when needed. */
1669         switch (inherit_scale_mode) {
1670           case BONE_INHERIT_SCALE_FULL:
1671           case BONE_INHERIT_SCALE_FIX_SHEAR:
1672             /* Keep scale and shear. */
1673             break;
1674 
1675           case BONE_INHERIT_SCALE_NONE:
1676           case BONE_INHERIT_SCALE_AVERAGE:
1677             /* Remove scale and shear from parent. */
1678             orthogonalize_m4_stable(tmat, 1, true);
1679             break;
1680 
1681           case BONE_INHERIT_SCALE_ALIGNED:
1682             /* Remove shear and extract scale. */
1683             orthogonalize_m4_stable(tmat, 1, false);
1684             normalize_m4_ex(tmat, r_bpt->post_scale);
1685             break;
1686 
1687           case BONE_INHERIT_SCALE_NONE_LEGACY:
1688             /* Remove only scale - bad legacy way. */
1689             normalize_m4(tmat);
1690             break;
1691 
1692           default:
1693             BLI_assert(false);
1694         }
1695       }
1696       /* If removing parent pose rotation: */
1697       else {
1698         copy_m4_m4(tmat, parent_arm_mat);
1699 
1700         /* Copy the parent scale when needed. */
1701         switch (inherit_scale_mode) {
1702           case BONE_INHERIT_SCALE_FULL:
1703             /* Ignore effects of shear. */
1704             mat4_to_size(tscale, parent_pose_mat);
1705             rescale_m4(tmat, tscale);
1706             break;
1707 
1708           case BONE_INHERIT_SCALE_FIX_SHEAR:
1709             /* Take the effects of parent shear into account to get exact volume. */
1710             mat4_to_size_fix_shear(tscale, parent_pose_mat);
1711             rescale_m4(tmat, tscale);
1712             break;
1713 
1714           case BONE_INHERIT_SCALE_ALIGNED:
1715             mat4_to_size_fix_shear(r_bpt->post_scale, parent_pose_mat);
1716             break;
1717 
1718           case BONE_INHERIT_SCALE_NONE:
1719           case BONE_INHERIT_SCALE_AVERAGE:
1720           case BONE_INHERIT_SCALE_NONE_LEGACY:
1721             /* Keep unscaled. */
1722             break;
1723 
1724           default:
1725             BLI_assert(false);
1726         }
1727       }
1728 
1729       /* Apply the average parent scale when needed. */
1730       if (inherit_scale_mode == BONE_INHERIT_SCALE_AVERAGE) {
1731         mul_mat3_m4_fl(tmat, cbrtf(fabsf(mat4_to_volume_scale(parent_pose_mat))));
1732       }
1733 
1734       mul_m4_m4m4(r_bpt->rotscale_mat, tmat, offs_bone);
1735 
1736       /* Remove remaining shear when needed, preserving volume. */
1737       if (inherit_scale_mode == BONE_INHERIT_SCALE_FIX_SHEAR) {
1738         orthogonalize_m4_stable(r_bpt->rotscale_mat, 1, false);
1739       }
1740     }
1741 
1742     /* Compose the loc matrix for this bone. */
1743     /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */
1744 
1745     /* In this case, use the object's space *orientation*. */
1746     if (bone_flag & BONE_NO_LOCAL_LOCATION) {
1747       /* XXX I'm sure that code can be simplified! */
1748       float bone_loc[4][4], bone_rotscale[3][3], tmat4[4][4], tmat3[3][3];
1749       unit_m4(bone_loc);
1750       unit_m4(r_bpt->loc_mat);
1751       unit_m4(tmat4);
1752 
1753       mul_v3_m4v3(bone_loc[3], parent_pose_mat, offs_bone[3]);
1754 
1755       unit_m3(bone_rotscale);
1756       copy_m3_m4(tmat3, parent_pose_mat);
1757       mul_m3_m3m3(bone_rotscale, tmat3, bone_rotscale);
1758 
1759       copy_m4_m3(tmat4, bone_rotscale);
1760       mul_m4_m4m4(r_bpt->loc_mat, bone_loc, tmat4);
1761     }
1762     /* Those flags do not affect position, use plain parent transform space! */
1763     else if (!full_transform) {
1764       mul_m4_m4m4(r_bpt->loc_mat, parent_pose_mat, offs_bone);
1765     }
1766     /* Else (i.e. default, usual case),
1767      * just use the same matrix for rotation/scaling, and location. */
1768     else {
1769       copy_m4_m4(r_bpt->loc_mat, r_bpt->rotscale_mat);
1770     }
1771   }
1772   /* Root bones. */
1773   else {
1774     /* Rotation/scaling. */
1775     copy_m4_m4(r_bpt->rotscale_mat, offs_bone);
1776     /* Translation. */
1777     if (bone_flag & BONE_NO_LOCAL_LOCATION) {
1778       /* Translation of arm_mat, without the rotation. */
1779       unit_m4(r_bpt->loc_mat);
1780       copy_v3_v3(r_bpt->loc_mat[3], offs_bone[3]);
1781     }
1782     else {
1783       copy_m4_m4(r_bpt->loc_mat, r_bpt->rotscale_mat);
1784     }
1785   }
1786 }
1787 
BKE_bone_parent_transform_clear(struct BoneParentTransform * bpt)1788 void BKE_bone_parent_transform_clear(struct BoneParentTransform *bpt)
1789 {
1790   unit_m4(bpt->rotscale_mat);
1791   unit_m4(bpt->loc_mat);
1792   copy_v3_fl(bpt->post_scale, 1.0f);
1793 }
1794 
BKE_bone_parent_transform_invert(struct BoneParentTransform * bpt)1795 void BKE_bone_parent_transform_invert(struct BoneParentTransform *bpt)
1796 {
1797   invert_m4(bpt->rotscale_mat);
1798   invert_m4(bpt->loc_mat);
1799   invert_v3(bpt->post_scale);
1800 }
1801 
BKE_bone_parent_transform_combine(const struct BoneParentTransform * in1,const struct BoneParentTransform * in2,struct BoneParentTransform * result)1802 void BKE_bone_parent_transform_combine(const struct BoneParentTransform *in1,
1803                                        const struct BoneParentTransform *in2,
1804                                        struct BoneParentTransform *result)
1805 {
1806   mul_m4_m4m4(result->rotscale_mat, in1->rotscale_mat, in2->rotscale_mat);
1807   mul_m4_m4m4(result->loc_mat, in1->loc_mat, in2->loc_mat);
1808   mul_v3_v3v3(result->post_scale, in1->post_scale, in2->post_scale);
1809 }
1810 
BKE_bone_parent_transform_apply(const struct BoneParentTransform * bpt,const float inmat[4][4],float outmat[4][4])1811 void BKE_bone_parent_transform_apply(const struct BoneParentTransform *bpt,
1812                                      const float inmat[4][4],
1813                                      float outmat[4][4])
1814 {
1815   /* in case inmat == outmat */
1816   float tmploc[3];
1817   copy_v3_v3(tmploc, inmat[3]);
1818 
1819   mul_m4_m4m4(outmat, bpt->rotscale_mat, inmat);
1820   mul_v3_m4v3(outmat[3], bpt->loc_mat, tmploc);
1821   rescale_m4(outmat, bpt->post_scale);
1822 }
1823 
1824 /* Convert Pose-Space Matrix to Bone-Space Matrix.
1825  * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1826  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
BKE_armature_mat_pose_to_bone(bPoseChannel * pchan,const float inmat[4][4],float outmat[4][4])1827 void BKE_armature_mat_pose_to_bone(bPoseChannel *pchan,
1828                                    const float inmat[4][4],
1829                                    float outmat[4][4])
1830 {
1831   BoneParentTransform bpt;
1832 
1833   BKE_bone_parent_transform_calc_from_pchan(pchan, &bpt);
1834   BKE_bone_parent_transform_invert(&bpt);
1835   BKE_bone_parent_transform_apply(&bpt, inmat, outmat);
1836 }
1837 
1838 /* Convert Bone-Space Matrix to Pose-Space Matrix. */
BKE_armature_mat_bone_to_pose(bPoseChannel * pchan,const float inmat[4][4],float outmat[4][4])1839 void BKE_armature_mat_bone_to_pose(bPoseChannel *pchan,
1840                                    const float inmat[4][4],
1841                                    float outmat[4][4])
1842 {
1843   BoneParentTransform bpt;
1844 
1845   BKE_bone_parent_transform_calc_from_pchan(pchan, &bpt);
1846   BKE_bone_parent_transform_apply(&bpt, inmat, outmat);
1847 }
1848 
1849 /* Convert Pose-Space Location to Bone-Space Location
1850  * NOTE: this cannot be used to convert to pose-space location of the supplied
1851  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
BKE_armature_loc_pose_to_bone(bPoseChannel * pchan,const float inloc[3],float outloc[3])1852 void BKE_armature_loc_pose_to_bone(bPoseChannel *pchan, const float inloc[3], float outloc[3])
1853 {
1854   float xLocMat[4][4];
1855   float nLocMat[4][4];
1856 
1857   /* build matrix for location */
1858   unit_m4(xLocMat);
1859   copy_v3_v3(xLocMat[3], inloc);
1860 
1861   /* get bone-space cursor matrix and extract location */
1862   BKE_armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1863   copy_v3_v3(outloc, nLocMat[3]);
1864 }
1865 
1866 /** \} */
1867 
1868 /* -------------------------------------------------------------------- */
1869 /** \name Bone Matrix Read/Write API
1870  *
1871  * High level functions for transforming bones and reading the transform values.
1872  * \{ */
1873 
BKE_armature_mat_pose_to_bone_ex(struct Depsgraph * depsgraph,Object * ob,bPoseChannel * pchan,const float inmat[4][4],float outmat[4][4])1874 void BKE_armature_mat_pose_to_bone_ex(struct Depsgraph *depsgraph,
1875                                       Object *ob,
1876                                       bPoseChannel *pchan,
1877                                       const float inmat[4][4],
1878                                       float outmat[4][4])
1879 {
1880   bPoseChannel work_pchan = *pchan;
1881 
1882   /* recalculate pose matrix with only parent transformations,
1883    * bone loc/sca/rot is ignored, scene and frame are not used. */
1884   BKE_pose_where_is_bone(depsgraph, NULL, ob, &work_pchan, 0.0f, false);
1885 
1886   /* find the matrix, need to remove the bone transforms first so this is
1887    * calculated as a matrix to set rather than a difference ontop of what's
1888    * already there. */
1889   unit_m4(outmat);
1890   BKE_pchan_apply_mat4(&work_pchan, outmat, false);
1891 
1892   BKE_armature_mat_pose_to_bone(&work_pchan, inmat, outmat);
1893 }
1894 
1895 /**
1896  * Same as #BKE_object_mat3_to_rot().
1897  */
BKE_pchan_mat3_to_rot(bPoseChannel * pchan,const float mat[3][3],bool use_compat)1898 void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, const float mat[3][3], bool use_compat)
1899 {
1900   BLI_ASSERT_UNIT_M3(mat);
1901 
1902   switch (pchan->rotmode) {
1903     case ROT_MODE_QUAT:
1904       mat3_normalized_to_quat(pchan->quat, mat);
1905       break;
1906     case ROT_MODE_AXISANGLE:
1907       mat3_normalized_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1908       break;
1909     default: /* euler */
1910       if (use_compat) {
1911         mat3_normalized_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1912       }
1913       else {
1914         mat3_normalized_to_eulO(pchan->eul, pchan->rotmode, mat);
1915       }
1916       break;
1917   }
1918 }
1919 
1920 /**
1921  * Same as #BKE_object_rot_to_mat3().
1922  */
BKE_pchan_rot_to_mat3(const bPoseChannel * pchan,float r_mat[3][3])1923 void BKE_pchan_rot_to_mat3(const bPoseChannel *pchan, float r_mat[3][3])
1924 {
1925   /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1926   if (pchan->rotmode > 0) {
1927     /* euler rotations (will cause gimble lock,
1928      * but this can be alleviated a bit with rotation orders) */
1929     eulO_to_mat3(r_mat, pchan->eul, pchan->rotmode);
1930   }
1931   else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
1932     /* axis-angle - not really that great for 3D-changing orientations */
1933     axis_angle_to_mat3(r_mat, pchan->rotAxis, pchan->rotAngle);
1934   }
1935   else {
1936     /* quats are normalized before use to eliminate scaling issues */
1937     float quat[4];
1938 
1939     /* NOTE: we now don't normalize the stored values anymore,
1940      * since this was kindof evil in some cases but if this proves to be too problematic,
1941      * switch back to the old system of operating directly on the stored copy. */
1942     normalize_qt_qt(quat, pchan->quat);
1943     quat_to_mat3(r_mat, quat);
1944   }
1945 }
1946 
1947 /**
1948  * Apply a 4x4 matrix to the pose bone,
1949  * similar to #BKE_object_apply_mat4().
1950  */
BKE_pchan_apply_mat4(bPoseChannel * pchan,const float mat[4][4],bool use_compat)1951 void BKE_pchan_apply_mat4(bPoseChannel *pchan, const float mat[4][4], bool use_compat)
1952 {
1953   float rot[3][3];
1954   mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1955   BKE_pchan_mat3_to_rot(pchan, rot, use_compat);
1956 }
1957 
1958 /**
1959  * Remove rest-position effects from pose-transform for obtaining
1960  * 'visual' transformation of pose-channel.
1961  * (used by the Visual-Keyframing stuff).
1962  */
BKE_armature_mat_pose_to_delta(float delta_mat[4][4],float pose_mat[4][4],float arm_mat[4][4])1963 void BKE_armature_mat_pose_to_delta(float delta_mat[4][4],
1964                                     float pose_mat[4][4],
1965                                     float arm_mat[4][4])
1966 {
1967   float imat[4][4];
1968 
1969   invert_m4_m4(imat, arm_mat);
1970   mul_m4_m4m4(delta_mat, imat, pose_mat);
1971 }
1972 
1973 /** \} */
1974 
1975 /* -------------------------------------------------------------------- */
1976 /** \name Rotation Mode Conversions
1977  *
1978  * Used for Objects and Pose Channels, since both can have multiple rotation representations.
1979  * \{ */
1980 
1981 /* Called from RNA when rotation mode changes
1982  * - the result should be that the rotations given in the provided pointers have had conversions
1983  *   applied (as appropriate), such that the rotation of the element hasn't 'visually' changed  */
BKE_rotMode_change_values(float quat[4],float eul[3],float axis[3],float * angle,short oldMode,short newMode)1984 void BKE_rotMode_change_values(
1985     float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1986 {
1987   /* check if any change - if so, need to convert data */
1988   if (newMode > 0) { /* to euler */
1989     if (oldMode == ROT_MODE_AXISANGLE) {
1990       /* axis-angle to euler */
1991       axis_angle_to_eulO(eul, newMode, axis, *angle);
1992     }
1993     else if (oldMode == ROT_MODE_QUAT) {
1994       /* quat to euler */
1995       normalize_qt(quat);
1996       quat_to_eulO(eul, newMode, quat);
1997     }
1998     /* else { no conversion needed } */
1999   }
2000   else if (newMode == ROT_MODE_QUAT) { /* to quat */
2001     if (oldMode == ROT_MODE_AXISANGLE) {
2002       /* axis angle to quat */
2003       axis_angle_to_quat(quat, axis, *angle);
2004     }
2005     else if (oldMode > 0) {
2006       /* euler to quat */
2007       eulO_to_quat(quat, eul, oldMode);
2008     }
2009     /* else { no conversion needed } */
2010   }
2011   else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
2012     if (oldMode > 0) {
2013       /* euler to axis angle */
2014       eulO_to_axis_angle(axis, angle, eul, oldMode);
2015     }
2016     else if (oldMode == ROT_MODE_QUAT) {
2017       /* quat to axis angle */
2018       normalize_qt(quat);
2019       quat_to_axis_angle(axis, angle, quat);
2020     }
2021 
2022     /* When converting to axis-angle,
2023      * we need a special exception for the case when there is no axis. */
2024     if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
2025       /* for now, rotate around y-axis then (so that it simply becomes the roll) */
2026       axis[1] = 1.0f;
2027     }
2028   }
2029 }
2030 
2031 /** \} */
2032 
2033 /* -------------------------------------------------------------------- */
2034 /** \name Bone Vector, Roll Conversion
2035  *
2036  * Used for Objects and Pose Channels, since both can have multiple rotation representations.
2037  *
2038  * How it Works
2039  * ============
2040  *
2041  * This is the bone transformation trick; they're hierarchical so each bone(b)
2042  * is in the coord system of bone(b-1):
2043  *
2044  * arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
2045  *
2046  * -> yoffs is just the y axis translation in parent's coord system
2047  * -> d_root is the translation of the bone root, also in parent's coord system
2048  *
2049  * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
2050  *
2051  * we then - in init deform - store the deform in chan_mat, such that:
2052  *
2053  * pose_mat(b)= arm_mat(b) * chan_mat(b)
2054  *
2055  * \{ */
2056 
2057 /* Computes vector and roll based on a rotation.
2058  * "mat" must contain only a rotation, and no scaling. */
mat3_to_vec_roll(const float mat[3][3],float r_vec[3],float * r_roll)2059 void mat3_to_vec_roll(const float mat[3][3], float r_vec[3], float *r_roll)
2060 {
2061   if (r_vec) {
2062     copy_v3_v3(r_vec, mat[1]);
2063   }
2064 
2065   if (r_roll) {
2066     mat3_vec_to_roll(mat, mat[1], r_roll);
2067   }
2068 }
2069 
2070 /* Computes roll around the vector that best approximates the matrix.
2071  * If vec is the Y vector from purely rotational mat, result should be exact. */
mat3_vec_to_roll(const float mat[3][3],const float vec[3],float * r_roll)2072 void mat3_vec_to_roll(const float mat[3][3], const float vec[3], float *r_roll)
2073 {
2074   float vecmat[3][3], vecmatinv[3][3], rollmat[3][3], q[4];
2075 
2076   /* Compute the orientation relative to the vector with zero roll. */
2077   vec_roll_to_mat3(vec, 0.0f, vecmat);
2078   invert_m3_m3(vecmatinv, vecmat);
2079   mul_m3_m3m3(rollmat, vecmatinv, mat);
2080 
2081   /* Extract the twist angle as the roll value. */
2082   mat3_to_quat(q, rollmat);
2083 
2084   *r_roll = quat_split_swing_and_twist(q, 1, NULL, NULL);
2085 }
2086 
2087 /* Calculates the rest matrix of a bone based on its vector and a roll around that vector. */
2088 /**
2089  * Given `v = (v.x, v.y, v.z)` our (normalized) bone vector, we want the rotation matrix M
2090  * from the Y axis (so that `M * (0, 1, 0) = v`).
2091  * - The rotation axis a lays on XZ plane, and it is orthonormal to v,
2092  *   hence to the projection of v onto XZ plane.
2093  * - `a = (v.z, 0, -v.x)`
2094  *
2095  * We know a is eigenvector of M (so M * a = a).
2096  * Finally, we have w, such that M * w = (0, 1, 0)
2097  * (i.e. the vector that will be aligned with Y axis once transformed).
2098  * We know w is symmetric to v by the Y axis.
2099  * - `w = (-v.x, v.y, -v.z)`
2100  *
2101  * Solving this, we get (x, y and z being the components of v):
2102  * <pre>
2103  *     ┌ (x^2 * y + z^2) / (x^2 + z^2),   x,   x * z * (y - 1) / (x^2 + z^2) ┐
2104  * M = │  x * (y^2 - 1)  / (x^2 + z^2),   y,    z * (y^2 - 1)  / (x^2 + z^2) │
2105  *     └ x * z * (y - 1) / (x^2 + z^2),   z,   (x^2 + z^2 * y) / (x^2 + z^2) ┘
2106  * </pre>
2107  *
2108  * This is stable as long as v (the bone) is not too much aligned with +/-Y
2109  * (i.e. x and z components are not too close to 0).
2110  *
2111  * Since v is normalized, we have `x^2 + y^2 + z^2 = 1`,
2112  * hence `x^2 + z^2 = 1 - y^2 = (1 - y)(1 + y)`.
2113  *
2114  * This allows to simplifies M like this:
2115  * <pre>
2116  *     ┌ 1 - x^2 / (1 + y),   x,     -x * z / (1 + y) ┐
2117  * M = │                -x,   y,                   -z │
2118  *     └  -x * z / (1 + y),   z,    1 - z^2 / (1 + y) ┘
2119  * </pre>
2120  *
2121  * Written this way, we see the case v = +Y is no more a singularity.
2122  * The only one
2123  * remaining is the bone being aligned with -Y.
2124  *
2125  * Let's handle
2126  * the asymptotic behavior when bone vector is reaching the limit of y = -1.
2127  * Each of the four corner elements can vary from -1 to 1,
2128  * depending on the axis a chosen for doing the rotation.
2129  * And the "rotation" here is in fact established by mirroring XZ plane by that given axis,
2130  * then inversing the Y-axis.
2131  * For sufficiently small x and z, and with y approaching -1,
2132  * all elements but the four corner ones of M will degenerate.
2133  * So let's now focus on these corner elements.
2134  *
2135  * We rewrite M so that it only contains its four corner elements,
2136  * and combine the `1 / (1 + y)` factor:
2137  * <pre>
2138  *                    ┌ 1 + y - x^2,        -x * z ┐
2139  * M* = 1 / (1 + y) * │                            │
2140  *                    └      -x * z,   1 + y - z^2 ┘
2141  * </pre>
2142  *
2143  * When y is close to -1, computing 1 / (1 + y) will cause severe numerical instability,
2144  * so we ignore it and normalize M instead.
2145  * We know `y^2 = 1 - (x^2 + z^2)`, and `y < 0`, hence `y = -sqrt(1 - (x^2 + z^2))`.
2146  *
2147  * Since x and z are both close to 0, we apply the binomial expansion to the first order:
2148  * `y = -sqrt(1 - (x^2 + z^2)) = -1 + (x^2 + z^2) / 2`. Which gives:
2149  * <pre>
2150  *                        ┌  z^2 - x^2,  -2 * x * z ┐
2151  * M* = 1 / (x^2 + z^2) * │                         │
2152  *                        └ -2 * x * z,   x^2 - z^2 ┘
2153  * </pre>
2154  */
vec_roll_to_mat3_normalized(const float nor[3],const float roll,float r_mat[3][3])2155 void vec_roll_to_mat3_normalized(const float nor[3], const float roll, float r_mat[3][3])
2156 {
2157 #define THETA_THRESHOLD_NEGY 1.0e-9f
2158 #define THETA_THRESHOLD_NEGY_CLOSE 1.0e-5f
2159 
2160   float theta;
2161   float rMatrix[3][3], bMatrix[3][3];
2162 
2163   BLI_ASSERT_UNIT_V3(nor);
2164 
2165   theta = 1.0f + nor[1];
2166 
2167   /* With old algo, 1.0e-13f caused T23954 and T31333, 1.0e-6f caused T27675 and T30438,
2168    * so using 1.0e-9f as best compromise.
2169    *
2170    * New algo is supposed much more precise, since less complex computations are performed,
2171    * but it uses two different threshold values...
2172    *
2173    * Note: When theta is close to zero, we have to check we do have non-null X/Z components as well
2174    *       (due to float precision errors, we can have nor = (0.0, 0.99999994, 0.0)...).
2175    */
2176   if (theta > THETA_THRESHOLD_NEGY_CLOSE || ((nor[0] || nor[2]) && theta > THETA_THRESHOLD_NEGY)) {
2177     /* nor is *not* -Y.
2178      * We got these values for free... so be happy with it... ;)
2179      */
2180     bMatrix[0][1] = -nor[0];
2181     bMatrix[1][0] = nor[0];
2182     bMatrix[1][1] = nor[1];
2183     bMatrix[1][2] = nor[2];
2184     bMatrix[2][1] = -nor[2];
2185     if (theta > THETA_THRESHOLD_NEGY_CLOSE) {
2186       /* If nor is far enough from -Y, apply the general case. */
2187       bMatrix[0][0] = 1 - nor[0] * nor[0] / theta;
2188       bMatrix[2][2] = 1 - nor[2] * nor[2] / theta;
2189       bMatrix[2][0] = bMatrix[0][2] = -nor[0] * nor[2] / theta;
2190     }
2191     else {
2192       /* If nor is too close to -Y, apply the special case. */
2193       theta = nor[0] * nor[0] + nor[2] * nor[2];
2194       bMatrix[0][0] = (nor[0] + nor[2]) * (nor[0] - nor[2]) / -theta;
2195       bMatrix[2][2] = -bMatrix[0][0];
2196       bMatrix[2][0] = bMatrix[0][2] = 2.0f * nor[0] * nor[2] / theta;
2197     }
2198   }
2199   else {
2200     /* If nor is -Y, simple symmetry by Z axis. */
2201     unit_m3(bMatrix);
2202     bMatrix[0][0] = bMatrix[1][1] = -1.0;
2203   }
2204 
2205   /* Make Roll matrix */
2206   axis_angle_normalized_to_mat3(rMatrix, nor, roll);
2207 
2208   /* Combine and output result */
2209   mul_m3_m3m3(r_mat, rMatrix, bMatrix);
2210 
2211 #undef THETA_THRESHOLD_NEGY
2212 #undef THETA_THRESHOLD_NEGY_CLOSE
2213 }
2214 
vec_roll_to_mat3(const float vec[3],const float roll,float r_mat[3][3])2215 void vec_roll_to_mat3(const float vec[3], const float roll, float r_mat[3][3])
2216 {
2217   float nor[3];
2218 
2219   normalize_v3_v3(nor, vec);
2220   vec_roll_to_mat3_normalized(nor, roll, r_mat);
2221 }
2222 
2223 /** \} */
2224 
2225 /* -------------------------------------------------------------------- */
2226 /** \name Armature Bone Matrix Calculation (Recursive)
2227  * \{ */
2228 
2229 /**
2230  * Recursive part, calculates rest-position of entire tree of children.
2231  * \note Used when exiting edit-mode too.
2232  */
BKE_armature_where_is_bone(Bone * bone,const Bone * bone_parent,const bool use_recursion)2233 void BKE_armature_where_is_bone(Bone *bone, const Bone *bone_parent, const bool use_recursion)
2234 {
2235   float vec[3];
2236 
2237   /* Bone Space */
2238   sub_v3_v3v3(vec, bone->tail, bone->head);
2239   bone->length = len_v3(vec);
2240   vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
2241 
2242   /* this is called on old file reading too... */
2243   if (bone->xwidth == 0.0f) {
2244     bone->xwidth = 0.1f;
2245     bone->zwidth = 0.1f;
2246     bone->segments = 1;
2247   }
2248 
2249   if (bone_parent) {
2250     float offs_bone[4][4];
2251     /* yoffs(b-1) + root(b) + bonemat(b) */
2252     BKE_bone_offset_matrix_get(bone, offs_bone);
2253 
2254     /* Compose the matrix for this bone  */
2255     mul_m4_m4m4(bone->arm_mat, bone_parent->arm_mat, offs_bone);
2256   }
2257   else {
2258     copy_m4_m3(bone->arm_mat, bone->bone_mat);
2259     copy_v3_v3(bone->arm_mat[3], bone->head);
2260   }
2261 
2262   /* and the kiddies */
2263   if (use_recursion) {
2264     bone_parent = bone;
2265     for (bone = bone->childbase.first; bone; bone = bone->next) {
2266       BKE_armature_where_is_bone(bone, bone_parent, use_recursion);
2267     }
2268   }
2269 }
2270 
2271 /* updates vectors and matrices on rest-position level, only needed
2272  * after editing armature itself, now only on reading file */
BKE_armature_where_is(bArmature * arm)2273 void BKE_armature_where_is(bArmature *arm)
2274 {
2275   Bone *bone;
2276 
2277   /* hierarchical from root to children */
2278   for (bone = arm->bonebase.first; bone; bone = bone->next) {
2279     BKE_armature_where_is_bone(bone, NULL, true);
2280   }
2281 }
2282 
2283 /** \} */
2284 
2285 /* -------------------------------------------------------------------- */
2286 /** \name Pose Rebuild
2287  * \{ */
2288 
2289 /* if bone layer is protected, copy the data from from->pose
2290  * when used with linked libraries this copies from the linked pose into the local pose */
pose_proxy_sync(Object * ob,Object * from,int layer_protected)2291 static void pose_proxy_sync(Object *ob, Object *from, int layer_protected)
2292 {
2293   bPose *pose = ob->pose, *frompose = from->pose;
2294   bPoseChannel *pchan, *pchanp;
2295   bConstraint *con;
2296   int error = 0;
2297 
2298   if (frompose == NULL) {
2299     return;
2300   }
2301 
2302   /* in some cases when rigs change, we cant synchronize
2303    * to avoid crashing check for possible errors here */
2304   for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2305     if (pchan->bone->layer & layer_protected) {
2306       if (BKE_pose_channel_find_name(frompose, pchan->name) == NULL) {
2307         CLOG_ERROR(&LOG,
2308                    "failed to sync proxy armature because '%s' is missing pose channel '%s'",
2309                    from->id.name,
2310                    pchan->name);
2311         error = 1;
2312       }
2313     }
2314   }
2315 
2316   if (error) {
2317     return;
2318   }
2319 
2320   /* clear all transformation values from library */
2321   BKE_pose_rest(frompose, false);
2322 
2323   /* copy over all of the proxy's bone groups */
2324   /* TODO for later
2325    * - implement 'local' bone groups as for constraints
2326    * Note: this isn't trivial, as bones reference groups by index not by pointer,
2327    *       so syncing things correctly needs careful attention */
2328   BLI_freelistN(&pose->agroups);
2329   BLI_duplicatelist(&pose->agroups, &frompose->agroups);
2330   pose->active_group = frompose->active_group;
2331 
2332   for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2333     pchanp = BKE_pose_channel_find_name(frompose, pchan->name);
2334 
2335     if (UNLIKELY(pchanp == NULL)) {
2336       /* happens for proxies that become invalid because of a missing link
2337        * for regular cases it shouldn't happen at all */
2338     }
2339     else if (pchan->bone->layer & layer_protected) {
2340       ListBase proxylocal_constraints = {NULL, NULL};
2341       bPoseChannel pchanw;
2342 
2343       /* copy posechannel to temp, but restore important pointers */
2344       pchanw = *pchanp;
2345       pchanw.bone = pchan->bone;
2346       pchanw.prev = pchan->prev;
2347       pchanw.next = pchan->next;
2348       pchanw.parent = pchan->parent;
2349       pchanw.child = pchan->child;
2350       pchanw.custom_tx = pchan->custom_tx;
2351       pchanw.bbone_prev = pchan->bbone_prev;
2352       pchanw.bbone_next = pchan->bbone_next;
2353 
2354       pchanw.mpath = pchan->mpath;
2355       pchan->mpath = NULL;
2356 
2357       /* Reset runtime data, we don't want to share that with the proxy. */
2358       BKE_pose_channel_runtime_reset_on_copy(&pchanw.runtime);
2359 
2360       /* this is freed so copy a copy, else undo crashes */
2361       if (pchanw.prop) {
2362         pchanw.prop = IDP_CopyProperty(pchanw.prop);
2363 
2364         /* use the values from the existing props */
2365         if (pchan->prop) {
2366           IDP_SyncGroupValues(pchanw.prop, pchan->prop);
2367         }
2368       }
2369 
2370       /* Constraints - proxy constraints are flushed... local ones are added after
2371        * 1: extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints.
2372        * 2: copy proxy-pchan's constraints on-to new.
2373        * 3: add extracted local constraints back on top.
2374        *
2375        * Note for BKE_constraints_copy:
2376        * When copying constraints, disable 'do_extern' otherwise
2377        * we get the libs direct linked in this blend.
2378        */
2379       BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints);
2380       BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false);
2381       BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
2382 
2383       /* constraints - set target ob pointer to own object */
2384       for (con = pchanw.constraints.first; con; con = con->next) {
2385         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
2386         ListBase targets = {NULL, NULL};
2387         bConstraintTarget *ct;
2388 
2389         if (cti && cti->get_constraint_targets) {
2390           cti->get_constraint_targets(con, &targets);
2391 
2392           for (ct = targets.first; ct; ct = ct->next) {
2393             if (ct->tar == from) {
2394               ct->tar = ob;
2395             }
2396           }
2397 
2398           if (cti->flush_constraint_targets) {
2399             cti->flush_constraint_targets(con, &targets, 0);
2400           }
2401         }
2402       }
2403 
2404       /* free stuff from current channel */
2405       BKE_pose_channel_free(pchan);
2406 
2407       /* copy data in temp back over to the cleaned-out (but still allocated) original channel */
2408       *pchan = pchanw;
2409       if (pchan->custom) {
2410         id_us_plus(&pchan->custom->id);
2411       }
2412     }
2413     else {
2414       /* always copy custom shape */
2415       pchan->custom = pchanp->custom;
2416       if (pchan->custom) {
2417         id_us_plus(&pchan->custom->id);
2418       }
2419       if (pchanp->custom_tx) {
2420         pchan->custom_tx = BKE_pose_channel_find_name(pose, pchanp->custom_tx->name);
2421       }
2422 
2423       /* ID-Property Syncing */
2424       {
2425         IDProperty *prop_orig = pchan->prop;
2426         if (pchanp->prop) {
2427           pchan->prop = IDP_CopyProperty(pchanp->prop);
2428           if (prop_orig) {
2429             /* copy existing values across when types match */
2430             IDP_SyncGroupValues(pchan->prop, prop_orig);
2431           }
2432         }
2433         else {
2434           pchan->prop = NULL;
2435         }
2436         if (prop_orig) {
2437           IDP_FreeProperty(prop_orig);
2438         }
2439       }
2440     }
2441   }
2442 }
2443 
rebuild_pose_bone(bPose * pose,Bone * bone,bPoseChannel * parchan,int counter)2444 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
2445 {
2446   bPoseChannel *pchan = BKE_pose_channel_verify(pose, bone->name); /* verify checks and/or adds */
2447 
2448   pchan->bone = bone;
2449   pchan->parent = parchan;
2450 
2451   counter++;
2452 
2453   for (bone = bone->childbase.first; bone; bone = bone->next) {
2454     counter = rebuild_pose_bone(pose, bone, pchan, counter);
2455     /* for quick detecting of next bone in chain, only b-bone uses it now */
2456     if (bone->flag & BONE_CONNECTED) {
2457       pchan->child = BKE_pose_channel_find_name(pose, bone->name);
2458     }
2459   }
2460 
2461   return counter;
2462 }
2463 
2464 /**
2465  * Clear pointers of object's pose
2466  * (needed in remap case, since we cannot always wait for a complete pose rebuild).
2467  */
BKE_pose_clear_pointers(bPose * pose)2468 void BKE_pose_clear_pointers(bPose *pose)
2469 {
2470   LISTBASE_FOREACH (bPoseChannel *, pchan, &pose->chanbase) {
2471     pchan->bone = NULL;
2472     pchan->child = NULL;
2473   }
2474 }
2475 
BKE_pose_remap_bone_pointers(bArmature * armature,bPose * pose)2476 void BKE_pose_remap_bone_pointers(bArmature *armature, bPose *pose)
2477 {
2478   LISTBASE_FOREACH (bPoseChannel *, pchan, &pose->chanbase) {
2479     pchan->bone = BKE_armature_find_bone_name(armature, pchan->name);
2480   }
2481 }
2482 
2483 /** Find the matching pose channel using the bone name, if not NULL. */
pose_channel_find_bone(bPose * pose,Bone * bone)2484 static bPoseChannel *pose_channel_find_bone(bPose *pose, Bone *bone)
2485 {
2486   return (bone != NULL) ? BKE_pose_channel_find_name(pose, bone->name) : NULL;
2487 }
2488 
2489 /** Update the links for the B-Bone handles from Bone data. */
BKE_pchan_rebuild_bbone_handles(bPose * pose,bPoseChannel * pchan)2490 void BKE_pchan_rebuild_bbone_handles(bPose *pose, bPoseChannel *pchan)
2491 {
2492   pchan->bbone_prev = pose_channel_find_bone(pose, pchan->bone->bbone_prev);
2493   pchan->bbone_next = pose_channel_find_bone(pose, pchan->bone->bbone_next);
2494 }
2495 
2496 /**
2497  * Only after leave editmode, duplicating, validating older files, library syncing.
2498  *
2499  * \note pose->flag is set for it.
2500  *
2501  * \param bmain: May be NULL, only used to tag depsgraph as being dirty...
2502  */
BKE_pose_rebuild(Main * bmain,Object * ob,bArmature * arm,const bool do_id_user)2503 void BKE_pose_rebuild(Main *bmain, Object *ob, bArmature *arm, const bool do_id_user)
2504 {
2505   Bone *bone;
2506   bPose *pose;
2507   bPoseChannel *pchan, *next;
2508   int counter = 0;
2509 
2510   /* only done here */
2511   if (ob->pose == NULL) {
2512     /* create new pose */
2513     ob->pose = MEM_callocN(sizeof(bPose), "new pose");
2514 
2515     /* set default settings for animviz */
2516     animviz_settings_init(&ob->pose->avs);
2517   }
2518   pose = ob->pose;
2519 
2520   /* clear */
2521   BKE_pose_clear_pointers(pose);
2522 
2523   /* first step, check if all channels are there */
2524   for (bone = arm->bonebase.first; bone; bone = bone->next) {
2525     counter = rebuild_pose_bone(pose, bone, NULL, counter);
2526   }
2527 
2528   /* and a check for garbage */
2529   for (pchan = pose->chanbase.first; pchan; pchan = next) {
2530     next = pchan->next;
2531     if (pchan->bone == NULL) {
2532       BKE_pose_channel_free_ex(pchan, do_id_user);
2533       BKE_pose_channels_hash_free(pose);
2534       BLI_freelinkN(&pose->chanbase, pchan);
2535     }
2536   }
2537 
2538   BKE_pose_channels_hash_make(pose);
2539 
2540   for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2541     /* Find the custom B-Bone handles. */
2542     BKE_pchan_rebuild_bbone_handles(pose, pchan);
2543     /* Re-validate that we are still using a valid pchan form custom transform. */
2544     /* Note that we could store pointers of freed pchan in a GSet to speed this up, however this is
2545      * supposed to be a rarely used feature, so for now assuming that always building that GSet
2546      * would be less optimal. */
2547     if (pchan->custom_tx != NULL && BLI_findindex(&pose->chanbase, pchan->custom_tx) == -1) {
2548       pchan->custom_tx = NULL;
2549     }
2550   }
2551 
2552   /* printf("rebuild pose %s, %d bones\n", ob->id.name, counter); */
2553 
2554   /* synchronize protected layers with proxy */
2555   /* HACK! To preserve 2.7x behavior that you always can pose even locked bones,
2556    * do not do any restoration if this is a COW temp copy! */
2557   /* Switched back to just NO_MAIN tag, for some reasons (c)
2558    * using COW tag was working this morning, but not anymore... */
2559   if (ob->proxy != NULL && (ob->id.tag & LIB_TAG_NO_MAIN) == 0) {
2560     BKE_object_copy_proxy_drivers(ob, ob->proxy);
2561     pose_proxy_sync(ob, ob->proxy, arm->layer_protected);
2562   }
2563 
2564   BKE_pose_update_constraint_flags(pose); /* for IK detection for example */
2565 
2566   pose->flag &= ~POSE_RECALC;
2567   pose->flag |= POSE_WAS_REBUILT;
2568 
2569   /* Rebuilding poses forces us to also rebuild the dependency graph,
2570    * since there is one node per pose/bone. */
2571   if (bmain != NULL) {
2572     DEG_relations_tag_update(bmain);
2573   }
2574 }
2575 
2576 /**
2577  * Ensures object's pose is rebuilt if needed.
2578  *
2579  * \param bmain: May be NULL, only used to tag depsgraph as being dirty...
2580  */
BKE_pose_ensure(Main * bmain,Object * ob,bArmature * arm,const bool do_id_user)2581 void BKE_pose_ensure(Main *bmain, Object *ob, bArmature *arm, const bool do_id_user)
2582 {
2583   BLI_assert(!ELEM(NULL, arm, ob));
2584   if (ob->type == OB_ARMATURE && ((ob->pose == NULL) || (ob->pose->flag & POSE_RECALC))) {
2585     BLI_assert(GS(arm->id.name) == ID_AR);
2586     BKE_pose_rebuild(bmain, ob, arm, do_id_user);
2587   }
2588 }
2589 
2590 /** \} */
2591 
2592 /* -------------------------------------------------------------------- */
2593 /** \name Pose Solver
2594  * \{ */
2595 
2596 /**
2597  * Convert the loc/rot/size to \a r_chanmat (typically #bPoseChannel.chan_mat).
2598  */
BKE_pchan_to_mat4(const bPoseChannel * pchan,float r_chanmat[4][4])2599 void BKE_pchan_to_mat4(const bPoseChannel *pchan, float r_chanmat[4][4])
2600 {
2601   float smat[3][3];
2602   float rmat[3][3];
2603   float tmat[3][3];
2604 
2605   /* get scaling matrix */
2606   size_to_mat3(smat, pchan->size);
2607 
2608   /* get rotation matrix */
2609   BKE_pchan_rot_to_mat3(pchan, rmat);
2610 
2611   /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2612   mul_m3_m3m3(tmat, rmat, smat);
2613   copy_m4_m3(r_chanmat, tmat);
2614 
2615   /* prevent action channels breaking chains */
2616   /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2617   if ((pchan->bone == NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2618     copy_v3_v3(r_chanmat[3], pchan->loc);
2619   }
2620 }
2621 
2622 /* loc/rot/size to mat4 */
2623 /* used in constraint.c too */
BKE_pchan_calc_mat(bPoseChannel * pchan)2624 void BKE_pchan_calc_mat(bPoseChannel *pchan)
2625 {
2626   /* this is just a wrapper around the copy of this function which calculates the matrix
2627    * and stores the result in any given channel
2628    */
2629   BKE_pchan_to_mat4(pchan, pchan->chan_mat);
2630 }
2631 
2632 /* calculate tail of posechannel */
BKE_pose_where_is_bone_tail(bPoseChannel * pchan)2633 void BKE_pose_where_is_bone_tail(bPoseChannel *pchan)
2634 {
2635   float vec[3];
2636 
2637   copy_v3_v3(vec, pchan->pose_mat[1]);
2638   mul_v3_fl(vec, pchan->bone->length);
2639   add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2640 }
2641 
2642 /* The main armature solver, does all constraints excluding IK */
2643 /* pchan is validated, as having bone and parent pointer
2644  * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2645  */
BKE_pose_where_is_bone(struct Depsgraph * depsgraph,Scene * scene,Object * ob,bPoseChannel * pchan,float ctime,bool do_extra)2646 void BKE_pose_where_is_bone(struct Depsgraph *depsgraph,
2647                             Scene *scene,
2648                             Object *ob,
2649                             bPoseChannel *pchan,
2650                             float ctime,
2651                             bool do_extra)
2652 {
2653   /* This gives a chan_mat with actions (ipos) results. */
2654   if (do_extra) {
2655     BKE_pchan_calc_mat(pchan);
2656   }
2657   else {
2658     unit_m4(pchan->chan_mat);
2659   }
2660 
2661   /* Construct the posemat based on PoseChannels, that we do before applying constraints. */
2662   /* pose_mat(b) = pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2663   BKE_armature_mat_bone_to_pose(pchan, pchan->chan_mat, pchan->pose_mat);
2664 
2665   /* Only rootbones get the cyclic offset (unless user doesn't want that). */
2666   /* XXX That could be a problem for snapping and other "reverse transform" features... */
2667   if (!pchan->parent) {
2668     if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0) {
2669       add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2670     }
2671   }
2672 
2673   if (do_extra) {
2674     /* Do constraints */
2675     if (pchan->constraints.first) {
2676       bConstraintOb *cob;
2677       float vec[3];
2678 
2679       /* make a copy of location of PoseChannel for later */
2680       copy_v3_v3(vec, pchan->pose_mat[3]);
2681 
2682       /* prepare PoseChannel for Constraint solving
2683        * - makes a copy of matrix, and creates temporary struct to use
2684        */
2685       cob = BKE_constraints_make_evalob(depsgraph, scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2686 
2687       /* Solve PoseChannel's Constraints */
2688 
2689       /* ctime doesn't alter objects. */
2690       BKE_constraints_solve(depsgraph, &pchan->constraints, cob, ctime);
2691 
2692       /* cleanup after Constraint Solving
2693        * - applies matrix back to pchan, and frees temporary struct used
2694        */
2695       BKE_constraints_clear_evalob(cob);
2696 
2697       /* prevent constraints breaking a chain */
2698       if (pchan->bone->flag & BONE_CONNECTED) {
2699         copy_v3_v3(pchan->pose_mat[3], vec);
2700       }
2701     }
2702   }
2703 
2704   /* calculate head */
2705   copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
2706   /* calculate tail */
2707   BKE_pose_where_is_bone_tail(pchan);
2708 }
2709 
2710 /* This only reads anim data from channels, and writes to channels */
2711 /* This is the only function adding poses */
BKE_pose_where_is(struct Depsgraph * depsgraph,Scene * scene,Object * ob)2712 void BKE_pose_where_is(struct Depsgraph *depsgraph, Scene *scene, Object *ob)
2713 {
2714   bArmature *arm;
2715   Bone *bone;
2716   bPoseChannel *pchan;
2717   float imat[4][4];
2718   float ctime;
2719 
2720   if (ob->type != OB_ARMATURE) {
2721     return;
2722   }
2723   arm = ob->data;
2724 
2725   if (ELEM(NULL, arm, scene)) {
2726     return;
2727   }
2728   /* WARNING! passing NULL bmain here means we won't tag depsgraph's as dirty -
2729    * hopefully this is OK. */
2730   BKE_pose_ensure(NULL, ob, arm, true);
2731 
2732   ctime = BKE_scene_frame_get(scene); /* not accurate... */
2733 
2734   /* In edit-mode or rest-position we read the data from the bones. */
2735   if (arm->edbo || (arm->flag & ARM_RESTPOS)) {
2736     for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2737       bone = pchan->bone;
2738       if (bone) {
2739         copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2740         copy_v3_v3(pchan->pose_head, bone->arm_head);
2741         copy_v3_v3(pchan->pose_tail, bone->arm_tail);
2742       }
2743     }
2744   }
2745   else {
2746     invert_m4_m4(ob->imat, ob->obmat); /* imat is needed */
2747 
2748     /* 1. clear flags */
2749     for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2750       pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
2751     }
2752 
2753     /* 2a. construct the IK tree (standard IK) */
2754     BIK_init_tree(depsgraph, scene, ob, ctime);
2755 
2756     /* 2b. construct the Spline IK trees
2757      * - this is not integrated as an IK plugin, since it should be able
2758      *   to function in conjunction with standard IK
2759      */
2760     BKE_pose_splineik_init_tree(scene, ob, ctime);
2761 
2762     /* 3. the main loop, channels are already hierarchical sorted from root to children */
2763     for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2764       /* 4a. if we find an IK root, we handle it separated */
2765       if (pchan->flag & POSE_IKTREE) {
2766         BIK_execute_tree(depsgraph, scene, ob, pchan, ctime);
2767       }
2768       /* 4b. if we find a Spline IK root, we handle it separated too */
2769       else if (pchan->flag & POSE_IKSPLINE) {
2770         BKE_splineik_execute_tree(depsgraph, scene, ob, pchan, ctime);
2771       }
2772       /* 5. otherwise just call the normal solver */
2773       else if (!(pchan->flag & POSE_DONE)) {
2774         BKE_pose_where_is_bone(depsgraph, scene, ob, pchan, ctime, 1);
2775       }
2776     }
2777     /* 6. release the IK tree */
2778     BIK_release_tree(scene, ob, ctime);
2779   }
2780 
2781   /* calculating deform matrices */
2782   for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2783     if (pchan->bone) {
2784       invert_m4_m4(imat, pchan->bone->arm_mat);
2785       mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
2786     }
2787   }
2788 }
2789 
2790 /** \} */
2791 
2792 /* -------------------------------------------------------------------- */
2793 /** \name Calculate Bounding Box (Armature & Pose)
2794  * \{ */
2795 
minmax_armature(Object * ob,float r_min[3],float r_max[3])2796 static int minmax_armature(Object *ob, float r_min[3], float r_max[3])
2797 {
2798   bPoseChannel *pchan;
2799 
2800   /* For now, we assume BKE_pose_where_is has already been called
2801    * (hence we have valid data in pachan). */
2802   for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2803     minmax_v3v3_v3(r_min, r_max, pchan->pose_head);
2804     minmax_v3v3_v3(r_min, r_max, pchan->pose_tail);
2805   }
2806 
2807   return (BLI_listbase_is_empty(&ob->pose->chanbase) == false);
2808 }
2809 
boundbox_armature(Object * ob)2810 static void boundbox_armature(Object *ob)
2811 {
2812   BoundBox *bb;
2813   float min[3], max[3];
2814 
2815   if (ob->runtime.bb == NULL) {
2816     ob->runtime.bb = MEM_callocN(sizeof(BoundBox), "Armature boundbox");
2817   }
2818   bb = ob->runtime.bb;
2819 
2820   INIT_MINMAX(min, max);
2821   if (!minmax_armature(ob, min, max)) {
2822     min[0] = min[1] = min[2] = -1.0f;
2823     max[0] = max[1] = max[2] = 1.0f;
2824   }
2825 
2826   BKE_boundbox_init_from_minmax(bb, min, max);
2827 
2828   bb->flag &= ~BOUNDBOX_DIRTY;
2829 }
2830 
BKE_armature_boundbox_get(Object * ob)2831 BoundBox *BKE_armature_boundbox_get(Object *ob)
2832 {
2833   boundbox_armature(ob);
2834 
2835   return ob->runtime.bb;
2836 }
2837 
BKE_pose_minmax(Object * ob,float r_min[3],float r_max[3],bool use_hidden,bool use_select)2838 bool BKE_pose_minmax(Object *ob, float r_min[3], float r_max[3], bool use_hidden, bool use_select)
2839 {
2840   bool changed = false;
2841 
2842   if (ob->pose) {
2843     bArmature *arm = ob->data;
2844     bPoseChannel *pchan;
2845 
2846     for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2847       /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2848        *     (editarmature.c:2592)... Skip in this case too! */
2849       if (pchan->bone && (!((use_hidden == false) && (PBONE_VISIBLE(arm, pchan->bone) == false)) &&
2850                           !((use_select == true) && ((pchan->bone->flag & BONE_SELECTED) == 0)))) {
2851         bPoseChannel *pchan_tx = (pchan->custom && pchan->custom_tx) ? pchan->custom_tx : pchan;
2852         BoundBox *bb_custom = ((pchan->custom) && !(arm->flag & ARM_NO_CUSTOM)) ?
2853                                   BKE_object_boundbox_get(pchan->custom) :
2854                                   NULL;
2855         if (bb_custom) {
2856           float mat[4][4], smat[4][4];
2857           scale_m4_fl(smat, PCHAN_CUSTOM_DRAW_SIZE(pchan));
2858           mul_m4_series(mat, ob->obmat, pchan_tx->pose_mat, smat);
2859           BKE_boundbox_minmax(bb_custom, mat, r_min, r_max);
2860         }
2861         else {
2862           float vec[3];
2863           mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_head);
2864           minmax_v3v3_v3(r_min, r_max, vec);
2865           mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_tail);
2866           minmax_v3v3_v3(r_min, r_max, vec);
2867         }
2868 
2869         changed = true;
2870       }
2871     }
2872   }
2873 
2874   return changed;
2875 }
2876 
2877 /** \} */
2878 
2879 /* -------------------------------------------------------------------- */
2880 /** \name Graph Evaluation
2881  * \{ */
2882 
BKE_armature_ik_solver_find_root(bPoseChannel * pchan,bKinematicConstraint * data)2883 bPoseChannel *BKE_armature_ik_solver_find_root(bPoseChannel *pchan, bKinematicConstraint *data)
2884 {
2885   bPoseChannel *rootchan = pchan;
2886   if (!(data->flag & CONSTRAINT_IK_TIP)) {
2887     /* Exclude tip from chain. */
2888     rootchan = rootchan->parent;
2889   }
2890   if (rootchan != NULL) {
2891     int segcount = 0;
2892     while (rootchan->parent) {
2893       /* Continue up chain, until we reach target number of items. */
2894       segcount++;
2895       if (segcount == data->rootbone) {
2896         break;
2897       }
2898       rootchan = rootchan->parent;
2899     }
2900   }
2901   return rootchan;
2902 }
2903 
BKE_armature_splineik_solver_find_root(bPoseChannel * pchan,bSplineIKConstraint * data)2904 bPoseChannel *BKE_armature_splineik_solver_find_root(bPoseChannel *pchan,
2905                                                      bSplineIKConstraint *data)
2906 {
2907   bPoseChannel *rootchan = pchan;
2908   int segcount = 0;
2909   BLI_assert(rootchan != NULL);
2910   while (rootchan->parent) {
2911     /* Continue up chain, until we reach target number of items. */
2912     segcount++;
2913     if (segcount == data->chainlen) {
2914       break;
2915     }
2916     rootchan = rootchan->parent;
2917   }
2918   return rootchan;
2919 }
2920 
2921 /** \} */
2922