Fix build error on Windows 32 bit.
[blender-staging.git] / source / blender / collada / ArmatureImporter.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Nathan Letwory, Sukhitha jayathilake.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/collada/ArmatureImporter.cpp
24  *  \ingroup collada
25  */
26
27
28 /* COLLADABU_ASSERT, may be able to remove later */
29 #include "COLLADABUPlatform.h"
30
31 #include <algorithm>
32
33 #include "COLLADAFWUniqueId.h"
34
35 extern "C" {
36 #include "BKE_action.h"
37 #include "BKE_depsgraph.h"
38 #include "BKE_object.h"
39 #include "BKE_armature.h"
40 #include "BLI_string.h"
41 #include "BLI_listbase.h"
42 #include "ED_armature.h"
43 }
44
45 #include "collada_utils.h"
46 #include "ArmatureImporter.h"
47
48 // use node name, or fall back to original id if not present (name is optional)
49 template<class T>
50 static const char *bc_get_joint_name(T *node)
51 {
52         const std::string& id = node->getName();
53         return id.size() ? id.c_str() : node->getOriginalId().c_str();
54 }
55
56
57 ArmatureImporter::ArmatureImporter(UnitConverter *conv, MeshImporterBase *mesh, Scene *sce, const ImportSettings *import_settings) :
58         TransformReader(conv),
59         scene(sce),
60         unit_converter(conv),
61         import_settings(import_settings),
62         empty(NULL), 
63         mesh_importer(mesh) {
64 }
65
66 ArmatureImporter::~ArmatureImporter()
67 {
68         // free skin controller data if we forget to do this earlier
69         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
70         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
71                 it->second.free();
72         }
73 }
74
75 #if 0
76 JointData *ArmatureImporter::get_joint_data(COLLADAFW::Node *node);
77 {
78         const COLLADAFW::UniqueId& joint_id = node->getUniqueId();
79
80         if (joint_id_to_joint_index_map.find(joint_id) == joint_id_to_joint_index_map.end()) {
81                 fprintf(stderr, "Cannot find a joint index by joint id for %s.\n",
82                         node->getOriginalId().c_str());
83                 return NULL;
84         }
85
86         int joint_index = joint_id_to_joint_index_map[joint_id];
87
88         return &joint_index_to_joint_info_map[joint_index];
89 }
90 #endif
91
92 int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBone *parent, int totchild,
93         float parent_mat[4][4], bArmature *arm, std::vector<std::string> &layer_labels)
94 {
95         float mat[4][4];
96         float joint_inv_bind_mat[4][4];
97         float joint_bind_mat[4][4];
98         int chain_length = 0;
99
100         //Checking if bone is already made.
101         std::vector<COLLADAFW::Node *>::iterator it;
102         it = std::find(finished_joints.begin(), finished_joints.end(), node);
103         if (it != finished_joints.end()) return chain_length;
104         
105         EditBone *bone = ED_armature_edit_bone_add(arm, (char *)bc_get_joint_name(node));
106         totbone++;
107
108         /*
109          * We use the inv_bind_shape matrix to apply the armature bind pose as its rest pose.
110         */
111
112         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator skin_it;
113         bool bone_is_skinned = false;
114         for (skin_it = skin_by_data_uid.begin(); skin_it != skin_by_data_uid.end(); skin_it++) {
115
116                 SkinInfo *b = &skin_it->second;
117                 if (b->get_joint_inv_bind_matrix(joint_inv_bind_mat, node)) {
118
119                         // get original world-space matrix
120                         invert_m4_m4(mat, joint_inv_bind_mat);
121                         copy_m4_m4(joint_bind_mat, mat);
122                         // And make local to armature
123                         Object *ob_arm = skin->BKE_armature_from_object();
124                         if (ob_arm) {
125                                 float invmat[4][4];
126                                 invert_m4_m4(invmat, ob_arm->obmat);
127                                 mul_m4_m4m4(mat, invmat, mat);
128                         }
129
130                         bone_is_skinned = true;
131                         break;
132                 }
133         }
134
135         // create a bone even if there's no joint data for it (i.e. it has no influence)
136         if (!bone_is_skinned) {
137                 get_node_mat(mat, node, NULL, NULL, parent_mat);
138         }
139
140         if (parent) bone->parent = parent;
141
142         float loc[3], size[3], rot[3][3]; 
143         BoneExtensionMap &extended_bones = bone_extension_manager.getExtensionMap(arm);
144         BoneExtended &be = add_bone_extended(bone, node, totchild, layer_labels, extended_bones);
145         int layer = be.get_bone_layers();
146         if (layer) bone->layer = layer;
147         arm->layer |= layer; // ensure that all populated bone layers are visible after import
148
149         float *tail = be.get_tail();
150         int use_connect = be.get_use_connect();
151
152         switch (use_connect) {
153                 case 1: bone->flag |= BONE_CONNECTED;
154                         break;
155                 case -1:/* Connect type not specified */
156                 case 0: bone->flag &= ~BONE_CONNECTED;
157                         break;
158         }
159
160         if (be.has_roll()) {
161                 bone->roll = be.get_roll();
162         }
163         else {
164                 float angle;
165                 mat4_to_loc_rot_size(loc, rot, size, mat);
166                 mat3_to_vec_roll(rot, NULL, &angle);
167                 bone->roll = angle;
168         }
169         copy_v3_v3(bone->head, mat[3]);
170
171         if (bone_is_skinned)
172         {
173                 float rest_mat[4][4];
174                 get_node_mat(rest_mat, node, NULL, NULL, NULL);
175                 bc_set_IDPropertyMatrix(bone, "bind_mat", joint_bind_mat);
176                 bc_set_IDPropertyMatrix(bone, "rest_mat", rest_mat);
177         }
178
179         add_v3_v3v3(bone->tail, bone->head, tail); //tail must be non zero
180
181         /* find smallest bone length in armature (used later for leaf bone length) */
182         if (parent) {
183
184                 if (use_connect == 1) {
185                         copy_v3_v3(parent->tail, bone->head);
186                 }
187
188                 /* guess reasonable leaf bone length */
189                 float length = len_v3v3(parent->head, bone->head);
190                 if ((length < leaf_bone_length || totbone == 0) && length > MINIMUM_BONE_LENGTH) {
191                         leaf_bone_length = length;
192                 }
193         }
194
195         COLLADAFW::NodePointerArray& children = node->getChildNodes();
196
197         for (unsigned int i = 0; i < children.getCount(); i++) {
198                 int cl = create_bone(skin, children[i], bone, children.getCount(), mat, arm, layer_labels);
199                 if (cl > chain_length)
200                         chain_length = cl;
201         }
202
203         bone->length = len_v3v3(bone->head, bone->tail);
204         joint_by_uid[node->getUniqueId()] = node;
205         finished_joints.push_back(node);
206
207         be.set_chain_length(chain_length + 1);
208
209         return chain_length + 1;
210 }
211
212 /**
213   * Collada only knows Joints, hence bones at the end of a bone chain
214   * don't have a defined length. This function guesses reasonable
215   * tail locations for the affected bones (nodes which don't have any connected child)
216   * Hint: The extended_bones set gets populated in ArmatureImporter::create_bone
217 **/
218 void ArmatureImporter::fix_leaf_bone_hierarchy(bArmature *armature, Bone *bone, bool fix_orientation)
219 {
220         if (bone == NULL)
221                 return;
222
223         if (bc_is_leaf_bone(bone)) {
224                 BoneExtensionMap &extended_bones = bone_extension_manager.getExtensionMap(armature);
225                 BoneExtended *be = extended_bones[bone->name];
226                 EditBone *ebone = bc_get_edit_bone(armature, bone->name);
227                 fix_leaf_bone(armature, ebone, be, fix_orientation);
228         }
229
230         for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
231                 fix_leaf_bone_hierarchy(armature, child, fix_orientation);
232         }
233 }
234
235 void ArmatureImporter::fix_leaf_bone(bArmature *armature, EditBone *ebone, BoneExtended *be , bool fix_orientation)
236 {
237         if (be == NULL || !be->has_tail()) {
238
239                 /* Collada only knows Joints, Here we guess a reasonable leaf bone length */
240                 float leaf_length = (leaf_bone_length == FLT_MAX) ? 1.0 : leaf_bone_length;
241
242
243                 float vec[3];
244
245                 if (fix_orientation && ebone->parent != NULL) {
246                         EditBone *parent = ebone->parent;
247                         sub_v3_v3v3(vec, ebone->head, parent->head);
248                         if (len_squared_v3(vec) < MINIMUM_BONE_LENGTH)
249                         {
250                                 sub_v3_v3v3(vec, parent->tail, parent->head);
251                         }
252                 }
253                 else {
254                         vec[2] = 0.1f;
255                         sub_v3_v3v3(vec, ebone->tail, ebone->head);
256                 }
257
258                 normalize_v3_v3(vec, vec);
259                 mul_v3_fl(vec, leaf_length);
260                 add_v3_v3v3(ebone->tail, ebone->head, vec);
261         }
262 }
263
264 void ArmatureImporter::fix_parent_connect(bArmature *armature, Bone *bone)
265 {
266         /* armature has no bones */
267         if (bone == NULL)
268                 return;
269
270         if (bone->parent && bone->flag & BONE_CONNECTED) {
271                 copy_v3_v3(bone->parent->tail, bone->head);
272         }
273
274         for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
275                 fix_parent_connect(armature, child);
276         }
277
278 }
279
280 void ArmatureImporter::connect_bone_chains(bArmature *armature, Bone *parentbone, int clip)
281 {
282         BoneExtensionMap &extended_bones = bone_extension_manager.getExtensionMap(armature);
283         BoneExtended *dominant_child = NULL;
284         int maxlen = 0;
285
286         if (parentbone == NULL)
287                 return;
288
289         Bone *child = (Bone *)parentbone->childbase.first;
290         if (child && (import_settings->find_chains || child->next==NULL)) {
291                 for (; child; child = child->next) {
292                         BoneExtended *be = extended_bones[child->name];
293                         if (be != NULL) {
294                                 int chain_len = be->get_chain_length();
295                                 if (chain_len <= clip) {
296                                         if (chain_len > maxlen) {
297                                                 dominant_child = be;
298                                                 maxlen = chain_len;
299                                         }
300                                         else if (chain_len == maxlen) {
301                                                 dominant_child = NULL;
302                                         }
303                                 }
304                         }
305                 }
306         }
307
308         BoneExtended *pbe = extended_bones[parentbone->name];
309         if (dominant_child != NULL) {
310                 /* Found a valid chain. Now connect current bone with that chain.*/
311                 EditBone *pebone = bc_get_edit_bone(armature, parentbone->name);
312                 EditBone *cebone = bc_get_edit_bone(armature, dominant_child->get_name());
313                 if (pebone && !(cebone->flag & BONE_CONNECTED)) {
314                         float vec[3];
315                         sub_v3_v3v3(vec, cebone->head, pebone->head);
316
317                         /*
318                          * It is possible that the child's head is located on the parents head.
319                          * When this happens, then moving the parent's tail to the child's head
320                          * would result in a zero sized bone and Blender would  silently remove the bone.
321                          * So we move the tail only when the resulting bone has a minimum length:
322                          */
323
324                         if (len_squared_v3(vec) > MINIMUM_BONE_LENGTH)
325                         {
326                                 copy_v3_v3(pebone->tail, cebone->head);
327                                 pbe->set_tail(pebone->tail); /* to make fix_leafbone happy ...*/
328                                 if (pbe && pbe->get_chain_length() >= this->import_settings->min_chain_length) {
329
330                                         BoneExtended *cbe = extended_bones[cebone->name];
331                                         cbe->set_use_connect(true);
332
333                                         cebone->flag |= BONE_CONNECTED;
334                                         pbe->set_leaf_bone(false);
335                                         printf("Connect Bone chain: parent (%s --> %s) child)\n", pebone->name, cebone->name);
336                                 }
337                         }
338                 }
339                 for (Bone *ch = (Bone *)parentbone->childbase.first; ch; ch = ch->next) {
340                         ArmatureImporter::connect_bone_chains(armature, ch, UNLIMITED_CHAIN_MAX);
341                 }
342         }
343         else if (maxlen>1 && maxlen > this->import_settings->min_chain_length) {
344                 /* Try again with smaller chain length */
345                 ArmatureImporter::connect_bone_chains(armature, parentbone, maxlen - 1);
346         }
347         else {
348                 /* can't connect this Bone. Proceed with children ... */
349                 if (pbe) pbe->set_leaf_bone(true);
350                 for (Bone *ch = (Bone *)parentbone->childbase.first; ch; ch = ch->next) {
351                         ArmatureImporter::connect_bone_chains(armature, ch, UNLIMITED_CHAIN_MAX);
352                 }
353         }
354
355 }
356
357 #if 0
358 void ArmatureImporter::set_leaf_bone_shapes(Object *ob_arm)
359 {
360         bPose *pose = ob_arm->pose;
361
362         std::vector<LeafBone>::iterator it;
363         for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
364                 LeafBone& leaf = *it;
365
366                 bPoseChannel *pchan = BKE_pose_channel_find_name(pose, leaf.name);
367                 if (pchan) {
368                         pchan->custom = get_empty_for_leaves();
369                 }
370                 else {
371                         fprintf(stderr, "Cannot find a pose channel for leaf bone %s\n", leaf.name);
372                 }
373         }
374 }
375
376 void ArmatureImporter::set_euler_rotmode()
377 {
378         // just set rotmode = ROT_MODE_EUL on pose channel for each joint
379
380         std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>::iterator it;
381
382         for (it = joint_by_uid.begin(); it != joint_by_uid.end(); it++) {
383
384                 COLLADAFW::Node *joint = it->second;
385
386                 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator sit;
387                 
388                 for (sit = skin_by_data_uid.begin(); sit != skin_by_data_uid.end(); sit++) {
389                         SkinInfo& skin = sit->second;
390
391                         if (skin.uses_joint_or_descendant(joint)) {
392                                 bPoseChannel *pchan = skin.get_pose_channel_from_node(joint);
393
394                                 if (pchan) {
395                                         pchan->rotmode = ROT_MODE_EUL;
396                                 }
397                                 else {
398                                         fprintf(stderr, "Cannot find pose channel for %s.\n", get_joint_name(joint));
399                                 }
400
401                                 break;
402                         }
403                 }
404         }
405 }
406 #endif
407
408 Object *ArmatureImporter::get_empty_for_leaves()
409 {
410         if (empty) return empty;
411         
412         empty = bc_add_object(scene, OB_EMPTY, NULL);
413         empty->empty_drawtype = OB_EMPTY_SPHERE;
414
415         return empty;
416 }
417
418 #if 0
419 Object *ArmatureImporter::find_armature(COLLADAFW::Node *node)
420 {
421         JointData *jd = get_joint_data(node);
422         if (jd) return jd->ob_arm;
423
424         COLLADAFW::NodePointerArray& children = node->getChildNodes();
425         for (int i = 0; i < children.getCount(); i++) {
426                 Object *ob_arm = find_armature(children[i]);
427                 if (ob_arm) return ob_arm;
428         }
429
430         return NULL;
431 }
432
433 ArmatureJoints& ArmatureImporter::get_armature_joints(Object *ob_arm)
434 {
435         // try finding it
436         std::vector<ArmatureJoints>::iterator it;
437         for (it = armature_joints.begin(); it != armature_joints.end(); it++) {
438                 if ((*it).ob_arm == ob_arm) return *it;
439         }
440
441         // not found, create one
442         ArmatureJoints aj;
443         aj.ob_arm = ob_arm;
444         armature_joints.push_back(aj);
445
446         return armature_joints.back();
447 }
448 #endif
449 void ArmatureImporter::create_armature_bones(std::vector<Object *> &ob_arms)
450 {
451         std::vector<COLLADAFW::Node *>::iterator ri;
452         std::vector<std::string> layer_labels;
453
454         //if there is an armature created for root_joint next root_joint
455         for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
456                 if (get_armature_for_joint(*ri) != NULL) continue;
457                 
458                 Object *ob_arm = joint_parent_map[(*ri)->getUniqueId()];
459                 if (!ob_arm)
460                         continue;
461
462                 bArmature * armature = (bArmature *)ob_arm->data;
463                 if (!armature)
464                         continue;
465
466                 char * bone_name = (char *)bc_get_joint_name(*ri);
467                 Bone *bone = BKE_armature_find_bone_name(armature, bone_name);
468                 if (bone) {
469                         fprintf(stderr, "Reuse of child bone [%s] as root bone in same Armature is not supported.\n", bone_name);
470                         continue;
471                 }
472
473                 ED_armature_to_edit(armature);
474                 armature->layer = 0; // layer is set according to imported bone set in create_bone()
475
476                 create_bone(NULL, *ri , NULL, (*ri)->getChildNodes().getCount(), NULL, armature, layer_labels);
477                 if (this->import_settings->find_chains) {
478                         connect_bone_chains(armature, (Bone *)armature->bonebase.first, UNLIMITED_CHAIN_MAX);
479                 }
480
481                 /* exit armature edit mode to populate the Armature object */
482                 ED_armature_from_edit(armature);
483                 ED_armature_edit_free(armature);
484
485                 ED_armature_to_edit(armature);
486
487                 fix_leaf_bone_hierarchy(armature, (Bone *)armature->bonebase.first, this->import_settings->fix_orientation);
488                 unskinned_armature_map[(*ri)->getUniqueId()] = ob_arm;
489
490                 ED_armature_from_edit(armature);
491                 ED_armature_edit_free(armature);
492
493                 int index = std::find(ob_arms.begin(), ob_arms.end(), ob_arm) - ob_arms.begin();
494                 if (index == 0) {
495                         ob_arms.push_back(ob_arm);
496                 }
497
498                 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB | OB_RECALC_DATA);
499         }
500 }
501
502 Object *ArmatureImporter::create_armature_bones(SkinInfo& skin)
503 {
504         // just do like so:
505         // - get armature
506         // - enter editmode
507         // - add edit bones and head/tail properties using matrices and parent-child info
508         // - exit edit mode
509         // - set a sphere shape to leaf bones
510
511         Object *ob_arm = NULL;
512
513         /*
514          * find if there's another skin sharing at least one bone with this skin
515          * if so, use that skin's armature
516          */
517
518         /*
519           Pseudocode:
520
521           find_node_in_tree(node, root_joint)
522
523           skin::find_root_joints(root_joints):
524                 std::vector root_joints;
525                 for each root in root_joints:
526                         for each joint in joints:
527                                 if find_node_in_tree(joint, root):
528                                         if (std::find(root_joints.begin(), root_joints.end(), root) == root_joints.end())
529                                                 root_joints.push_back(root);
530
531           for (each skin B with armature) {
532                   find all root joints for skin B
533
534                   for each joint X in skin A:
535                         for each root joint R in skin B:
536                                 if (find_node_in_tree(X, R)) {
537                                         shared = 1;
538                                         goto endloop;
539                                 }
540           }
541
542           endloop:
543         */
544
545         SkinInfo *a = &skin;
546         Object *shared = NULL;
547         std::vector<COLLADAFW::Node *> skin_root_joints;
548         std::vector<std::string> layer_labels;
549
550         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
551         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
552                 SkinInfo *b = &it->second;
553                 if (b == a || b->BKE_armature_from_object() == NULL)
554                         continue;
555
556                 skin_root_joints.clear();
557
558                 b->find_root_joints(root_joints, joint_by_uid, skin_root_joints);
559
560                 std::vector<COLLADAFW::Node *>::iterator ri;
561                 for (ri = skin_root_joints.begin(); ri != skin_root_joints.end(); ri++) {
562                         if (a->uses_joint_or_descendant(*ri)) {
563                                 shared = b->BKE_armature_from_object();
564                                 break;
565                         }
566                 }
567
568                 if (shared != NULL)
569                         break;
570         }
571
572         if (!shared && this->joint_parent_map.size() > 0) {
573                 // All armatures have been created while creating the Node tree. 
574                 // The Collada exporter currently does not create a 
575                 // strict relationship between geometries and armatures
576                 // So when we reimport a Blender collada file, then we have
577                 // to guess what is meant.
578                 // XXX This is not safe when we have more than one armatures
579                 // in the import.
580                 shared = this->joint_parent_map.begin()->second;
581         }
582
583         if (shared) {
584                 ob_arm = skin.set_armature(shared);
585         }
586         else {
587                 ob_arm = skin.create_armature(scene);  //once for every armature
588         }
589
590         // enter armature edit mode
591         bArmature * armature = (bArmature *)ob_arm->data;
592         ED_armature_to_edit(armature);
593
594         totbone = 0;
595         // bone_direction_row = 1; // TODO: don't default to Y but use asset and based on it decide on default row
596
597         // create bones
598         /*
599            TODO:
600            check if bones have already been created for a given joint
601          */
602
603         std::vector<COLLADAFW::Node *>::iterator ri;
604         for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
605                 // for shared armature check if bone tree is already created
606                 if (shared && std::find(skin_root_joints.begin(), skin_root_joints.end(), *ri) != skin_root_joints.end())
607                         continue;
608
609                 // since root_joints may contain joints for multiple controllers, we need to filter
610                 if (skin.uses_joint_or_descendant(*ri)) {
611
612                         create_bone(&skin, *ri, NULL, (*ri)->getChildNodes().getCount(), NULL, armature, layer_labels);
613
614                         if (joint_parent_map.find((*ri)->getUniqueId()) != joint_parent_map.end() && !skin.get_parent())
615                                 skin.set_parent(joint_parent_map[(*ri)->getUniqueId()]);
616                 }
617         }
618
619         /* exit armature edit mode to populate the Armature object */
620         ED_armature_from_edit(armature);
621         ED_armature_edit_free(armature);
622
623         ED_armature_to_edit(armature);
624         if (this->import_settings->find_chains) {
625                 connect_bone_chains(armature, (Bone *)armature->bonebase.first, UNLIMITED_CHAIN_MAX);
626         }
627         fix_leaf_bone_hierarchy(armature, (Bone *)armature->bonebase.first, this->import_settings->fix_orientation);
628         ED_armature_from_edit(armature);
629         ED_armature_edit_free(armature);
630
631         DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB | OB_RECALC_DATA);
632
633         return ob_arm;
634 }
635
636 void ArmatureImporter::set_pose(Object *ob_arm,  COLLADAFW::Node *root_node, const char *parentname, float parent_mat[4][4])
637
638         char *bone_name = (char *) bc_get_joint_name(root_node);
639         float mat[4][4];
640         float obmat[4][4];
641
642         // object-space
643         get_node_mat(obmat, root_node, NULL, NULL);
644
645         //if (*edbone)
646         bPoseChannel *pchan  = BKE_pose_channel_find_name(ob_arm->pose, bone_name);
647         //else fprintf ( "",
648
649         // get world-space
650         if (parentname) {
651                 mul_m4_m4m4(mat, parent_mat, obmat);
652                 bPoseChannel *parchan = BKE_pose_channel_find_name(ob_arm->pose, parentname);
653
654                 mul_m4_m4m4(pchan->pose_mat, parchan->pose_mat, mat);
655
656         }
657         else {
658                 
659                 copy_m4_m4(mat, obmat);
660                 float invObmat[4][4];
661                 invert_m4_m4(invObmat, ob_arm->obmat);
662                 mul_m4_m4m4(pchan->pose_mat, invObmat, mat);
663                 
664         }
665
666         //float angle = 0.0f;
667         ///*mat4_to_axis_angle(ax, &angle, mat);
668         //pchan->bone->roll = angle;*/
669
670
671         COLLADAFW::NodePointerArray& children = root_node->getChildNodes();
672         for (unsigned int i = 0; i < children.getCount(); i++) {
673                 set_pose(ob_arm, children[i], bone_name, mat);
674         }
675
676 }
677
678 /**
679   * root - if this joint is the top joint in hierarchy, if a joint
680   * is a child of a node (not joint), root should be true since
681   * this is where we build armature bones from
682   **/
683 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node, Object *parent)
684 {
685         root_joints.push_back(node);
686         if (parent) {
687                 joint_parent_map[node->getUniqueId()] = parent;
688         }
689 }
690
691 #if 0
692 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node)
693 {
694         // root_joints.push_back(node);
695         Object *ob_arm = find_armature(node);
696         if (ob_arm) {
697                 get_armature_joints(ob_arm).root_joints.push_back(node);
698         }
699 #ifdef COLLADA_DEBUG
700         else {
701                 fprintf(stderr, "%s cannot be added to armature.\n", get_joint_name(node));
702         }
703 #endif
704 }
705 #endif
706
707 // here we add bones to armatures, having armatures previously created in write_controller
708 void ArmatureImporter::make_armatures(bContext *C, std::vector<Object *> &objects_to_scale)
709 {
710         std::vector<Object *> ob_arms;
711         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
712
713         leaf_bone_length = FLT_MAX; /*TODO: Make this work for more than one armature in the import file*/
714
715         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
716
717                 SkinInfo& skin = it->second;
718
719                 Object *ob_arm = create_armature_bones(skin);
720
721                 // link armature with a mesh object
722                 const COLLADAFW::UniqueId &uid = skin.get_controller_uid();
723                 const COLLADAFW::UniqueId *guid = get_geometry_uid(uid);
724                 if (guid != NULL) {
725                         Object *ob = mesh_importer->get_object_by_geom_uid(*guid);
726                         if (ob) {
727                                 skin.link_armature(C, ob, joint_by_uid, this);
728
729                                 std::vector<Object *>::iterator ob_it = std::find(objects_to_scale.begin(), objects_to_scale.end(), ob);
730
731                                 if (ob_it != objects_to_scale.end()) {
732                                         int index = ob_it - objects_to_scale.begin();
733                                         objects_to_scale.erase(objects_to_scale.begin() + index);
734                                 }
735
736                                 if (std::find(objects_to_scale.begin(), objects_to_scale.end(), ob_arm) == objects_to_scale.end()) {
737                                         objects_to_scale.push_back(ob_arm);
738                                 }
739
740                                 if (std::find(ob_arms.begin(), ob_arms.end(), ob_arm) == ob_arms.end()) {
741                                         ob_arms.push_back(ob_arm);
742                                 }
743                         }
744                         else
745                                 fprintf(stderr, "Cannot find object to link armature with.\n");
746                 }
747                 else
748                         fprintf(stderr, "Cannot find geometry to link armature with.\n");
749
750                 // set armature parent if any
751                 Object *par = skin.get_parent();
752                 if (par)
753                         bc_set_parent(skin.BKE_armature_from_object(), par, C, false);
754
755                 // free memory stolen from SkinControllerData
756                 skin.free();
757         }
758         
759         //for bones without skins
760         create_armature_bones(ob_arms);
761
762         // Fix bone relations
763         std::vector<Object *>::iterator ob_arm_it;
764         for (ob_arm_it = ob_arms.begin(); ob_arm_it != ob_arms.end(); ob_arm_it++) {
765
766                 Object *ob_arm = *ob_arm_it;
767                 bArmature *armature = (bArmature *)ob_arm->data;
768
769                 /* and step back to edit mode to fix the leaf nodes */
770                 ED_armature_to_edit(armature);
771
772                 fix_parent_connect(armature, (Bone *)armature->bonebase.first);
773
774                 ED_armature_from_edit(armature);
775                 ED_armature_edit_free(armature);
776         }
777 }
778
779 #if 0
780 // link with meshes, create vertex groups, assign weights
781 void ArmatureImporter::link_armature(Object *ob_arm, const COLLADAFW::UniqueId& geom_id, const COLLADAFW::UniqueId& controller_data_id)
782 {
783         Object *ob = mesh_importer->get_object_by_geom_uid(geom_id);
784
785         if (!ob) {
786                 fprintf(stderr, "Cannot find object by geometry UID.\n");
787                 return;
788         }
789
790         if (skin_by_data_uid.find(controller_data_id) == skin_by_data_uid.end()) {
791                 fprintf(stderr, "Cannot find skin info by controller data UID.\n");
792                 return;
793         }
794
795         SkinInfo& skin = skin_by_data_uid[conroller_data_id];
796
797         // create vertex groups
798 }
799 #endif
800
801 bool ArmatureImporter::write_skin_controller_data(const COLLADAFW::SkinControllerData *data)
802 {
803         // at this stage we get vertex influence info that should go into me->verts and ob->defbase
804         // there's no info to which object this should be long so we associate it with skin controller data UID
805
806         // don't forget to call defgroup_unique_name before we copy
807
808         // controller data uid -> [armature] -> joint data, 
809         // [mesh object]
810         // 
811
812         SkinInfo skin(unit_converter);
813         skin.borrow_skin_controller_data(data);
814
815         // store join inv bind matrix to use it later in armature construction
816         const COLLADAFW::Matrix4Array& inv_bind_mats = data->getInverseBindMatrices();
817         for (unsigned int i = 0; i < data->getJointsCount(); i++) {
818                 skin.add_joint(inv_bind_mats[i]);
819         }
820
821         skin_by_data_uid[data->getUniqueId()] = skin;
822
823         return true;
824 }
825
826 bool ArmatureImporter::write_controller(const COLLADAFW::Controller *controller)
827 {
828         // - create and store armature object
829         const COLLADAFW::UniqueId& con_id = controller->getUniqueId();
830
831         if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_SKIN) {
832                 COLLADAFW::SkinController *co = (COLLADAFW::SkinController *)controller;
833                 // to be able to find geom id by controller id
834                 geom_uid_by_controller_uid[con_id] = co->getSource();
835
836                 const COLLADAFW::UniqueId& data_uid = co->getSkinControllerData();
837                 if (skin_by_data_uid.find(data_uid) == skin_by_data_uid.end()) {
838                         fprintf(stderr, "Cannot find skin by controller data UID.\n");
839                         return true;
840                 }
841
842                 skin_by_data_uid[data_uid].set_controller(co);
843         }
844         // morph controller
845         else if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_MORPH) {
846                 COLLADAFW::MorphController *co = (COLLADAFW::MorphController *)controller;
847                 // to be able to find geom id by controller id
848                 geom_uid_by_controller_uid[con_id] = co->getSource();
849                 //Shape keys are applied in DocumentImporter->finish()
850                 morph_controllers.push_back(co);
851         }
852
853         return true;
854 }
855
856 void ArmatureImporter::make_shape_keys()
857 {
858         std::vector<COLLADAFW::MorphController *>::iterator mc;
859         float weight;
860
861         for (mc = morph_controllers.begin(); mc != morph_controllers.end(); mc++) {
862                 //Controller data
863                 COLLADAFW::UniqueIdArray& morphTargetIds = (*mc)->getMorphTargets();
864                 COLLADAFW::FloatOrDoubleArray& morphWeights = (*mc)->getMorphWeights();
865
866                 //Prereq: all the geometries must be imported and mesh objects must be made
867                 Object *source_ob = this->mesh_importer->get_object_by_geom_uid((*mc)->getSource());
868                 
869                 if (source_ob) {
870
871                         Mesh *source_me = (Mesh *)source_ob->data;
872                         //insert key to source mesh
873                         Key *key = source_me->key = BKE_key_add((ID *)source_me);
874                         key->type = KEY_RELATIVE;
875                         KeyBlock *kb;
876                         
877                         //insert basis key
878                         kb = BKE_keyblock_add_ctime(key, "Basis", false);
879                         BKE_keyblock_convert_from_mesh(source_me, kb);
880
881                         //insert other shape keys
882                         for (int i = 0 ; i < morphTargetIds.getCount() ; i++ ) {
883                                 //better to have a separate map of morph objects,
884                                 //This'll do for now since only mesh morphing is imported
885
886                                 Mesh *me = this->mesh_importer->get_mesh_by_geom_uid(morphTargetIds[i]);
887                                 
888                                 if (me) {
889                                         me->key = key;
890                                         std::string morph_name = *this->mesh_importer->get_geometry_name(me->id.name);
891
892                                         kb = BKE_keyblock_add_ctime(key, morph_name.c_str(), false);
893                                         BKE_keyblock_convert_from_mesh(me, kb);
894                                         
895                                         //apply weights
896                                         weight =  morphWeights.getFloatValues()->getData()[i];
897                                         kb->curval = weight;
898                                 }
899                                 else {
900                                         fprintf(stderr, "Morph target geometry not found.\n");
901                                 }
902                         }
903                 }
904                 else {
905                         fprintf(stderr, "Morph target object not found.\n");
906                 }
907         }
908 }
909
910
911 COLLADAFW::UniqueId *ArmatureImporter::get_geometry_uid(const COLLADAFW::UniqueId& controller_uid)
912 {
913         if (geom_uid_by_controller_uid.find(controller_uid) == geom_uid_by_controller_uid.end())
914                 return NULL;
915
916         return &geom_uid_by_controller_uid[controller_uid];
917 }
918
919 Object *ArmatureImporter::get_armature_for_joint(COLLADAFW::Node *node)
920 {
921         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
922         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
923                 SkinInfo& skin = it->second;
924
925                 if (skin.uses_joint_or_descendant(node))
926                         return skin.BKE_armature_from_object();
927         }
928
929         std::map<COLLADAFW::UniqueId, Object *>::iterator arm;
930         for (arm = unskinned_armature_map.begin(); arm != unskinned_armature_map.end(); arm++) {
931                 if (arm->first == node->getUniqueId() )
932                         return arm->second;
933         }
934         return NULL;
935 }
936
937 void ArmatureImporter::set_tags_map(TagsMap & tagsMap)
938 {
939         this->uid_tags_map = tagsMap;
940 }
941
942 void ArmatureImporter::get_rna_path_for_joint(COLLADAFW::Node *node, char *joint_path, size_t count)
943 {
944         BLI_snprintf(joint_path, count, "pose.bones[\"%s\"]", bc_get_joint_name(node));
945 }
946
947 // gives a world-space mat
948 bool ArmatureImporter::get_joint_bind_mat(float m[4][4], COLLADAFW::Node *joint)
949 {
950         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
951         bool found = false;
952         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
953                 SkinInfo& skin = it->second;
954                 if ((found = skin.get_joint_inv_bind_matrix(m, joint))) {
955                         invert_m4(m);
956                         break;
957                 }
958         }
959
960         return found;
961 }
962
963 BoneExtended &ArmatureImporter::add_bone_extended(EditBone *bone, COLLADAFW::Node *node, int sibcount, std::vector<std::string> &layer_labels, BoneExtensionMap &extended_bones)
964 {
965         BoneExtended *be = new BoneExtended(bone);
966         extended_bones[bone->name] = be;
967
968         TagsMap::iterator etit;
969         ExtraTags *et = 0;
970         etit = uid_tags_map.find(node->getUniqueId().toAscii());
971
972         bool has_connect = false;
973         int connect_type = -1;
974
975         if (etit != uid_tags_map.end()) {
976
977                 float tail[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
978                 float roll = 0;
979                 std::string layers;
980
981                 et = etit->second;
982
983                 bool has_tail = false;
984                 has_tail |= et->setData("tip_x", &tail[0]);
985                 has_tail |= et->setData("tip_y", &tail[1]);
986                 has_tail |= et->setData("tip_z", &tail[2]);
987
988                 has_connect   = et->setData("connect", &connect_type);
989                 bool has_roll = et->setData("roll", &roll);
990                 
991                 layers = et->setData("layer", layers);
992
993                 if (has_tail && !has_connect)
994                 {
995                         /* got a bone tail definition but no connect info -> bone is not connected */
996                         has_connect  = true;
997                         connect_type = 0; 
998                 }
999
1000                 be->set_bone_layers(layers, layer_labels);
1001                 if (has_tail) be->set_tail(tail);
1002                 if (has_roll) be->set_roll(roll);
1003         }
1004
1005         if (!has_connect && this->import_settings->auto_connect) {
1006                 /* auto connect only whyen parent has exactly one child*/
1007                 connect_type = sibcount == 1;
1008         }
1009
1010         be->set_use_connect(connect_type);
1011         be->set_leaf_bone(true);
1012
1013         return *be;
1014 }