style cleanup
[blender.git] / source / blender / collada / ControllerExporter.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, Jan Diederich, Tod Liverseed,
19  *                 Nathan Letwory, Sukhitha Jayathilake
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/collada/ControllerExporter.cpp
25  *  \ingroup collada
26  */
27
28 #include "COLLADASWBaseInputElement.h"
29 #include "COLLADASWInstanceController.h"
30 #include "COLLADASWPrimitves.h"
31 #include "COLLADASWSource.h"
32
33 #include "DNA_action_types.h"
34 #include "DNA_meshdata_types.h"
35 #include "DNA_modifier_types.h"
36
37 #include "BKE_action.h"
38 #include "BKE_armature.h"
39
40 extern "C" {
41 #include "BKE_main.h"
42 #include "BKE_mesh.h"
43 #include "BKE_global.h"
44 #include "BKE_library.h"
45 }
46
47 #include "ED_armature.h"
48
49 #include "BLI_listbase.h"
50
51 #include "GeometryExporter.h"
52 #include "ArmatureExporter.h"
53 #include "ControllerExporter.h"
54 #include "SceneExporter.h"
55
56 #include "collada_utils.h"
57
58 // XXX exporter writes wrong data for shared armatures.  A separate
59 // controller should be written for each armature-mesh binding how do
60 // we make controller ids then?
61 ControllerExporter::ControllerExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings) : COLLADASW::LibraryControllers(sw), export_settings(export_settings) {
62 }
63
64 bool ControllerExporter::is_skinned_mesh(Object *ob)
65 {
66         return bc_get_assigned_armature(ob) != NULL;
67 }
68
69
70 void ControllerExporter::write_bone_URLs(COLLADASW::InstanceController &ins, Object *ob_arm, Bone *bone)
71 {
72         if (bc_is_root_bone(bone, this->export_settings->deform_bones_only))
73                 ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(bone, ob_arm)));
74         else {
75                 for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
76                         write_bone_URLs(ins, ob_arm, child);
77                 }
78         }
79 }
80
81 bool ControllerExporter::add_instance_controller(Object *ob)
82 {
83         Object *ob_arm = bc_get_assigned_armature(ob);
84         bArmature *arm = (bArmature *)ob_arm->data;
85
86         const std::string& controller_id = get_controller_id(ob_arm, ob);
87
88         COLLADASW::InstanceController ins(mSW);
89         ins.setUrl(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, controller_id));
90
91         Mesh *me = (Mesh *)ob->data;
92         if (!me->dvert) return false;
93
94         // write root bone URLs
95         Bone *bone;
96         for (bone = (Bone *)arm->bonebase.first; bone; bone = bone->next) {
97                 write_bone_URLs(ins, ob_arm, bone);
98         }
99
100         InstanceWriter::add_material_bindings(ins.getBindMaterial(), ob, this->export_settings->active_uv_only);
101                 
102         ins.add();
103         return true;
104 }
105
106 void ControllerExporter::export_controllers(Scene *sce)
107 {
108         scene = sce;
109
110         openLibrary();
111
112         GeometryFunctor gf;
113         gf.forEachMeshObjectInExportSet<ControllerExporter>(sce, *this, this->export_settings->export_set);
114
115         closeLibrary();
116 }
117
118 void ControllerExporter::operator()(Object *ob)
119 {
120         Object *ob_arm = bc_get_assigned_armature(ob);
121         Key *key = BKE_key_from_object(ob);
122
123         if (ob_arm) {
124                 export_skin_controller(ob, ob_arm);
125         }
126         if (key) {
127                 export_morph_controller(ob, key);
128         }
129 }
130 #if 0
131
132 bool ArmatureExporter::already_written(Object *ob_arm)
133 {
134         return std::find(written_armatures.begin(), written_armatures.end(), ob_arm) != written_armatures.end();
135 }
136
137 void ArmatureExporter::wrote(Object *ob_arm)
138 {
139         written_armatures.push_back(ob_arm);
140 }
141
142 void ArmatureExporter::find_objects_using_armature(Object *ob_arm, std::vector<Object *>& objects, Scene *sce)
143 {
144         objects.clear();
145
146         Base *base = (Base *) sce->base.first;
147         while (base) {
148                 Object *ob = base->object;
149                 
150                 if (ob->type == OB_MESH && get_assigned_armature(ob) == ob_arm) {
151                         objects.push_back(ob);
152                 }
153
154                 base = base->next;
155         }
156 }
157 #endif
158
159 std::string ControllerExporter::get_joint_sid(Bone *bone, Object *ob_arm)
160 {
161         return get_joint_id(bone, ob_arm);
162 }
163
164 std::string ControllerExporter::get_controller_id(Object *ob_arm, Object *ob)
165 {
166         return translate_id(id_name(ob_arm)) + "_" + translate_id(id_name(ob)) + SKIN_CONTROLLER_ID_SUFFIX;
167 }
168
169 std::string ControllerExporter::get_controller_id(Key *key, Object *ob)
170 {
171         return translate_id(id_name(ob)) + MORPH_CONTROLLER_ID_SUFFIX;
172 }
173
174 // ob should be of type OB_MESH
175 // both args are required
176 void ControllerExporter::export_skin_controller(Object *ob, Object *ob_arm)
177 {
178         // joint names
179         // joint inverse bind matrices
180         // vertex weights
181
182         // input:
183         // joint names: ob -> vertex group names
184         // vertex group weights: me->dvert -> groups -> index, weight
185
186 #if 0
187         me->dvert :
188
189         typedef struct MDeformVert {
190                 struct MDeformWeight *dw;
191                 int totweight;
192                 int flag;   // flag only in use for weightpaint now
193         } MDeformVert;
194
195         typedef struct MDeformWeight {
196                 int def_nr;
197                 float weight;
198         } MDeformWeight;
199 #endif
200
201         bool use_instantiation = this->export_settings->use_object_instantiation;
202         Mesh *me;
203
204         me = bc_get_mesh_copy(scene,
205                                 ob,
206                                 this->export_settings->export_mesh_type,
207                                 this->export_settings->apply_modifiers,
208                                 this->export_settings->triangulate);
209         
210         if (!me->dvert) return;
211
212         std::string controller_name = id_name(ob_arm);
213         std::string controller_id = get_controller_id(ob_arm, ob);
214
215         openSkin(controller_id, controller_name,
216                  COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
217
218         add_bind_shape_mat(ob);
219
220         std::string joints_source_id = add_joints_source(ob_arm, &ob->defbase, controller_id);
221         std::string inv_bind_mat_source_id = add_inv_bind_mats_source(ob_arm, &ob->defbase, controller_id);
222
223         std::list<int> vcounts;
224         std::list<int> joints;
225         std::list<float> weights;
226
227         {
228                 int i, j;
229
230                 // def group index -> joint index
231                 std::vector<int> joint_index_by_def_index;
232                 bDeformGroup *def;
233
234                 for (def = (bDeformGroup *)ob->defbase.first, i = 0, j = 0; def; def = def->next, i++) {
235                         if (is_bone_defgroup(ob_arm, def))
236                                 joint_index_by_def_index.push_back(j++);
237                         else
238                                 joint_index_by_def_index.push_back(-1);
239                 }
240
241                 int oob_counter = 0;
242                 for (i = 0; i < me->totvert; i++) {
243                         MDeformVert *vert = &me->dvert[i];
244                         std::map<int, float> jw;
245
246                         // We're normalizing the weights later
247                         float sumw = 0.0f;
248
249                         for (j = 0; j < vert->totweight; j++) {
250                                 int idx = vert->dw[j].def_nr;
251                                 if (idx >= joint_index_by_def_index.size()) {
252                                         // XXX: Maybe better find out where and 
253                                         //      why the Out Of Bound indexes get created ?
254                                         oob_counter += 1;
255                                 }
256                                 else {
257                                         if (idx >= 0) {
258                                                 int joint_index = joint_index_by_def_index[idx];
259                                                 if (joint_index != -1 && vert->dw[j].weight > 0.0f) {
260                                                         jw[joint_index] += vert->dw[j].weight;
261                                                         sumw += vert->dw[j].weight;
262                                                 }
263                                         }
264                                 }
265                         }
266
267                         if (sumw > 0.0f) {
268                                 float invsumw = 1.0f / sumw;
269                                 vcounts.push_back(jw.size());
270                                 for (std::map<int, float>::iterator m = jw.begin(); m != jw.end(); ++m) {
271                                         joints.push_back((*m).first);
272                                         weights.push_back(invsumw * (*m).second);
273                                 }
274                         }
275                         else {
276                                 vcounts.push_back(0);
277 #if 0
278                                 vcounts.push_back(1);
279                                 joints.push_back(-1);
280                                 weights.push_back(1.0f);
281 #endif
282                         }
283                 }
284
285                 if (oob_counter > 0) {
286                         fprintf(stderr, "Ignored %d Vertex weigths which use index to non existing VGroup %ld.\n", oob_counter, joint_index_by_def_index.size());
287                 }
288         }
289
290         std::string weights_source_id = add_weights_source(me, controller_id, weights);
291         add_joints_element(&ob->defbase, joints_source_id, inv_bind_mat_source_id);
292         add_vertex_weights_element(weights_source_id, joints_source_id, vcounts, joints);
293
294         BKE_libblock_free_us(&(G.main->mesh), me);
295
296         closeSkin();
297         closeController();
298 }
299
300 void ControllerExporter::export_morph_controller(Object *ob, Key *key)
301 {
302         bool use_instantiation = this->export_settings->use_object_instantiation;
303         Mesh *me;
304
305         me = bc_get_mesh_copy(scene,
306                                 ob,
307                                 this->export_settings->export_mesh_type,
308                                 this->export_settings->apply_modifiers,
309                                 this->export_settings->triangulate);
310
311         std::string controller_name = id_name(ob) + "-morph";
312         std::string controller_id = get_controller_id(key, ob);
313
314         openMorph(controller_id, controller_name,
315                  COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
316
317         std::string targets_id = add_morph_targets(key, ob);
318         std::string morph_weights_id = add_morph_weights(key, ob);
319         
320         COLLADASW::TargetsElement targets(mSW);
321
322         COLLADASW::InputList &input = targets.getInputList();
323
324         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::MORPH_TARGET, // constant declared in COLLADASWInputList.h
325                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, targets_id)));
326         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::MORPH_WEIGHT,
327                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, morph_weights_id)));
328         targets.add();
329
330         BKE_libblock_free_us(&(G.main->mesh), me);
331
332
333         //support for animations
334         //can also try the base element and param alternative
335         add_weight_extras(key);
336         closeMorph();
337         closeController();
338 }
339
340 std::string ControllerExporter::add_morph_targets(Key *key, Object *ob)
341 {
342         std::string source_id = translate_id(id_name(ob)) + TARGETS_SOURCE_ID_SUFFIX;
343
344         COLLADASW::IdRefSource source(mSW);
345         source.setId(source_id);
346         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
347         source.setAccessorCount(key->totkey - 1);
348         source.setAccessorStride(1);
349
350         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
351         param.push_back("IDREF");
352
353         source.prepareToAppendValues();
354
355         KeyBlock *kb = (KeyBlock *)key->block.first;
356         //skip the basis
357         kb = kb->next;
358         for (; kb; kb = kb->next) {
359                 std::string geom_id = get_geometry_id(ob, false) + "_morph_" + translate_id(kb->name);
360                 source.appendValues(geom_id);
361
362         }
363
364         source.finish();
365
366         return source_id;
367 }
368
369 std::string ControllerExporter::add_morph_weights(Key *key, Object *ob)
370 {
371         std::string source_id = translate_id(id_name(ob)) + WEIGHTS_SOURCE_ID_SUFFIX;
372
373         COLLADASW::FloatSourceF source(mSW);
374         source.setId(source_id);
375         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
376         source.setAccessorCount(key->totkey - 1);
377         source.setAccessorStride(1);
378
379         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
380         param.push_back("MORPH_WEIGHT");
381         
382         source.prepareToAppendValues();
383
384         KeyBlock *kb = (KeyBlock *)key->block.first;
385         //skip the basis
386         kb = kb->next;
387         for (; kb; kb = kb->next) {
388                 float weight = kb->curval;
389                 source.appendValues(weight);
390         }
391         source.finish();
392
393         return source_id;
394 }
395
396 //Added to implemente support for animations.
397 void ControllerExporter::add_weight_extras(Key *key)
398 {
399         // can also try the base element and param alternative
400         COLLADASW::BaseExtraTechnique extra;
401         
402         KeyBlock * kb = (KeyBlock *)key->block.first;
403         //skip the basis
404         kb = kb->next;
405         for (; kb; kb = kb->next) {
406                 // XXX why is the weight not used here and set to 0.0?
407                 // float weight = kb->curval;
408                 extra.addExtraTechniqueParameter ("KHR", "morph_weights" , 0.000, "MORPH_WEIGHT_TO_TARGET");
409         }
410 }
411
412
413
414 void ControllerExporter::add_joints_element(ListBase *defbase,
415                                           const std::string& joints_source_id, const std::string& inv_bind_mat_source_id)
416 {
417         COLLADASW::JointsElement joints(mSW);
418         COLLADASW::InputList &input = joints.getInputList();
419
420         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
421                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id)));
422         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::BINDMATRIX,
423                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, inv_bind_mat_source_id)));
424         joints.add();
425 }
426
427 void ControllerExporter::add_bind_shape_mat(Object *ob)
428 {
429         double bind_mat[4][4];
430
431         converter.mat4_to_dae_double(bind_mat, ob->obmat);
432
433         addBindShapeTransform(bind_mat);
434 }
435
436 std::string ControllerExporter::add_joints_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
437 {
438         std::string source_id = controller_id + JOINTS_SOURCE_ID_SUFFIX;
439
440         int totjoint = 0;
441         bDeformGroup *def;
442         for (def = (bDeformGroup *)defbase->first; def; def = def->next) {
443                 if (is_bone_defgroup(ob_arm, def))
444                         totjoint++;
445         }
446
447         COLLADASW::NameSource source(mSW);
448         source.setId(source_id);
449         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
450         source.setAccessorCount(totjoint);
451         source.setAccessorStride(1);
452         
453         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
454         param.push_back("JOINT");
455
456         source.prepareToAppendValues();
457
458         for (def = (bDeformGroup *)defbase->first; def; def = def->next) {
459                 Bone *bone = get_bone_from_defgroup(ob_arm, def);
460                 if (bone)
461                         source.appendValues(get_joint_sid(bone, ob_arm));
462         }
463
464         source.finish();
465
466         return source_id;
467 }
468
469 std::string ControllerExporter::add_inv_bind_mats_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
470 {
471         std::string source_id = controller_id + BIND_POSES_SOURCE_ID_SUFFIX;
472
473         int totjoint = 0;
474         for (bDeformGroup *def = (bDeformGroup *)defbase->first; def; def = def->next) {
475                 if (is_bone_defgroup(ob_arm, def))
476                         totjoint++;
477         }
478
479         COLLADASW::FloatSourceF source(mSW);
480         source.setId(source_id);
481         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
482         source.setAccessorCount(totjoint); //BLI_countlist(defbase));
483         source.setAccessorStride(16);
484         
485         source.setParameterTypeName(&COLLADASW::CSWC::CSW_VALUE_TYPE_FLOAT4x4);
486         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
487         param.push_back("TRANSFORM");
488
489         source.prepareToAppendValues();
490
491         bPose *pose = ob_arm->pose;
492         bArmature *arm = (bArmature *)ob_arm->data;
493
494         int flag = arm->flag;
495
496         // put armature in rest position
497         if (!(arm->flag & ARM_RESTPOS)) {
498                 arm->flag |= ARM_RESTPOS;
499                 BKE_pose_where_is(scene, ob_arm);
500         }
501
502         for (bDeformGroup *def = (bDeformGroup *)defbase->first; def; def = def->next) {
503                 if (is_bone_defgroup(ob_arm, def)) {
504                         bPoseChannel *pchan = BKE_pose_channel_find_name(pose, def->name);
505
506                         float mat[4][4];
507                         float world[4][4];
508                         float inv_bind_mat[4][4];
509
510                         // SECOND_LIFE_COMPATIBILITY
511                         if (export_settings->second_life) {
512                                 // Only translations, no rotation vs armature
513                                 float temp[4][4];
514                                 unit_m4(temp);
515                                 copy_v3_v3(temp[3], pchan->bone->arm_mat[3]);
516                                 mult_m4_m4m4(world, ob_arm->obmat, temp);
517                         }
518                         else {
519                                 // make world-space matrix, arm_mat is armature-space
520                                 mult_m4_m4m4(world, ob_arm->obmat, pchan->bone->arm_mat);
521                         }
522
523                         invert_m4_m4(mat, world);
524                         converter.mat4_to_dae(inv_bind_mat, mat);
525
526                         source.appendValues(inv_bind_mat);
527                 }
528         }
529
530         // back from rest positon
531         if (!(flag & ARM_RESTPOS)) {
532                 arm->flag = flag;
533                 BKE_pose_where_is(scene, ob_arm);
534         }
535
536         source.finish();
537
538         return source_id;
539 }
540
541 Bone *ControllerExporter::get_bone_from_defgroup(Object *ob_arm, bDeformGroup *def)
542 {
543         bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, def->name);
544         return pchan ? pchan->bone : NULL;
545 }
546
547 bool ControllerExporter::is_bone_defgroup(Object *ob_arm, bDeformGroup *def)
548 {
549         return get_bone_from_defgroup(ob_arm, def) != NULL;
550 }
551
552 std::string ControllerExporter::add_weights_source(Mesh *me, const std::string& controller_id, const std::list<float>& weights)
553 {
554         std::string source_id = controller_id + WEIGHTS_SOURCE_ID_SUFFIX;
555
556         COLLADASW::FloatSourceF source(mSW);
557         source.setId(source_id);
558         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
559         source.setAccessorCount(weights.size());
560         source.setAccessorStride(1);
561         
562         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
563         param.push_back("WEIGHT");
564
565         source.prepareToAppendValues();
566
567         for (std::list<float>::const_iterator i = weights.begin(); i != weights.end(); ++i) {
568                 source.appendValues(*i);
569         }
570
571         source.finish();
572
573         return source_id;
574 }
575
576 void ControllerExporter::add_vertex_weights_element(const std::string& weights_source_id, const std::string& joints_source_id,
577                                                   const std::list<int>& vcounts,
578                                                   const std::list<int>& joints)
579 {
580         COLLADASW::VertexWeightsElement weightselem(mSW);
581         COLLADASW::InputList &input = weightselem.getInputList();
582
583         int offset = 0;
584         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::JOINT, // constant declared in COLLADASWInputList.h
585                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id), offset++));
586         input.push_back(COLLADASW::Input(COLLADASW::InputSemantic::WEIGHT,
587                                          COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, weights_source_id), offset++));
588
589         weightselem.setCount(vcounts.size());
590
591         // write number of deformers per vertex
592         COLLADASW::PrimitivesBase::VCountList vcountlist;
593
594         vcountlist.resize(vcounts.size());
595         std::copy(vcounts.begin(), vcounts.end(), vcountlist.begin());
596
597         weightselem.prepareToAppendVCountValues();
598         weightselem.appendVertexCount(vcountlist);
599
600         weightselem.CloseVCountAndOpenVElement();
601
602         // write deformer index - weight index pairs
603         int weight_index = 0;
604         for (std::list<int>::const_iterator i = joints.begin(); i != joints.end(); ++i) {
605                 weightselem.appendValues(*i, weight_index++);
606         }
607
608         weightselem.finish();
609 }