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