4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * Contributor(s): Martin Poirier
22 * ***** END GPL LICENSE BLOCK *****
23 * autoarmature.c: Interface for automagically manipulating armature (retarget, created, ...)
35 #include "MEM_guardedalloc.h"
40 #include "DNA_action_types.h"
41 #include "DNA_armature_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_view3d_types.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_arithb.h"
51 #include "BLI_editVert.h"
52 #include "BLI_ghash.h"
53 #include "BLI_graph.h"
55 #include "BLI_threads.h"
57 #include "BDR_editobject.h"
59 #include "BKE_global.h"
60 #include "BKE_utildefines.h"
61 #include "BKE_constraint.h"
62 #include "BKE_armature.h"
64 #include "BIF_editarmature.h"
65 #include "BIF_retarget.h"
66 #include "BIF_space.h"
67 #include "BIF_toolbox.h"
72 #include "reeb.h" // FIX ME
75 /************ RIG RETARGET DATA STRUCTURES ***************/
77 typedef struct MemoNode {
82 typedef struct RetargetParam {
96 METHOD_BRUTE_FORCE = 0,
107 RigGraph *GLOBAL_RIGG = NULL;
109 /*******************************************************************************************************/
111 void *exec_retargetArctoArc(void *param);
113 static void RIG_calculateEdgeAngle(RigEdge *edge_first, RigEdge *edge_second);
116 #define SHAPE_LEVELS (SHAPE_RADIX * SHAPE_RADIX)
118 /*********************************** EDITBONE UTILS ****************************************************/
120 int countEditBoneChildren(ListBase *list, EditBone *parent)
125 for (ebone = list->first; ebone; ebone = ebone->next)
127 if (ebone->parent == parent)
136 EditBone* nextEditBoneChild(ListBase *list, EditBone *parent, int n)
140 for (ebone = list->first; ebone; ebone = ebone->next)
142 if (ebone->parent == parent)
155 void getEditBoneRollUpAxis(EditBone *bone, float roll, float up_axis[3])
157 float mat[3][3], nor[3];
159 VecSubf(nor, bone->tail, bone->head);
161 vec_roll_to_mat3(nor, roll, mat);
162 VECCOPY(up_axis, mat[2]);
165 float rollBoneByQuatAligned(EditBone *bone, float old_up_axis[3], float quat[4], float qroll[4], float aligned_axis[3])
167 float nor[3], new_up_axis[3], x_axis[3], z_axis[3];
169 VECCOPY(new_up_axis, old_up_axis);
170 QuatMulVecf(quat, new_up_axis);
172 VecSubf(nor, bone->tail, bone->head);
174 Crossf(x_axis, nor, aligned_axis);
175 Crossf(z_axis, x_axis, nor);
177 Normalize(new_up_axis);
181 if (Inpf(new_up_axis, x_axis) < 0)
186 if (Inpf(new_up_axis, z_axis) < 0)
191 if (NormalizedVecAngle2(x_axis, new_up_axis) < NormalizedVecAngle2(z_axis, new_up_axis))
193 RotationBetweenVectorsToQuat(qroll, new_up_axis, x_axis); /* set roll rotation quat */
194 return rollBoneToVector(bone, x_axis);
198 RotationBetweenVectorsToQuat(qroll, new_up_axis, z_axis); /* set roll rotation quat */
199 return rollBoneToVector(bone, z_axis);
203 float rollBoneByQuat(EditBone *bone, float old_up_axis[3], float quat[4])
205 float new_up_axis[3];
207 VECCOPY(new_up_axis, old_up_axis);
208 QuatMulVecf(quat, new_up_axis);
210 return rollBoneToVector(bone, new_up_axis);
213 /************************************ DESTRUCTORS ******************************************************/
215 void RIG_freeRigArc(BArc *arc)
217 BLI_freelistN(&((RigArc*)arc)->edges);
220 void RIG_freeRigGraph(BGraph *rg)
222 RigGraph *rigg = (RigGraph*)rg;
227 BLI_destroy_worker(rigg->worker);
232 REEB_freeGraph(rigg->link_mesh);
235 for (arc = rg->arcs.first; arc; arc = arc->next)
239 BLI_freelistN(&rg->arcs);
241 for (node = rg->nodes.first; node; node = node->next)
243 BLI_freeNode(rg, (BNode*)node);
245 BLI_freelistN(&rg->nodes);
247 BLI_freelistN(&rigg->controls);
249 BLI_ghash_free(rigg->bones_map, NULL, NULL);
250 BLI_ghash_free(rigg->controls_map, NULL, NULL);
252 if (rigg->editbones != &G.edbo)
254 BLI_freelistN(rigg->editbones);
255 MEM_freeN(rigg->editbones);
261 /************************************* ALLOCATORS ******************************************************/
263 static RigGraph *newRigGraph()
268 rg = MEM_callocN(sizeof(RigGraph), "rig graph");
272 rg->bones_map = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
273 rg->controls_map = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
275 rg->free_arc = RIG_freeRigArc;
276 rg->free_node = NULL;
279 if(G.scene->r.mode & R_FIXED_THREADS)
281 totthread = G.scene->r.threads;
285 totthread = BLI_system_thread_count();
288 rg->worker = BLI_create_worker(exec_retargetArctoArc, totthread, 20); /* fix number of threads */
294 static RigArc *newRigArc(RigGraph *rg)
298 arc = MEM_callocN(sizeof(RigArc), "rig arc");
300 BLI_addtail(&rg->arcs, arc);
305 static RigControl *newRigControl(RigGraph *rg)
309 ctrl = MEM_callocN(sizeof(RigControl), "rig control");
311 BLI_addtail(&rg->controls, ctrl);
316 static RigNode *newRigNodeHead(RigGraph *rg, RigArc *arc, float p[3])
319 node = MEM_callocN(sizeof(RigNode), "rig node");
320 BLI_addtail(&rg->nodes, node);
331 static void addRigNodeHead(RigGraph *rg, RigArc *arc, RigNode *node)
338 static RigNode *newRigNode(RigGraph *rg, float p[3])
341 node = MEM_callocN(sizeof(RigNode), "rig node");
342 BLI_addtail(&rg->nodes, node);
351 static RigNode *newRigNodeTail(RigGraph *rg, RigArc *arc, float p[3])
353 RigNode *node = newRigNode(rg, p);
361 static void RIG_appendEdgeToArc(RigArc *arc, RigEdge *edge)
363 BLI_addtail(&arc->edges, edge);
365 if (edge->prev == NULL)
367 VECCOPY(edge->head, arc->head->p);
371 RigEdge *last_edge = edge->prev;
372 VECCOPY(edge->head, last_edge->tail);
373 RIG_calculateEdgeAngle(last_edge, edge);
376 edge->length = VecLenf(edge->head, edge->tail);
378 arc->length += edge->length;
383 static void RIG_addEdgeToArc(RigArc *arc, float tail[3], EditBone *bone)
387 edge = MEM_callocN(sizeof(RigEdge), "rig edge");
389 VECCOPY(edge->tail, tail);
394 getEditBoneRollUpAxis(bone, bone->roll, edge->up_axis);
397 RIG_appendEdgeToArc(arc, edge);
399 /************************************** CLONING TEMPLATES **********************************************/
401 static RigControl *cloneControl(RigGraph *rg, RigControl *src_ctrl, GHash *ptr_hash)
405 ctrl = newRigControl(rg);
407 VECCOPY(ctrl->head, src_ctrl->head);
408 VECCOPY(ctrl->tail, src_ctrl->tail);
409 VECCOPY(ctrl->up_axis, src_ctrl->up_axis);
410 VECCOPY(ctrl->offset, src_ctrl->offset);
412 ctrl->flag = src_ctrl->flag;
414 ctrl->bone = duplicateEditBone(src_ctrl->bone, rg->editbones, rg->ob);
415 ctrl->bone->flag &= ~(BONE_SELECTED|BONE_ROOTSEL|BONE_TIPSEL);
416 BLI_ghash_insert(ptr_hash, src_ctrl->bone, ctrl->bone);
418 ctrl->link = src_ctrl->link;
423 static RigArc *cloneArc(RigGraph *rg, RigArc *src_arc, GHash *ptr_hash)
430 arc->head = BLI_ghash_lookup(ptr_hash, src_arc->head);
431 arc->tail = BLI_ghash_lookup(ptr_hash, src_arc->tail);
436 arc->length = src_arc->length;
438 arc->count = src_arc->count;
440 for (src_edge = src_arc->edges.first; src_edge; src_edge = src_edge->next)
444 edge = MEM_callocN(sizeof(RigEdge), "rig edge");
446 VECCOPY(edge->head, src_edge->head);
447 VECCOPY(edge->tail, src_edge->tail);
448 VECCOPY(edge->up_axis, src_edge->up_axis);
450 edge->length = src_edge->length;
451 edge->angle = src_edge->angle;
453 if (src_edge->bone != NULL)
455 edge->bone = duplicateEditBone(src_edge->bone, rg->editbones, rg->ob);
456 edge->bone->flag &= ~(BONE_SELECTED|BONE_ROOTSEL|BONE_TIPSEL);
457 BLI_ghash_insert(ptr_hash, src_edge->bone, edge->bone);
460 BLI_addtail(&arc->edges, edge);
466 static RigGraph *cloneRigGraph(RigGraph *src)
474 ptr_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
479 rg->editbones = src->editbones;
481 preEditBoneDuplicate(rg->editbones); /* prime bones for duplication */
484 for (node = src->nodes.first; node; node = node->next)
486 RigNode *cloned_node = newRigNode(rg, node->p);
487 BLI_ghash_insert(ptr_hash, node, cloned_node);
490 rg->head = BLI_ghash_lookup(ptr_hash, src->head);
493 for (arc = src->arcs.first; arc; arc = arc->next)
495 cloneArc(rg, arc, ptr_hash);
499 for (ctrl = src->controls.first; ctrl; ctrl = ctrl->next)
501 cloneControl(rg, ctrl, ptr_hash);
504 /* Relink bones properly */
505 for (arc = rg->arcs.first; arc; arc = arc->next)
509 for (edge = arc->edges.first; edge; edge = edge->next)
511 if (edge->bone != NULL)
515 updateDuplicateSubtarget(edge->bone, rg->ob);
517 bone = BLI_ghash_lookup(ptr_hash, edge->bone->parent);
521 edge->bone->parent = bone;
527 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
531 updateDuplicateSubtarget(ctrl->bone, rg->ob);
533 bone = BLI_ghash_lookup(ptr_hash, ctrl->bone->parent);
537 ctrl->bone->parent = bone;
540 ctrl->link = BLI_ghash_lookup(ptr_hash, ctrl->link);
543 BLI_ghash_free(ptr_hash, NULL, NULL);
549 /*******************************************************************************************************/
551 static void RIG_calculateEdgeAngle(RigEdge *edge_first, RigEdge *edge_second)
553 float vec_first[3], vec_second[3];
555 VecSubf(vec_first, edge_first->tail, edge_first->head);
556 VecSubf(vec_second, edge_second->tail, edge_second->head);
558 Normalize(vec_first);
559 Normalize(vec_second);
561 edge_first->angle = saacos(Inpf(vec_first, vec_second));
564 /************************************ CONTROL BONES ****************************************************/
566 static void RIG_addControlBone(RigGraph *rg, EditBone *bone)
568 RigControl *ctrl = newRigControl(rg);
570 VECCOPY(ctrl->head, bone->head);
571 VECCOPY(ctrl->tail, bone->tail);
572 getEditBoneRollUpAxis(bone, bone->roll, ctrl->up_axis);
574 BLI_ghash_insert(rg->controls_map, bone->name, ctrl);
577 static int RIG_parentControl(RigControl *ctrl, EditBone *link)
584 VecSubf(offset, ctrl->bone->head, link->head);
586 /* if root matches, check for direction too */
587 if (Inpf(offset, offset) < 0.0001)
589 float vbone[3], vparent[3];
591 flag |= RIG_CTRL_FIT_ROOT;
593 VecSubf(vbone, ctrl->bone->tail, ctrl->bone->head);
594 VecSubf(vparent, link->tail, link->head);
596 /* test for opposite direction */
597 if (Inpf(vbone, vparent) > 0)
602 Crossf(nor, vbone, vparent);
604 len = Inpf(nor, nor);
607 flag |= RIG_CTRL_FIT_BONE;
612 /* Bail out if old one is automatically better */
613 if (flag < ctrl->flag)
618 /* if there's already a link
619 * overwrite only if new link is higher in the chain */
620 if (ctrl->link && flag == ctrl->flag)
622 EditBone *bone = NULL;
624 for (bone = ctrl->link; bone; bone = bone->parent)
626 /* if link is in the chain, break and use that one */
633 /* not in chain, don't update link */
644 VECCOPY(ctrl->offset, offset);
652 static void RIG_reconnectControlBones(RigGraph *rg)
657 /* first pass, link to deform bones */
658 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
664 /* DO SOME MAGIC HERE */
665 for (pchan= rg->ob->pose->chanbase.first; pchan; pchan= pchan->next)
667 for (con= pchan->constraints.first; con; con= con->next)
669 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
670 ListBase targets = {NULL, NULL};
671 bConstraintTarget *ct;
673 /* constraint targets */
674 if (cti && cti->get_constraint_targets)
676 cti->get_constraint_targets(con, &targets);
678 for (ct= targets.first; ct; ct= ct->next)
680 if ((ct->tar == rg->ob) && strcmp(ct->subtarget, ctrl->bone->name) == 0)
682 /* SET bone link to bone corresponding to pchan */
683 EditBone *link = BLI_ghash_lookup(rg->bones_map, pchan->name);
685 found = RIG_parentControl(ctrl, link);
689 if (cti->flush_constraint_targets)
690 cti->flush_constraint_targets(con, &targets, 0);
695 /* if not found yet, check parent */
698 if (ctrl->bone->parent)
700 /* make sure parent is a deforming bone
703 EditBone *link = BLI_ghash_lookup(rg->bones_map, ctrl->bone->parent->name);
705 found = RIG_parentControl(ctrl, link);
708 /* check if bone is not superposed on another one */
711 RigArc *best_arc = NULL;
712 EditBone *link = NULL;
714 for (arc = rg->arcs.first; arc; arc = arc->next)
717 for (edge = arc->edges.first; edge; edge = edge->next)
723 fit = VecLenf(ctrl->bone->head, edge->bone->head) < 0.0001;
724 fit = fit || VecLenf(ctrl->bone->tail, edge->bone->tail) < 0.0001;
728 /* pick the bone on the arc with the lowest symmetry level
729 * means you connect control to the trunk of the skeleton */
730 if (best_arc == NULL || arc->symmetry_level < best_arc->symmetry_level)
740 found = RIG_parentControl(ctrl, link);
744 /* if not found yet, check child */
748 RigArc *best_arc = NULL;
749 EditBone *link = NULL;
751 for (arc = rg->arcs.first; arc; arc = arc->next)
754 for (edge = arc->edges.first; edge; edge = edge->next)
756 if (edge->bone && edge->bone->parent == ctrl->bone)
758 /* pick the bone on the arc with the lowest symmetry level
759 * means you connect control to the trunk of the skeleton */
760 if (best_arc == NULL || arc->symmetry_level < best_arc->symmetry_level)
769 found = RIG_parentControl(ctrl, link);
775 /* second pass, make chains in control bones */
780 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
782 /* if control is not linked yet */
783 if (ctrl->link == NULL)
787 RigControl *ctrl_parent = NULL;
788 RigControl *ctrl_child;
791 if (ctrl->bone->parent)
793 ctrl_parent = BLI_ghash_lookup(rg->controls_map, ctrl->bone->parent->name);
796 /* check constraints first */
798 /* DO SOME MAGIC HERE */
799 for (pchan= rg->ob->pose->chanbase.first; pchan; pchan= pchan->next)
801 for (con= pchan->constraints.first; con; con= con->next)
803 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
804 ListBase targets = {NULL, NULL};
805 bConstraintTarget *ct;
807 /* constraint targets */
808 if (cti && cti->get_constraint_targets)
810 cti->get_constraint_targets(con, &targets);
812 for (ct= targets.first; ct; ct= ct->next)
814 if ((ct->tar == rg->ob) && strcmp(ct->subtarget, ctrl->bone->name) == 0)
816 /* SET bone link to ctrl corresponding to pchan */
817 RigControl *link = BLI_ghash_lookup(rg->controls_map, pchan->name);
819 /* if owner is a control bone, link with it */
820 if (link && link->link)
822 printf("%s -constraint- %s\n", ctrl->bone->name, link->bone->name);
823 RIG_parentControl(ctrl, link->bone);
830 if (cti->flush_constraint_targets)
831 cti->flush_constraint_targets(con, &targets, 0);
838 /* check if parent is already linked */
839 if (ctrl_parent && ctrl_parent->link)
841 printf("%s -parent- %s\n", ctrl->bone->name, ctrl_parent->bone->name);
842 RIG_parentControl(ctrl, ctrl_parent->bone);
848 for (ctrl_child = rg->controls.first; ctrl_child; ctrl_child = ctrl_child->next)
850 /* if a child is linked, link to that one */
851 if (ctrl_child->link && ctrl_child->bone->parent == ctrl->bone)
853 printf("%s -child- %s\n", ctrl->bone->name, ctrl_child->bone->name);
854 RIG_parentControl(ctrl, ctrl_child->bone);
867 /*******************************************************************************************************/
869 static void RIG_joinArcs(RigGraph *rg, RigNode *node, RigArc *joined_arc1, RigArc *joined_arc2)
871 RigEdge *edge, *next_edge;
873 /* ignore cases where joint is at start or end */
874 if (joined_arc1->head == joined_arc2->head || joined_arc1->tail == joined_arc2->tail)
879 /* swap arcs to make sure arc1 is before arc2 */
880 if (joined_arc1->head == joined_arc2->tail)
882 RigArc *tmp = joined_arc1;
883 joined_arc1 = joined_arc2;
887 for (edge = joined_arc2->edges.first; edge; edge = next_edge)
889 next_edge = edge->next;
891 RIG_appendEdgeToArc(joined_arc1, edge);
894 joined_arc1->tail = joined_arc2->tail;
896 joined_arc2->edges.first = joined_arc2->edges.last = NULL;
898 BLI_removeArc((BGraph*)rg, (BArc*)joined_arc2);
900 BLI_removeNode((BGraph*)rg, (BNode*)node);
903 static void RIG_removeNormalNodes(RigGraph *rg)
905 RigNode *node, *next_node;
907 for (node = rg->nodes.first; node; node = next_node)
909 next_node = node->next;
911 if (node->degree == 2)
913 RigArc *arc, *joined_arc1 = NULL, *joined_arc2 = NULL;
915 for (arc = rg->arcs.first; arc; arc = arc->next)
917 if (arc->head == node || arc->tail == node)
919 if (joined_arc1 == NULL)
931 RIG_joinArcs(rg, node, joined_arc1, joined_arc2);
936 static void RIG_removeUneededOffsets(RigGraph *rg)
940 for (arc = rg->arcs.first; arc; arc = arc->next)
942 RigEdge *first_edge, *last_edge;
944 first_edge = arc->edges.first;
945 last_edge = arc->edges.last;
947 if (first_edge->bone == NULL)
949 if (first_edge->bone == NULL && VecLenf(first_edge->tail, arc->head->p) <= 0.001)
951 BLI_remlink(&arc->edges, first_edge);
952 MEM_freeN(first_edge);
954 else if (arc->head->degree == 1)
956 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, first_edge->tail, 0.001);
960 BLI_remlink(&arc->edges, first_edge);
961 MEM_freeN(first_edge);
962 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->head);
966 RigEdge *next_edge = first_edge->next;
970 BLI_remlink(&arc->edges, first_edge);
971 MEM_freeN(first_edge);
973 VECCOPY(arc->head->p, next_edge->head);
979 /* check if all arc connected start with a null edge */
981 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
983 if (other_arc != arc)
986 if (other_arc->head == arc->head)
988 test_edge = other_arc->edges.first;
990 if (test_edge->bone != NULL)
995 else if (other_arc->tail == arc->head)
997 test_edge = other_arc->edges.last;
999 if (test_edge->bone != NULL)
1007 if (other_arc == NULL)
1009 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, first_edge->tail, 0.001);
1013 /* remove null edge in other arcs too */
1014 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1016 if (other_arc != arc)
1019 if (other_arc->head == arc->head)
1021 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)other_arc, (BNode*)new_node, (BNode*)other_arc->head);
1022 test_edge = other_arc->edges.first;
1023 BLI_remlink(&other_arc->edges, test_edge);
1024 MEM_freeN(test_edge);
1026 else if (other_arc->tail == arc->head)
1028 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)other_arc, (BNode*)new_node, (BNode*)other_arc->tail);
1029 test_edge = other_arc->edges.last;
1030 BLI_remlink(&other_arc->edges, test_edge);
1031 MEM_freeN(test_edge);
1036 BLI_remlink(&arc->edges, first_edge);
1037 MEM_freeN(first_edge);
1038 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->head);
1042 RigEdge *next_edge = first_edge->next;
1046 BLI_remlink(&arc->edges, first_edge);
1047 MEM_freeN(first_edge);
1049 VECCOPY(arc->head->p, next_edge->head);
1051 /* remove null edge in other arcs too */
1052 for (other_arc = rg->arcs.first; other_arc; other_arc = other_arc->next)
1054 if (other_arc != arc)
1057 if (other_arc->head == arc->head)
1059 test_edge = other_arc->edges.first;
1060 BLI_remlink(&other_arc->edges, test_edge);
1061 MEM_freeN(test_edge);
1063 else if (other_arc->tail == arc->head)
1065 test_edge = other_arc->edges.last;
1066 BLI_remlink(&other_arc->edges, test_edge);
1067 MEM_freeN(test_edge);
1077 if (last_edge->bone == NULL)
1079 if (VecLenf(last_edge->head, arc->tail->p) <= 0.001)
1081 BLI_remlink(&arc->edges, last_edge);
1082 MEM_freeN(last_edge);
1084 else if (arc->tail->degree == 1)
1086 RigNode *new_node = (RigNode*)BLI_FindNodeByPosition((BGraph*)rg, last_edge->head, 0.001);
1090 RigEdge *previous_edge = last_edge->prev;
1092 BLI_remlink(&arc->edges, last_edge);
1093 MEM_freeN(last_edge);
1094 BLI_replaceNodeInArc((BGraph*)rg, (BArc*)arc, (BNode*)new_node, (BNode*)arc->tail);
1096 /* set previous angle to 0, since there's no following edges */
1099 previous_edge->angle = 0;
1104 RigEdge *previous_edge = last_edge->prev;
1108 BLI_remlink(&arc->edges, last_edge);
1109 MEM_freeN(last_edge);
1111 VECCOPY(arc->tail->p, previous_edge->tail);
1112 previous_edge->angle = 0;
1120 static void RIG_arcFromBoneChain(RigGraph *rg, ListBase *list, EditBone *root_bone, RigNode *starting_node, int selected)
1122 EditBone *bone, *last_bone = root_bone;
1124 int contain_head = 0;
1126 for(bone = root_bone; bone; bone = nextEditBoneChild(list, bone, 0))
1130 if (selected == 0 || (bone->flag & BONE_SELECTED))
1132 if ((bone->flag & BONE_NO_DEFORM) == 0)
1134 BLI_ghash_insert(rg->bones_map, bone->name, bone);
1138 arc = newRigArc(rg);
1140 if (starting_node == NULL)
1142 starting_node = newRigNodeHead(rg, arc, root_bone->head);
1146 addRigNodeHead(rg, arc, starting_node);
1150 if (bone->parent && (bone->flag & BONE_CONNECTED) == 0)
1152 RIG_addEdgeToArc(arc, bone->head, NULL);
1155 RIG_addEdgeToArc(arc, bone->tail, bone);
1159 if (strcmp(bone->name, "head") == 0)
1164 else if ((bone->flag & BONE_EDITMODE_LOCKED) == 0) /* ignore locked bones */
1166 RIG_addControlBone(rg, bone);
1170 nb_children = countEditBoneChildren(list, bone);
1171 if (nb_children > 1)
1173 RigNode *end_node = NULL;
1178 end_node = newRigNodeTail(rg, arc, bone->tail);
1182 end_node = newRigNode(rg, bone->tail);
1185 for (i = 0; i < nb_children; i++)
1187 root_bone = nextEditBoneChild(list, bone, i);
1188 RIG_arcFromBoneChain(rg, list, root_bone, end_node, selected);
1191 /* arc ends here, break */
1196 /* If the loop exited without forking */
1197 if (arc != NULL && bone == NULL)
1199 newRigNodeTail(rg, arc, last_bone->tail);
1204 rg->head = arc->tail;
1208 /*******************************************************************************************************/
1209 static void RIG_findHead(RigGraph *rg)
1211 if (rg->head == NULL)
1213 if (BLI_countlist(&rg->arcs) == 1)
1215 RigArc *arc = rg->arcs.first;
1217 rg->head = (RigNode*)arc->head;
1223 for (arc = rg->arcs.first; arc; arc = arc->next)
1225 RigEdge *edge = arc->edges.last;
1227 if (edge->bone->flag & (BONE_TIPSEL|BONE_SELECTED))
1229 rg->head = arc->tail;
1235 if (rg->head == NULL)
1237 rg->head = rg->nodes.first;
1242 /*******************************************************************************************************/
1244 void RIG_printNode(RigNode *node, char name[])
1246 printf("%s %p %i <%0.3f, %0.3f, %0.3f>\n", name, node, node->degree, node->p[0], node->p[1], node->p[2]);
1248 if (node->symmetry_flag & SYM_TOPOLOGICAL)
1250 if (node->symmetry_flag & SYM_AXIAL)
1251 printf("Symmetry AXIAL\n");
1252 else if (node->symmetry_flag & SYM_RADIAL)
1253 printf("Symmetry RADIAL\n");
1255 printvecf("symmetry axis", node->symmetry_axis);
1259 void RIG_printArcBones(RigArc *arc)
1263 for (edge = arc->edges.first; edge; edge = edge->next)
1266 printf("%s ", edge->bone->name);
1273 void RIG_printCtrl(RigControl *ctrl, char *indent)
1277 printf("%sBone: %s\n", indent, ctrl->bone->name);
1278 printf("%sLink: %s\n", indent, ctrl->link ? ctrl->link->name : "!NONE!");
1280 sprintf(text, "%soffset", indent);
1281 printvecf(text, ctrl->offset);
1283 printf("%sFlag: %i\n", indent, ctrl->flag);
1286 void RIG_printLinkedCtrl(RigGraph *rg, EditBone *bone, int tabs)
1293 for (i = 0; i < tabs; i++)
1300 for (ctrl = rg->controls.first; ctrl; ctrl = ctrl->next)
1302 if (ctrl->link == bone)
1304 RIG_printCtrl(ctrl, indent);
1305 RIG_printLinkedCtrl(rg, ctrl->bone, tabs + 1);
1310 void RIG_printArc(RigGraph *rg, RigArc *arc)
1314 RIG_printNode((RigNode*)arc->head, "head");
1316 for (edge = arc->edges.first; edge; edge = edge->next)
1318 printf("\tinner joints %0.3f %0.3f %0.3f\n", edge->tail[0], edge->tail[1], edge->tail[2]);
1319 printf("\t\tlength %f\n", edge->length);
1320 printf("\t\tangle %f\n", edge->angle * 180 / M_PI);
1323 printf("\t\t%s\n", edge->bone->name);
1324 RIG_printLinkedCtrl(rg, edge->bone, 3);
1327 printf("symmetry level: %i flag: %i group %i\n", arc->symmetry_level, arc->symmetry_flag, arc->symmetry_group);
1329 RIG_printNode((RigNode*)arc->tail, "tail");
1332 void RIG_printGraph(RigGraph *rg)
1336 printf("---- ARCS ----\n");
1337 for (arc = rg->arcs.first; arc; arc = arc->next)
1339 RIG_printArc(rg, arc);
1345 RIG_printNode(rg->head, "HEAD NODE:");
1349 printf("HEAD NODE: NONE\n");
1353 /*******************************************************************************************************/
1355 RigGraph *armatureToGraph(Object *ob, bArmature *arm)
1364 rg->editbones = &G.edbo;
1368 rg->editbones = MEM_callocN(sizeof(ListBase), "EditBones");
1369 make_boneList(rg->editbones, &arm->bonebase, NULL);
1374 /* Do the rotations */
1375 for (ebone = rg->editbones->first; ebone; ebone=ebone->next){
1376 if (ebone->parent == NULL)
1378 RIG_arcFromBoneChain(rg, rg->editbones, ebone, NULL, 0);
1382 BLI_removeDoubleNodes((BGraph*)rg, 0.001);
1384 RIG_removeNormalNodes(rg);
1386 RIG_removeUneededOffsets(rg);
1388 BLI_buildAdjacencyList((BGraph*)rg);
1392 BLI_markdownSymmetry((BGraph*)rg, (BNode*)rg->head, G.scene->toolsettings->skgen_symmetry_limit);
1394 RIG_reconnectControlBones(rg); /* after symmetry, because we use levels to find best match */
1396 if (BLI_isGraphCyclic((BGraph*)rg))
1398 printf("armature cyclic\n");
1404 RigGraph *armatureSelectedToGraph(Object *ob, bArmature *arm)
1413 rg->editbones = &G.edbo;
1417 rg->editbones = MEM_callocN(sizeof(ListBase), "EditBones");
1418 make_boneList(rg->editbones, &arm->bonebase, NULL);
1423 /* Do the rotations */
1424 for (ebone = rg->editbones->first; ebone; ebone=ebone->next){
1425 if (ebone->parent == NULL)
1427 RIG_arcFromBoneChain(rg, rg->editbones, ebone, NULL, 1);
1431 BLI_removeDoubleNodes((BGraph*)rg, 0.001);
1433 RIG_removeNormalNodes(rg);
1435 RIG_removeUneededOffsets(rg);
1437 BLI_buildAdjacencyList((BGraph*)rg);
1441 BLI_markdownSymmetry((BGraph*)rg, (BNode*)rg->head, G.scene->toolsettings->skgen_symmetry_limit);
1443 RIG_reconnectControlBones(rg); /* after symmetry, because we use levels to find best match */
1445 if (BLI_isGraphCyclic((BGraph*)rg))
1447 printf("armature cyclic\n");
1452 /************************************ GENERATING *****************************************************/
1454 static EditBone *add_editbonetolist(char *name, ListBase *list)
1456 EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
1458 BLI_strncpy(bone->name, name, 32);
1459 unique_editbone_name(list, bone->name);
1461 BLI_addtail(list, bone);
1463 bone->flag |= BONE_TIPSEL;
1470 bone->rad_head= 0.10;
1471 bone->rad_tail= 0.05;
1473 bone->layer= 1;//arm->layer;
1478 EditBone * generateBonesForArc(RigGraph *rigg, ReebArc *arc, ReebNode *head, ReebNode *tail)
1480 ReebArcIterator iter;
1482 float ADAPTIVE_THRESHOLD = G.scene->toolsettings->skgen_correlation_limit;
1483 EditBone *lastBone = NULL;
1485 /* init iterator to get start and end from head */
1486 initArcIterator(&iter, arc, head);
1488 /* Calculate overall */
1489 VecSubf(n, arc->buckets[iter.end].p, head->p);
1491 if (1 /* G.scene->toolsettings->skgen_options & SKGEN_CUT_CORRELATION */ )
1493 EmbedBucket *bucket = NULL;
1494 EmbedBucket *previous = NULL;
1495 EditBone *child = NULL;
1496 EditBone *parent = NULL;
1497 float normal[3] = {0, 0, 0};
1498 float avg_normal[3];
1500 int boneStart = iter.start;
1502 parent = add_editbonetolist("Bone", rigg->editbones);
1503 parent->flag = BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL;
1504 VECCOPY(parent->head, head->p);
1506 for (previous = nextBucket(&iter), bucket = nextBucket(&iter);
1508 previous = bucket, bucket = nextBucket(&iter))
1513 if (G.scene->toolsettings->skgen_options & SKGEN_STICK_TO_EMBEDDING)
1515 VECCOPY(btail, bucket->p);
1521 /* Calculate normal */
1522 VecSubf(n, bucket->p, parent->head);
1523 length = Normalize(n);
1526 VecAddf(normal, normal, n);
1527 VECCOPY(avg_normal, normal);
1528 VecMulf(avg_normal, 1.0f / total);
1530 VECCOPY(btail, avg_normal);
1531 VecMulf(btail, length);
1532 VecAddf(btail, btail, parent->head);
1535 if (G.scene->toolsettings->skgen_options & SKGEN_ADAPTIVE_DISTANCE)
1537 value = calcDistance(arc, boneStart, iter.index, parent->head, btail);
1543 VecSubf(n, btail, parent->head);
1544 value = calcVariance(arc, boneStart, iter.index, parent->head, n);
1547 if (value > ADAPTIVE_THRESHOLD)
1549 VECCOPY(parent->tail, btail);
1551 child = add_editbonetolist("Bone", rigg->editbones);
1552 VECCOPY(child->head, parent->tail);
1553 child->parent = parent;
1554 child->flag |= BONE_CONNECTED|BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL;
1556 parent = child; // new child is next parent
1557 boneStart = iter.index; // start from end
1559 normal[0] = normal[1] = normal[2] = 0;
1564 VECCOPY(parent->tail, tail->p);
1566 lastBone = parent; /* set last bone in the chain */
1572 void generateMissingArcsFromNode(RigGraph *rigg, ReebNode *node, int multi_level_limit)
1574 while (node->multi_level > multi_level_limit && node->link_up)
1576 node = node->link_up;
1579 while (node->multi_level < multi_level_limit && node->link_down)
1581 node = node->link_down;
1584 if (node->multi_level == multi_level_limit)
1588 for (i = 0; i < node->degree; i++)
1590 ReebArc *earc = node->arcs[i];
1592 if (earc->flag == ARC_FREE && earc->head == node)
1594 ReebNode *other = BIF_otherNodeFromIndex(earc, node);
1596 earc->flag = ARC_USED;
1598 generateBonesForArc(rigg, earc, node, other);
1599 generateMissingArcsFromNode(rigg, other, multi_level_limit);
1605 void generateMissingArcs(RigGraph *rigg)
1607 ReebGraph *reebg = rigg->link_mesh;
1608 int multi_level_limit = 5;
1610 for (reebg = rigg->link_mesh; reebg; reebg = reebg->link_up)
1614 for (earc = reebg->arcs.first; earc; earc = earc->next)
1616 if (earc->flag == ARC_USED)
1618 generateMissingArcsFromNode(rigg, earc->head, multi_level_limit);
1619 generateMissingArcsFromNode(rigg, earc->tail, multi_level_limit);
1625 /************************************ RETARGETTING *****************************************************/
1627 static void repositionControl(RigGraph *rigg, RigControl *ctrl, float head[3], float tail[3], float qrot[4], float resize)
1629 RigControl *ctrl_child;
1630 float parent_offset[3], tail_offset[3];
1632 VecSubf(tail_offset, ctrl->tail, ctrl->head);
1633 VecMulf(tail_offset, resize);
1635 VECCOPY(parent_offset, ctrl->offset);
1636 VecMulf(parent_offset, resize);
1638 QuatMulVecf(qrot, parent_offset);
1639 QuatMulVecf(qrot, tail_offset);
1641 VecAddf(ctrl->bone->head, head, parent_offset);
1642 VecAddf(ctrl->bone->tail, ctrl->bone->head, tail_offset);
1643 ctrl->bone->roll = rollBoneByQuat(ctrl->bone, ctrl->up_axis, qrot);
1645 ctrl->flag |= RIG_CTRL_DONE;
1647 /* Cascade to connected control bones */
1648 for (ctrl_child = rigg->controls.first; ctrl_child; ctrl_child = ctrl_child->next)
1650 if (ctrl_child->link == ctrl->bone)
1652 repositionControl(rigg, ctrl_child, ctrl->bone->head, ctrl->bone->tail, qrot, resize);
1658 static void repositionBone(RigGraph *rigg, RigEdge *edge, float vec0[3], float vec1[3], float *up_axis)
1662 float qrot[4], resize;
1668 VecSubf(v1, edge->tail, edge->head);
1669 VecSubf(v2, vec1, vec0);
1676 RotationBetweenVectorsToQuat(qrot, v1, v2);
1678 VECCOPY(bone->head, vec0);
1679 VECCOPY(bone->tail, vec1);
1681 if (up_axis != NULL)
1685 bone->roll = rollBoneByQuatAligned(bone, edge->up_axis, qrot, qroll, up_axis);
1687 QuatMul(qrot, qrot, qroll);
1691 bone->roll = rollBoneByQuat(bone, edge->up_axis, qrot);
1694 for (ctrl = rigg->controls.first; ctrl; ctrl = ctrl->next)
1696 if (ctrl->link == bone)
1698 repositionControl(rigg, ctrl, vec0, vec1, qrot, resize);
1703 static RetargetMode detectArcRetargetMode(RigArc *arc);
1704 static void retargetArctoArcLength(RigGraph *rigg, RigArc *iarc, RigNode *inode_start);
1707 static RetargetMode detectArcRetargetMode(RigArc *iarc)
1709 RetargetMode mode = RETARGET_AGGRESSIVE;
1710 ReebArc *earc = iarc->link_mesh;
1712 int large_angle = 0;
1713 float avg_angle = 0;
1714 float avg_length = 0;
1718 for (edge = iarc->edges.first; edge; edge = edge->next)
1720 avg_angle += edge->angle;
1724 avg_angle /= nb_edges - 1; /* -1 because last edge doesn't have an angle */
1726 avg_length = iarc->length / nb_edges;
1731 for (edge = iarc->edges.first; edge; edge = edge->next)
1733 if (fabs(edge->angle - avg_angle) > M_PI / 6)
1739 else if (nb_edges == 2 && avg_angle > 0)
1745 if (large_angle == 0)
1747 mode = RETARGET_LENGTH;
1750 if (earc->bcount <= (iarc->count - 1))
1752 mode = RETARGET_LENGTH;
1755 mode = RETARGET_AGGRESSIVE;
1761 static void printMovesNeeded(int *positions, int nb_positions)
1766 for (i = 0; i < nb_positions; i++)
1768 moves += positions[i] - (i + 1);
1771 printf("%i moves needed\n", moves);
1774 static void printPositions(int *positions, int nb_positions)
1778 for (i = 0; i < nb_positions; i++)
1780 printf("%i ", positions[i]);
1786 #define MAX_COST 100 /* FIX ME */
1788 static float costDistance(ReebArcIterator *iter, float *vec0, float *vec1, int i0, int i1)
1790 EmbedBucket *bucket = NULL;
1792 float v1[3], v2[3], c[3];
1795 if (G.scene->toolsettings->skgen_retarget_distance_weight > 0)
1797 VecSubf(v1, vec0, vec1);
1799 v1_inpf = Inpf(v1, v1);
1804 for (j = i0 + 1; j < i1 - 1; j++)
1808 bucket = peekBucket(iter, j);
1810 VecSubf(v2, bucket->p, vec1);
1814 dist = Inpf(c, c) / v1_inpf;
1816 max_dist = dist > max_dist ? dist : max_dist;
1819 return G.scene->toolsettings->skgen_retarget_distance_weight * max_dist;
1832 static float costAngle(float original_angle, float vec_first[3], float vec_second[3])
1834 if (G.scene->toolsettings->skgen_retarget_angle_weight > 0)
1836 float current_angle;
1838 if (!VecIsNull(vec_first) && !VecIsNull(vec_second))
1840 current_angle = saacos(Inpf(vec_first, vec_second));
1842 return G.scene->toolsettings->skgen_retarget_angle_weight * fabs(current_angle - original_angle);
1846 return G.scene->toolsettings->skgen_retarget_angle_weight * M_PI;
1855 static float costLength(float original_length, float current_length)
1857 if (current_length == 0)
1863 float length_ratio = fabs((current_length - original_length) / original_length);
1864 return G.scene->toolsettings->skgen_retarget_length_weight * length_ratio * length_ratio;
1868 static float calcCostLengthDistance(ReebArcIterator *iter, float **vec_cache, RigEdge *edge, float *vec1, float *vec2, int i1, int i2)
1873 VecSubf(vec, vec2, vec1);
1874 length = Normalize(vec);
1876 return costLength(edge->length, length) + costDistance(iter, vec1, vec2, i1, i2);
1879 static float calcCostAngleLengthDistance(ReebArcIterator *iter, float **vec_cache, RigEdge *edge, float *vec0, float *vec1, float *vec2, int i1, int i2)
1881 float vec_second[3], vec_first[3];
1885 VecSubf(vec_second, vec2, vec1);
1886 length2 = Normalize(vec_second);
1892 VecSubf(vec_first, vec1, vec0);
1893 Normalize(vec_first);
1895 new_cost += costAngle(edge->prev->angle, vec_first, vec_second);
1899 new_cost += costLength(edge->length, length2);
1902 new_cost += costDistance(iter, vec1, vec2, i1, i2);
1907 static int indexMemoNode(int nb_positions, int previous, int current, int joints_left)
1909 return joints_left * nb_positions * nb_positions + current * nb_positions + previous;
1912 static void copyMemoPositions(int *positions, MemoNode *table, int nb_positions, int joints_left)
1914 int previous = 0, current = 0;
1917 for (i = 0; joints_left > 0; joints_left--, i++)
1920 node = table + indexMemoNode(nb_positions, previous, current, joints_left);
1922 positions[i] = node->next;
1925 current = node->next;
1929 static MemoNode * solveJoints(MemoNode *table, ReebArcIterator *iter, float **vec_cache, int nb_joints, int nb_positions, int previous, int current, RigEdge *edge, int joints_left)
1932 int index = indexMemoNode(nb_positions, previous, current, joints_left);
1934 node = table + index;
1936 if (node->weight != 0)
1940 else if (joints_left == 0)
1942 float *vec1 = vec_cache[current];
1943 float *vec2 = vec_cache[nb_positions + 1];
1945 node->weight = calcCostLengthDistance(iter, vec_cache, edge, vec1, vec2, current, iter->length);
1951 MemoNode *min_node = NULL;
1952 float *vec0 = vec_cache[previous];
1953 float *vec1 = vec_cache[current];
1958 for (next = current + 1; next <= nb_positions - (joints_left - 1); next++)
1960 MemoNode *next_node;
1961 float *vec2 = vec_cache[next];
1964 /* ADD WEIGHT OF PREVIOUS - CURRENT - NEXT triple */
1965 weight = calcCostAngleLengthDistance(iter, vec_cache, edge, vec0, vec1, vec2, current, next);
1967 if (weight >= MAX_COST)
1972 /* add node weight */
1973 next_node = solveJoints(table, iter, vec_cache, nb_joints, nb_positions, current, next, edge->next, joints_left - 1);
1974 weight += next_node->weight;
1976 if (min_node == NULL || weight < min_weight)
1978 min_weight = weight;
1979 min_node = next_node;
1986 node->weight = min_weight;
1987 node->next = min_next;
1992 node->weight = MAX_COST;
1999 static int testFlipArc(RigArc *iarc, RigNode *inode_start)
2001 ReebArc *earc = iarc->link_mesh;
2002 ReebNode *enode_start = BIF_NodeFromIndex(earc, inode_start->link_mesh);
2004 /* no flip needed if both nodes are the same */
2005 if ((enode_start == earc->head && inode_start == iarc->head) || (enode_start == earc->tail && inode_start == iarc->tail))
2015 static void retargetArctoArcAggresive(RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2017 ReebArcIterator iter;
2019 EmbedBucket *bucket = NULL;
2020 ReebNode *node_start, *node_end;
2021 ReebArc *earc = iarc->link_mesh;
2022 float min_cost = FLT_MAX;
2023 float *vec0, *vec1, *vec2;
2026 int *best_positions;
2028 int nb_edges = BLI_countlist(&iarc->edges);
2029 int nb_joints = nb_edges - 1;
2030 RetargetMethod method = METHOD_MEMOIZE;
2033 if (nb_joints > earc->bcount)
2035 printf("NOT ENOUGH BUCKETS!\n");
2039 positions = MEM_callocN(sizeof(int) * nb_joints, "Aggresive positions");
2040 best_positions = MEM_callocN(sizeof(int) * nb_joints, "Best Aggresive positions");
2041 cost_cache = MEM_callocN(sizeof(float) * nb_edges, "Cost cache");
2042 vec_cache = MEM_callocN(sizeof(float*) * (nb_edges + 1), "Vec cache");
2044 if (testFlipArc(iarc, inode_start))
2046 node_start = earc->tail;
2047 node_end = earc->head;
2051 node_start = earc->head;
2052 node_end = earc->tail;
2055 /* init with first values */
2056 for (i = 0; i < nb_joints; i++)
2058 positions[i] = i + 1;
2059 //positions[i] = (earc->bcount / nb_edges) * (i + 1);
2062 /* init cost cache */
2063 for (i = 0; i < nb_edges; i++)
2068 vec_cache[0] = node_start->p;
2069 vec_cache[nb_edges] = node_end->p;
2071 if (method == METHOD_MEMOIZE)
2073 int nb_positions = earc->bcount;
2074 int nb_memo_nodes = nb_positions * nb_positions * (nb_joints + 1);
2075 MemoNode *table = MEM_callocN(nb_memo_nodes * sizeof(MemoNode), "memoization table");
2077 float **positions_cache = MEM_callocN(sizeof(float*) * (nb_positions + 2), "positions cache");
2080 positions_cache[0] = node_start->p;
2081 positions_cache[nb_positions + 1] = node_end->p;
2083 initArcIterator(&iter, earc, node_start);
2085 for (i = 1; i <= nb_positions; i++)
2087 EmbedBucket *bucket = peekBucket(&iter, i);
2088 positions_cache[i] = bucket->p;
2091 result = solveJoints(table, &iter, positions_cache, nb_joints, earc->bcount, 0, 0, iarc->edges.first, nb_joints);
2093 min_cost = result->weight;
2094 copyMemoPositions(best_positions, table, earc->bcount, nb_joints);
2097 MEM_freeN(positions_cache);
2100 else if (method == METHOD_BRUTE_FORCE)
2104 int must_move = nb_joints - 1;
2111 /* increment to next possible solution */
2122 /* increment positions, starting from the last one
2123 * until a valid increment is found
2125 for (i = must_move; i >= 0; i--)
2127 int remaining_joints = nb_joints - (i + 1);
2132 if (positions[i] + remaining_joints <= earc->bcount)
2144 /* reset joints following the last increment*/
2145 for (i = i + 1; i < nb_joints; i++)
2147 positions[i] = positions[i - 1] + 1;
2150 /* calculating cost */
2151 initArcIterator(&iter, earc, node_start);
2154 vec1 = node_start->p;
2157 for (edge = iarc->edges.first, i = 0, last_index = 0;
2159 edge = edge->next, i += 1)
2164 float vec_first[3], vec_second[3];
2165 float length1, length2;
2172 bucket = peekBucket(&iter, positions[i]);
2174 vec_cache[i + 1] = vec2; /* update cache for updated position */
2184 i1 = positions[i - 1];
2191 vec1 = vec_cache[i];
2194 VecSubf(vec_second, vec2, vec1);
2195 length2 = Normalize(vec_second);
2198 if (i != 0 && G.scene->toolsettings->skgen_retarget_angle_weight > 0)
2200 RigEdge *previous = edge->prev;
2202 vec0 = vec_cache[i - 1];
2203 VecSubf(vec_first, vec1, vec0);
2204 length1 = Normalize(vec_first);
2207 new_cost += costAngle(previous->angle, vec_first, vec_second);
2211 new_cost += costLength(edge->length, length2);
2214 new_cost += costDistance(&iter, vec1, vec2, i1, i2);
2216 cost_cache[i] = new_cost;
2219 cost += cost_cache[i];
2221 if (cost > min_cost)
2228 if (must_move != i || must_move > nb_joints - 1)
2230 must_move = nb_joints - 1;
2233 /* cost optimizing */
2234 if (cost < min_cost)
2237 memcpy(best_positions, positions, sizeof(int) * nb_joints);
2242 vec0 = node_start->p;
2243 initArcIterator(&iter, earc, node_start);
2246 printPositions(best_positions, nb_joints);
2247 printMovesNeeded(best_positions, nb_joints);
2248 printf("min_cost %f\n", min_cost);
2249 printf("buckets: %i\n", earc->bcount);
2252 /* set joints to best position */
2253 for (edge = iarc->edges.first, i = 0;
2255 edge = edge->next, i++)
2260 bucket = peekBucket(&iter, best_positions[i]);
2271 repositionBone(rigg, edge, vec0, vec1, no);
2277 MEM_freeN(positions);
2278 MEM_freeN(best_positions);
2279 MEM_freeN(cost_cache);
2280 MEM_freeN(vec_cache);
2283 static void retargetArctoArcLength(RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2285 ReebArcIterator iter;
2286 ReebArc *earc = iarc->link_mesh;
2287 ReebNode *node_start, *node_end;
2289 EmbedBucket *bucket = NULL;
2290 float embedding_length = 0;
2293 float *previous_vec = NULL;
2296 if (testFlipArc(iarc, inode_start))
2298 node_start = (ReebNode*)earc->tail;
2299 node_end = (ReebNode*)earc->head;
2303 node_start = (ReebNode*)earc->head;
2304 node_end = (ReebNode*)earc->tail;
2307 initArcIterator(&iter, earc, node_start);
2309 bucket = nextBucket(&iter);
2311 vec0 = node_start->p;
2313 while (bucket != NULL)
2317 embedding_length += VecLenf(vec0, vec1);
2320 bucket = nextBucket(&iter);
2323 embedding_length += VecLenf(node_end->p, vec1);
2326 initArcIterator(&iter, earc, node_start);
2328 bucket = nextBucket(&iter);
2330 vec0 = node_start->p;
2331 previous_vec = vec0;
2334 for (edge = iarc->edges.first; edge; edge = edge->next)
2336 float new_bone_length = edge->length / iarc->length * embedding_length;
2340 while (bucket && new_bone_length > length)
2342 length += VecLenf(previous_vec, vec1);
2343 bucket = nextBucket(&iter);
2344 previous_vec = vec1;
2355 /* no need to move virtual edges (space between unconnected bones) */
2358 repositionBone(rigg, edge, vec0, vec1, no);
2362 previous_vec = vec1;
2366 static void retargetArctoArc(RigGraph *rigg, RigArc *iarc, RigNode *inode_start)
2369 RetargetParam *p = MEM_callocN(sizeof(RetargetParam), "RetargetParam");
2373 p->inode_start = inode_start;
2375 BLI_insert_work(rigg->worker, p);
2381 p.inode_start = inode_start;
2383 exec_retargetArctoArc(&p);
2387 void *exec_retargetArctoArc(void *param)
2389 RetargetParam *p = (RetargetParam*)param;
2390 RigGraph *rigg = p->rigg;
2391 RigArc *iarc = p->iarc;
2392 RigNode *inode_start = p->inode_start;
2393 ReebArc *earc = iarc->link_mesh;
2395 if (BLI_countlist(&iarc->edges) == 1)
2397 RigEdge *edge = iarc->edges.first;
2399 if (testFlipArc(iarc, inode_start))
2401 repositionBone(rigg, edge, earc->tail->p, earc->head->p, NULL);
2405 repositionBone(rigg, edge, earc->head->p, earc->tail->p, NULL);
2410 RetargetMode mode = detectArcRetargetMode(iarc);
2412 if (mode == RETARGET_AGGRESSIVE)
2414 retargetArctoArcAggresive(rigg, iarc, inode_start);
2418 retargetArctoArcLength(rigg, iarc, inode_start);
2429 static void matchMultiResolutionNode(RigGraph *rigg, RigNode *inode, ReebNode *top_node)
2431 ReebNode *enode = top_node;
2432 ReebGraph *reebg = BIF_graphForMultiNode(rigg->link_mesh, enode);
2435 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)inode, NULL, 0) % SHAPE_LEVELS;
2436 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2438 inode->link_mesh = enode;
2440 while (ishape == eshape && enode->link_down)
2442 inode->link_mesh = enode;
2444 enode = enode->link_down;
2445 reebg = BIF_graphForMultiNode(rigg->link_mesh, enode); /* replace with call to link_down once that exists */
2446 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2450 static void markMultiResolutionChildArc(ReebNode *end_enode, ReebNode *enode)
2454 for(i = 0; i < enode->degree; i++)
2456 ReebArc *earc = (ReebArc*)enode->arcs[i];
2458 if (earc->flag == ARC_FREE)
2460 earc->flag = ARC_TAKEN;
2462 if (earc->tail->degree > 1 && earc->tail != end_enode)
2464 markMultiResolutionChildArc(end_enode, earc->tail);
2471 static void markMultiResolutionArc(ReebArc *start_earc)
2473 if (start_earc->link_up)
2476 for (earc = start_earc->link_up ; earc; earc = earc->link_up)
2478 earc->flag = ARC_TAKEN;
2480 if (earc->tail->index != start_earc->tail->index)
2482 markMultiResolutionChildArc(earc->tail, earc->tail);
2488 static void matchMultiResolutionArc(RigGraph *rigg, RigNode *start_node, RigArc *next_iarc, ReebArc *next_earc)
2490 ReebNode *enode = next_earc->head;
2491 ReebGraph *reebg = BIF_graphForMultiNode(rigg->link_mesh, enode);
2494 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)start_node, (BArc*)next_iarc, 1) % SHAPE_LEVELS;
2495 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, (BArc*)next_earc, 1) % SHAPE_LEVELS;
2497 while (ishape != eshape && next_earc->link_up)
2499 next_earc->flag = ARC_TAKEN; // mark previous as taken, to prevent backtrack on lower levels
2501 next_earc = next_earc->link_up;
2502 reebg = reebg->link_up;
2503 enode = next_earc->head;
2504 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, (BArc*)next_earc, 1) % SHAPE_LEVELS;
2507 next_earc->flag = ARC_USED;
2508 next_iarc->link_mesh = next_earc;
2510 /* mark all higher levels as taken too */
2511 markMultiResolutionArc(next_earc);
2512 // while (next_earc->link_up)
2514 // next_earc = next_earc->link_up;
2515 // next_earc->flag = ARC_TAKEN;
2519 static void matchMultiResolutionStartingNode(RigGraph *rigg, ReebGraph *reebg, RigNode *inode)
2524 enode = reebg->nodes.first;
2526 ishape = BLI_subtreeShape((BGraph*)rigg, (BNode*)inode, NULL, 0) % SHAPE_LEVELS;
2527 eshape = BLI_subtreeShape((BGraph*)rigg->link_mesh, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2529 while (ishape != eshape && reebg->link_up)
2531 reebg = reebg->link_up;
2533 enode = reebg->nodes.first;
2535 eshape = BLI_subtreeShape((BGraph*)reebg, (BNode*)enode, NULL, 0) % SHAPE_LEVELS;
2538 inode->link_mesh = enode;
2541 static void findCorrespondingArc(RigGraph *rigg, RigArc *start_arc, RigNode *start_node, RigArc *next_iarc, int root)
2543 ReebNode *enode = start_node->link_mesh;
2545 int symmetry_level = next_iarc->symmetry_level;
2546 int symmetry_group = next_iarc->symmetry_group;
2547 int symmetry_flag = next_iarc->symmetry_flag;
2550 next_iarc->link_mesh = NULL;
2554 // printf("-----------------------\n");
2555 // printf("MATCHING LIMB\n");
2556 // RIG_printArcBones(next_iarc);
2559 for(i = 0; i < enode->degree; i++)
2561 next_earc = (ReebArc*)enode->arcs[i];
2563 // if (next_earc->flag == ARC_FREE)
2565 // printf("candidate (level %i ?= %i) (flag %i ?= %i) (group %i ?= %i)\n",
2566 // symmetry_level, next_earc->symmetry_level,
2567 // symmetry_flag, next_earc->symmetry_flag,
2568 // symmetry_group, next_earc->symmetry_flag);
2571 if (next_earc->flag == ARC_FREE &&
2572 next_earc->symmetry_flag == symmetry_flag &&
2573 next_earc->symmetry_group == symmetry_group &&
2574 next_earc->symmetry_level == symmetry_level)
2576 // printf("CORRESPONDING ARC FOUND\n");
2577 // printf("flag %i -- level %i -- flag %i -- group %i\n", next_earc->flag, next_earc->symmetry_level, next_earc->symmetry_flag, next_earc->symmetry_group);
2579 matchMultiResolutionArc(rigg, start_node, next_iarc, next_earc);
2584 /* not found, try at higher nodes (lower node might have filtered internal arcs, messing shape of tree */
2585 if (next_iarc->link_mesh == NULL)
2587 // printf("NO CORRESPONDING ARC FOUND - GOING TO HIGHER LEVELS\n");
2591 start_node->link_mesh = enode->link_up;
2592 findCorrespondingArc(rigg, start_arc, start_node, next_iarc, 0);
2596 /* still not found, print debug info */
2597 if (root && next_iarc->link_mesh == NULL)
2599 start_node->link_mesh = enode; /* linking back with root node */
2601 // printf("NO CORRESPONDING ARC FOUND\n");
2602 // RIG_printArcBones(next_iarc);
2604 // printf("ON NODE %i, multilevel %i\n", enode->index, enode->multi_level);
2606 // printf("LOOKING FOR\n");
2607 // printf("flag %i -- level %i -- flag %i -- group %i\n", ARC_FREE, symmetry_level, symmetry_flag, symmetry_group);
2609 // printf("CANDIDATES\n");
2610 // for(i = 0; i < enode->degree; i++)
2612 // next_earc = (ReebArc*)enode->arcs[i];
2613 // printf("flag %i -- level %i -- flag %i -- group %i\n", next_earc->flag, next_earc->symmetry_level, next_earc->symmetry_flag, next_earc->symmetry_group);
2616 /* Emergency matching */
2617 for(i = 0; i < enode->degree; i++)
2619 next_earc = (ReebArc*)enode->arcs[i];
2621 if (next_earc->flag == ARC_FREE && next_earc->symmetry_level == symmetry_level)
2623 // printf("USING: \n");
2624 // printf("flag %i -- level %i -- flag %i -- group %i\n", next_earc->flag, next_earc->symmetry_level, next_earc->symmetry_flag, next_earc->symmetry_group);
2625 matchMultiResolutionArc(rigg, start_node, next_iarc, next_earc);
2633 static void retargetSubgraph(RigGraph *rigg, RigArc *start_arc, RigNode *start_node)
2635 RigNode *inode = start_node;
2638 /* no start arc on first node */
2641 ReebNode *enode = start_node->link_mesh;
2642 ReebArc *earc = start_arc->link_mesh;
2644 retargetArctoArc(rigg, start_arc, start_node);
2646 enode = BIF_otherNodeFromIndex(earc, enode);
2647 inode = (RigNode*)BLI_otherNode((BArc*)start_arc, (BNode*)inode);
2649 /* match with lowest node with correct shape */
2650 matchMultiResolutionNode(rigg, inode, enode);
2653 for(i = 0; i < inode->degree; i++)
2655 RigArc *next_iarc = (RigArc*)inode->arcs[i];
2657 /* no back tracking */
2658 if (next_iarc != start_arc)
2660 findCorrespondingArc(rigg, start_arc, inode, next_iarc, 1);
2661 if (next_iarc->link_mesh)
2663 retargetSubgraph(rigg, next_iarc, inode);
2669 static void finishRetarget(RigGraph *rigg)
2672 BLI_end_worker(rigg->worker);
2676 static void adjustGraphs(RigGraph *rigg)
2680 for (arc = rigg->arcs.first; arc; arc = arc->next)
2684 retargetArctoArc(rigg, arc, arc->head);
2688 finishRetarget(rigg);
2690 /* Turn the list into an armature */
2691 editbones_to_armature(rigg->editbones, rigg->ob);
2693 BIF_undo_push("Retarget Skeleton");
2696 static void retargetGraphs(RigGraph *rigg)
2698 ReebGraph *reebg = rigg->link_mesh;
2701 /* flag all ReebArcs as free */
2702 BIF_flagMultiArcs(reebg, ARC_FREE);
2704 /* return to first level */
2705 reebg = rigg->link_mesh;
2709 matchMultiResolutionStartingNode(rigg, reebg, inode);
2711 retargetSubgraph(rigg, NULL, inode);
2713 //generateMissingArcs(rigg);
2715 finishRetarget(rigg);
2717 /* Turn the list into an armature */
2718 editbones_to_armature(rigg->editbones, rigg->ob);
2722 void BIF_retargetArmature()
2727 double start_time, end_time;
2728 double gstart_time, gend_time;
2729 double reeb_time, rig_time, retarget_time, total_time;
2731 gstart_time = start_time = PIL_check_seconds_timer();
2733 reebg = BIF_ReebGraphMultiFromEditMesh();
2735 end_time = PIL_check_seconds_timer();
2736 reeb_time = end_time - start_time;
2738 printf("Reeb Graph created\n");
2741 for (base = FIRSTBASE; base; base = base->next)
2743 if TESTBASELIB(base) {
2746 if (ob->type==OB_ARMATURE)
2753 /* Put the armature into editmode */
2756 start_time = PIL_check_seconds_timer();
2758 rigg = armatureToGraph(ob, arm);
2760 end_time = PIL_check_seconds_timer();
2761 rig_time = end_time - start_time;
2763 printf("Armature graph created\n");
2765 //RIG_printGraph(rigg);
2767 rigg->link_mesh = reebg;
2769 printf("retargetting %s\n", ob->id.name);
2771 start_time = PIL_check_seconds_timer();
2773 retargetGraphs(rigg);
2775 end_time = PIL_check_seconds_timer();
2776 retarget_time = end_time - start_time;
2782 break; /* only one armature at a time */
2787 gend_time = PIL_check_seconds_timer();
2789 total_time = gend_time - gstart_time;
2791 printf("-----------\n");
2792 printf("runtime: \t%.3f\n", total_time);
2793 printf("reeb: \t\t%.3f (%.1f%%)\n", reeb_time, reeb_time / total_time * 100);
2794 printf("rig: \t\t%.3f (%.1f%%)\n", rig_time, rig_time / total_time * 100);
2795 printf("retarget: \t%.3f (%.1f%%)\n", retarget_time, retarget_time / total_time * 100);
2796 printf("-----------\n");
2798 BIF_undo_push("Retarget Skeleton");
2800 allqueue(REDRAWVIEW3D, 0);
2803 void BIF_retargetArc(ReebArc *earc)
2814 template = armatureSelectedToGraph(ob, arm);
2816 if (template->arcs.first == NULL)
2818 error("No deforming bones selected");
2822 rigg = cloneRigGraph(template);
2824 iarc = rigg->arcs.first;
2826 iarc->link_mesh = earc;
2827 iarc->head->link_mesh = earc->head;
2828 iarc->tail->link_mesh = earc->tail;
2830 retargetArctoArc(rigg, iarc, iarc->head);
2832 finishRetarget(rigg);
2834 RIG_freeRigGraph((BGraph*)template);
2835 RIG_freeRigGraph((BGraph*)rigg);
2837 BIF_undo_push("Retarget Arc");
2839 allqueue(REDRAWVIEW3D, 0);
2842 void BIF_adjustRetarget()
2846 adjustGraphs(GLOBAL_RIGG);
2850 void BIF_freeRetarget()
2854 RIG_freeRigGraph((BGraph*)GLOBAL_RIGG);