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