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