Armature object animations export.
[blender-staging.git] / source / blender / collada / ArmatureExporter.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
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.
10  *
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.
15  *
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Jan Diederich, Tod Liverseed,
21  *                 Nathan Letwory
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/collada/ArmatureExporter.cpp
27  *  \ingroup collada
28  */
29
30
31 #include "COLLADASWBaseInputElement.h"
32 #include "COLLADASWInstanceController.h"
33 #include "COLLADASWPrimitves.h"
34 #include "COLLADASWSource.h"
35
36 #include "DNA_action_types.h"
37 #include "DNA_meshdata_types.h"
38 #include "DNA_modifier_types.h"
39
40 #include "BKE_action.h"
41 #include "BKE_armature.h"
42 #include "ED_armature.h"
43
44 #include "BLI_listbase.h"
45
46 #include "GeometryExporter.h"
47 #include "ArmatureExporter.h"
48
49 // XXX exporter writes wrong data for shared armatures.  A separate
50 // controller should be written for each armature-mesh binding how do
51 // we make controller ids then?
52 ArmatureExporter::ArmatureExporter(COLLADASW::StreamWriter *sw) : COLLADASW::LibraryControllers(sw) {}
53
54 // write bone nodes
55 void ArmatureExporter::add_armature_bones(Object *ob_arm, Scene *sce)
56 {
57         // write bone nodes
58         bArmature *arm = (bArmature*)ob_arm->data;
59         for (Bone *bone = (Bone*)arm->bonebase.first; bone; bone = bone->next) {
60                 // start from root bones
61                 if (!bone->parent)
62                         add_bone_node(bone, ob_arm);
63         }
64 }
65
66 bool ArmatureExporter::is_skinned_mesh(Object *ob)
67 {
68         return get_assigned_armature(ob) != NULL;
69 }
70
71 void ArmatureExporter::add_instance_controller(Object *ob)
72 {
73         Object *ob_arm = get_assigned_armature(ob);
74         bArmature *arm = (bArmature*)ob_arm->data;
75
76         const std::string& controller_id = get_controller_id(ob_arm, ob);
77
78         COLLADASW::InstanceController ins(mSW);
79         ins.setUrl(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, controller_id));
80
81         // write root bone URLs
82         Bone *bone;
83         for (bone = (Bone*)arm->bonebase.first; bone; bone = bone->next) {
84                 if (!bone->parent)
85                         ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(bone, ob_arm)));
86         }
87
88         InstanceWriter::add_material_bindings(ins.getBindMaterial(), ob);
89                 
90         ins.add();
91 }
92
93 void ArmatureExporter::export_controllers(Scene *sce, bool export_selected)
94 {
95         scene = sce;
96
97         openLibrary();
98
99         GeometryFunctor gf;
100         gf.forEachMeshObjectInScene<ArmatureExporter>(sce, *this, export_selected);
101
102         closeLibrary();
103 }
104
105 void ArmatureExporter::operator()(Object *ob)
106 {
107         Object *ob_arm = get_assigned_armature(ob);
108
109         if (ob_arm /*&& !already_written(ob_arm)*/)
110                 export_controller(ob, ob_arm);
111 }
112 #if 0
113
114 bool ArmatureExporter::already_written(Object *ob_arm)
115 {
116         return std::find(written_armatures.begin(), written_armatures.end(), ob_arm) != written_armatures.end();
117 }
118
119 void ArmatureExporter::wrote(Object *ob_arm)
120 {
121         written_armatures.push_back(ob_arm);
122 }
123
124 void ArmatureExporter::find_objects_using_armature(Object *ob_arm, std::vector<Object *>& objects, Scene *sce)
125 {
126         objects.clear();
127
128         Base *base= (Base*) sce->base.first;
129         while(base) {
130                 Object *ob = base->object;
131                 
132                 if (ob->type == OB_MESH && get_assigned_armature(ob) == ob_arm) {
133                         objects.push_back(ob);
134                 }
135
136                 base= base->next;
137         }
138 }
139 #endif
140
141 Object *ArmatureExporter::get_assigned_armature(Object *ob)
142 {
143         Object *ob_arm = NULL;
144
145         if (ob->parent && ob->partype == PARSKEL && ob->parent->type == OB_ARMATURE) {
146                 ob_arm = ob->parent;
147         }
148         else {
149                 ModifierData *mod = (ModifierData*)ob->modifiers.first;
150                 while (mod) {
151                         if (mod->type == eModifierType_Armature) {
152                                 ob_arm = ((ArmatureModifierData*)mod)->object;
153                         }
154
155                         mod = mod->next;
156                 }
157         }
158
159         return ob_arm;
160 }
161
162 std::string ArmatureExporter::get_joint_sid(Bone *bone, Object *ob_arm)
163 {
164         return get_joint_id(bone, ob_arm);
165 }
166
167 // parent_mat is armature-space
168 void ArmatureExporter::add_bone_node(Bone *bone, Object *ob_arm)
169 {
170         std::string node_id = get_joint_id(bone, ob_arm);
171         std::string node_name = std::string(bone->name);
172         std::string node_sid = get_joint_sid(bone, ob_arm);
173
174         COLLADASW::Node node(mSW);
175
176         node.setType(COLLADASW::Node::JOINT);
177         node.setNodeId(node_id);
178         node.setNodeName(node_name);
179         node.setNodeSid(node_sid);
180
181         /*if ( bone->childbase.first == NULL || BLI_countlist(&(bone->childbase))>=2)
182                 add_blender_leaf_bone( bone, ob_arm , node );
183         else{*/
184         node.start();
185
186         add_bone_transform(ob_arm, bone, node);
187
188         for (Bone *child = (Bone*)bone->childbase.first; child; child = child->next) {
189                 add_bone_node(child, ob_arm);
190         }
191     node.end();
192         //}
193 }
194
195 void ArmatureExporter::add_blender_leaf_bone(Bone *bone, Object *ob_arm, COLLADASW::Node& node)
196 {
197         node.start();
198         
199         add_bone_transform(ob_arm, bone, node);
200         
201         node.addExtraTechniqueParameter("blender", "tip_x", bone->tail[0] );
202         node.addExtraTechniqueParameter("blender", "tip_y", bone->tail[1] );
203         node.addExtraTechniqueParameter("blender", "tip_z", bone->tail[2] );
204         
205         for (Bone *child = (Bone*)bone->childbase.first; child; child = child->next) {
206                 add_bone_node(child, ob_arm);
207         }
208         node.end();
209         
210 }
211 void ArmatureExporter::add_bone_transform(Object *ob_arm, Bone *bone, COLLADASW::Node& node)
212 {
213         bPoseChannel *pchan = get_pose_channel(ob_arm->pose, bone->name);
214
215         float mat[4][4];
216
217         if (bone->parent) {
218                 // get bone-space matrix from armature-space
219                 bPoseChannel *parchan = get_pose_channel(ob_arm->pose, bone->parent->name);
220
221                 float invpar[4][4];
222                 invert_m4_m4(invpar, parchan->pose_mat);
223                 mul_m4_m4m4(mat, pchan->pose_mat, invpar);
224         }
225         else {
226                 // get world-space from armature-space
227                 mul_m4_m4m4(mat, pchan->pose_mat, ob_arm->obmat);
228         }
229
230         TransformWriter::add_node_transform(node, mat,NULL );
231 }
232
233 std::string ArmatureExporter::get_controller_id(Object *ob_arm, Object *ob)
234 {
235         return translate_id(id_name(ob_arm)) + "_" + translate_id(id_name(ob)) + SKIN_CONTROLLER_ID_SUFFIX;
236 }
237
238 // ob should be of type OB_MESH
239 // both args are required
240 void ArmatureExporter::export_controller(Object* ob, Object *ob_arm)
241 {
242         // joint names
243         // joint inverse bind matrices
244         // vertex weights
245
246         // input:
247         // joint names: ob -> vertex group names
248         // vertex group weights: me->dvert -> groups -> index, weight
249
250         /*
251         me->dvert:
252
253         typedef struct MDeformVert {
254                 struct MDeformWeight *dw;
255                 int totweight;
256                 int flag;       // flag only in use for weightpaint now
257         } MDeformVert;
258
259         typedef struct MDeformWeight {
260                 int                             def_nr;
261                 float                   weight;
262         } MDeformWeight;
263         */
264
265         Mesh *me = (Mesh*)ob->data;
266         if (!me->dvert) return;
267
268         std::string controller_name = id_name(ob_arm);
269         std::string controller_id = get_controller_id(ob_arm, ob);
270
271         openSkin(controller_id, controller_name,
272                          COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob)));
273
274         add_bind_shape_mat(ob);
275
276         std::string joints_source_id = add_joints_source(ob_arm, &ob->defbase, controller_id);
277         std::string inv_bind_mat_source_id = add_inv_bind_mats_source(ob_arm, &ob->defbase, controller_id);
278         std::string weights_source_id = add_weights_source(me, controller_id);
279
280         add_joints_element(&ob->defbase, joints_source_id, inv_bind_mat_source_id);
281         add_vertex_weights_element(weights_source_id, joints_source_id, me, ob_arm, &ob->defbase);
282
283         closeSkin();
284         closeController();
285 }
286
287 void ArmatureExporter::add_joints_element(ListBase *defbase,
288                                                 const std::string& joints_source_id, const std::string& inv_bind_mat_source_id)
289 {
290         COLLADASW::JointsElement joints(mSW);
291         COLLADASW::InputList &input = joints.getInputList();
292
293         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
294                                                            COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id)));
295         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::BINDMATRIX,
296                                                            COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, inv_bind_mat_source_id)));
297         joints.add();
298 }
299
300 void ArmatureExporter::add_bind_shape_mat(Object *ob)
301 {
302         double bind_mat[4][4];
303
304         converter.mat4_to_dae_double(bind_mat, ob->obmat);
305
306         addBindShapeTransform(bind_mat);
307 }
308
309 std::string ArmatureExporter::add_joints_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
310 {
311         std::string source_id = controller_id + JOINTS_SOURCE_ID_SUFFIX;
312
313         int totjoint = 0;
314         bDeformGroup *def;
315         for (def = (bDeformGroup*)defbase->first; def; def = def->next) {
316                 if (is_bone_defgroup(ob_arm, def))
317                         totjoint++;
318         }
319
320         COLLADASW::NameSource source(mSW);
321         source.setId(source_id);
322         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
323         source.setAccessorCount(totjoint);
324         source.setAccessorStride(1);
325         
326         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
327         param.push_back("JOINT");
328
329         source.prepareToAppendValues();
330
331         for (def = (bDeformGroup*)defbase->first; def; def = def->next) {
332                 Bone *bone = get_bone_from_defgroup(ob_arm, def);
333                 if (bone)
334                         source.appendValues(get_joint_sid(bone, ob_arm));
335         }
336
337         source.finish();
338
339         return source_id;
340 }
341
342 std::string ArmatureExporter::add_inv_bind_mats_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
343 {
344         std::string source_id = controller_id + BIND_POSES_SOURCE_ID_SUFFIX;
345
346         COLLADASW::FloatSourceF source(mSW);
347         source.setId(source_id);
348         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
349         source.setAccessorCount(BLI_countlist(defbase));
350         source.setAccessorStride(16);
351         
352         source.setParameterTypeName(&COLLADASW::CSWC::CSW_VALUE_TYPE_FLOAT4x4);
353         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
354         param.push_back("TRANSFORM");
355
356         source.prepareToAppendValues();
357
358         bPose *pose = ob_arm->pose;
359         bArmature *arm = (bArmature*)ob_arm->data;
360
361         int flag = arm->flag;
362
363         // put armature in rest position
364         if (!(arm->flag & ARM_RESTPOS)) {
365                 arm->flag |= ARM_RESTPOS;
366                 where_is_pose(scene, ob_arm);
367         }
368
369         for (bDeformGroup *def = (bDeformGroup*)defbase->first; def; def = def->next) {
370                 if (is_bone_defgroup(ob_arm, def)) {
371
372                         bPoseChannel *pchan = get_pose_channel(pose, def->name);
373
374                         float mat[4][4];
375                         float world[4][4];
376                         float inv_bind_mat[4][4];
377
378                         // make world-space matrix, arm_mat is armature-space
379                         mul_m4_m4m4(world, pchan->bone->arm_mat, ob_arm->obmat);
380                         
381                         invert_m4_m4(mat, world);
382                         converter.mat4_to_dae(inv_bind_mat, mat);
383
384                         source.appendValues(inv_bind_mat);
385                 }
386         }
387
388         // back from rest positon
389         if (!(flag & ARM_RESTPOS)) {
390                 arm->flag = flag;
391                 where_is_pose(scene, ob_arm);
392         }
393
394         source.finish();
395
396         return source_id;
397 }
398
399 Bone *ArmatureExporter::get_bone_from_defgroup(Object *ob_arm, bDeformGroup* def)
400 {
401         bPoseChannel *pchan = get_pose_channel(ob_arm->pose, def->name);
402         return pchan ? pchan->bone : NULL;
403 }
404
405 bool ArmatureExporter::is_bone_defgroup(Object *ob_arm, bDeformGroup* def)
406 {
407         return get_bone_from_defgroup(ob_arm, def) != NULL;
408 }
409
410 std::string ArmatureExporter::add_weights_source(Mesh *me, const std::string& controller_id)
411 {
412         std::string source_id = controller_id + WEIGHTS_SOURCE_ID_SUFFIX;
413
414         int i;
415         int totweight = 0;
416
417         for (i = 0; i < me->totvert; i++) {
418                 totweight += me->dvert[i].totweight;
419         }
420
421         COLLADASW::FloatSourceF source(mSW);
422         source.setId(source_id);
423         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
424         source.setAccessorCount(totweight);
425         source.setAccessorStride(1);
426         
427         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
428         param.push_back("WEIGHT");
429
430         source.prepareToAppendValues();
431
432         // NOTE: COLLADA spec says weights should be normalized
433
434         for (i = 0; i < me->totvert; i++) {
435                 MDeformVert *vert = &me->dvert[i];
436                 for (int j = 0; j < vert->totweight; j++) {
437                         source.appendValues(vert->dw[j].weight);
438                 }
439         }
440
441         source.finish();
442
443         return source_id;
444 }
445
446 void ArmatureExporter::add_vertex_weights_element(const std::string& weights_source_id, const std::string& joints_source_id, Mesh *me,
447                                                                 Object *ob_arm, ListBase *defbase)
448 {
449         COLLADASW::VertexWeightsElement weights(mSW);
450         COLLADASW::InputList &input = weights.getInputList();
451
452         int offset = 0;
453         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
454                                                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id), offset++));
455         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::WEIGHT,
456                                                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, weights_source_id), offset++));
457
458         weights.setCount(me->totvert);
459
460         // write number of deformers per vertex
461         COLLADASW::PrimitivesBase::VCountList vcount;
462         int i;
463         for (i = 0; i < me->totvert; i++) {
464                 vcount.push_back(me->dvert[i].totweight);
465         }
466
467         weights.prepareToAppendVCountValues();
468         weights.appendVertexCount(vcount);
469
470         // def group index -> joint index
471         std::map<int, int> joint_index_by_def_index;
472         bDeformGroup *def;
473         int j;
474         for (def = (bDeformGroup*)defbase->first, i = 0, j = 0; def; def = def->next, i++) {
475                 if (is_bone_defgroup(ob_arm, def))
476                         joint_index_by_def_index[i] = j++;
477                 else
478                         joint_index_by_def_index[i] = -1;
479         }
480
481         weights.CloseVCountAndOpenVElement();
482
483         // write deformer index - weight index pairs
484         int weight_index = 0;
485         for (i = 0; i < me->totvert; i++) {
486                 MDeformVert *dvert = &me->dvert[i];
487                 for (int j = 0; j < dvert->totweight; j++) {
488                         weights.appendValues(joint_index_by_def_index[dvert->dw[j].def_nr]);
489                         weights.appendValues(weight_index++);
490                 }
491         }
492
493         weights.finish();
494 }