c7ad2ff39754404e8e37189989b7422ceb014155
[blender.git] / source / blender / collada / GeometryExporter.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
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/collada/GeometryExporter.cpp
25  *  \ingroup collada
26  */
27
28
29 #include <sstream>
30
31 #include "COLLADASWPrimitves.h"
32 #include "COLLADASWSource.h"
33 #include "COLLADASWVertices.h"
34 #include "COLLADABUUtils.h"
35
36 #include "GeometryExporter.h"
37
38 #include "DNA_meshdata_types.h"
39
40 extern "C" {
41         #include "BKE_DerivedMesh.h"
42         #include "BKE_main.h"
43         #include "BKE_global.h"
44         #include "BKE_library.h"
45         #include "BKE_customdata.h"
46         #include "BKE_material.h"
47         #include "BKE_mesh.h"
48 }
49
50 #include "collada_internal.h"
51 #include "collada_utils.h"
52
53 // TODO: optimize UV sets by making indexed list with duplicates removed
54 GeometryExporter::GeometryExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings) : COLLADASW::LibraryGeometries(sw), export_settings(export_settings) {
55 }
56
57
58 void GeometryExporter::exportGeom(Scene *sce)
59 {
60         openLibrary();
61
62         mScene = sce;
63         GeometryFunctor gf;
64         gf.forEachMeshObjectInExportSet<GeometryExporter>(sce, *this, this->export_settings->export_set);
65
66         closeLibrary();
67 }
68
69 void GeometryExporter::operator()(Object *ob)
70 {
71         // XXX don't use DerivedMesh, Mesh instead?
72
73 #if 0           
74         DerivedMesh *dm = mesh_get_derived_final(mScene, ob, CD_MASK_BAREMESH);
75 #endif
76
77         bool use_instantiation = this->export_settings->use_object_instantiation;
78         Mesh *me;
79         if (this->export_settings->apply_modifiers) {
80                 me = bc_to_mesh_apply_modifiers(mScene, ob, this->export_settings->export_mesh_type);
81         } 
82         else {
83                 me = (Mesh *)ob->data;
84         }
85         BKE_mesh_tessface_ensure(me);
86
87         std::string geom_id = get_geometry_id(ob, use_instantiation);
88         std::vector<Normal> nor;
89         std::vector<Face> norind;
90
91         // Skip if linked geometry was already exported from another reference
92         if (use_instantiation && 
93             exportedGeometry.find(geom_id) != exportedGeometry.end())
94         {
95                 return;
96         }
97
98         std::string geom_name = (use_instantiation) ? id_name(ob->data) : id_name(ob);
99
100         exportedGeometry.insert(geom_id);
101
102         bool has_color = (bool)CustomData_has_layer(&me->fdata, CD_MCOL);
103
104         create_normals(nor, norind, me);
105
106         // openMesh(geoId, geoName, meshId)
107         openMesh(geom_id, geom_name);
108         
109         // writes <source> for vertex coords
110         createVertsSource(geom_id, me);
111         
112         // writes <source> for normal coords
113         createNormalsSource(geom_id, me, nor);
114
115         bool has_uvs = (bool)CustomData_has_layer(&me->fdata, CD_MTFACE);
116         
117         // writes <source> for uv coords if mesh has uv coords
118         if (has_uvs)
119                 createTexcoordsSource(geom_id, me);
120
121         if (has_color)
122                 createVertexColorSource(geom_id, me);
123
124         // <vertices>
125
126         COLLADASW::Vertices verts(mSW);
127         verts.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX));
128         COLLADASW::InputList &input_list = verts.getInputList();
129         COLLADASW::Input input(COLLADASW::InputSemantic::POSITION, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::POSITION));
130         input_list.push_back(input);
131         verts.add();
132
133         createLooseEdgeList(ob, me, geom_id, norind);
134
135         // XXX slow             
136         if (ob->totcol) {
137                 for (int a = 0; a < ob->totcol; a++) {
138                         createPolylist(a, has_uvs, has_color, ob, me, geom_id, norind);
139                 }
140         }
141         else {
142                 createPolylist(0, has_uvs, has_color, ob, me, geom_id, norind);
143         }
144         
145         closeMesh();
146         
147         if (me->flag & ME_TWOSIDED) {
148                 mSW->appendTextBlock("<extra><technique profile=\"MAYA\"><double_sided>1</double_sided></technique></extra>");
149         }
150
151         closeGeometry();
152
153         if (this->export_settings->apply_modifiers)
154         {
155                 BKE_libblock_free_us(&(G.main->mesh), me);
156         }
157
158
159 #if 0
160         dm->release(dm);
161 #endif
162 }
163
164
165 void GeometryExporter::createLooseEdgeList(Object *ob,
166                                            Mesh   *me,
167                                            std::string& geom_id,
168                                            std::vector<Face>& norind)
169 {
170
171         MEdge *medges = me->medge;
172         int totedges  = me->totedge;
173         int edges_in_linelist = 0;
174         std::vector<unsigned int> edge_list;
175         int index;
176
177         // Find all loose edges in Mesh 
178         // and save vertex indices in edge_list
179         for (index = 0; index < totedges; index++) 
180         {
181                 MEdge *edge = &medges[index];
182
183                 if (edge->flag & ME_LOOSEEDGE)
184                 {
185                         edges_in_linelist += 1;
186                         edge_list.push_back(edge->v1);
187                         edge_list.push_back(edge->v2);
188                 }
189         }
190
191         if (edges_in_linelist > 0)
192         {
193                 // Create the list of loose edges
194                 COLLADASW::Lines lines(mSW);
195
196                 lines.setCount(edges_in_linelist);
197
198
199                 COLLADASW::InputList &til = lines.getInputList();
200                         
201                 // creates <input> in <lines> for vertices 
202                 COLLADASW::Input input1(COLLADASW::InputSemantic::VERTEX, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX), 0);
203                 til.push_back(input1);
204
205                 lines.prepareToAppendValues();
206
207                 for (index = 0; index < edges_in_linelist; index++) 
208                 {
209                         lines.appendValues(edge_list[2 * index + 1]);
210                         lines.appendValues(edge_list[2 * index]);
211                 }
212                 lines.finish();
213         }
214
215 }
216
217 // powerful because it handles both cases when there is material and when there's not
218 void GeometryExporter::createPolylist(short material_index,
219                                       bool has_uvs,
220                                       bool has_color,
221                                       Object *ob,
222                                       Mesh *me,
223                                       std::string& geom_id,
224                                       std::vector<Face>& norind)
225 {
226         MFace *mfaces = me->mface;
227         int totfaces = me->totface;
228
229         // <vcount>
230         int i;
231         int faces_in_polylist = 0;
232         std::vector<unsigned long> vcount_list;
233
234         // count faces with this material
235         for (i = 0; i < totfaces; i++) {
236                 MFace *f = &mfaces[i];
237                 
238                 if (f->mat_nr == material_index) {
239                         faces_in_polylist++;
240                         if (f->v4 == 0) {
241                                 vcount_list.push_back(3);
242                         }
243                         else {
244                                 vcount_list.push_back(4);
245                         }
246                 }
247         }
248
249         // no faces using this material
250         if (faces_in_polylist == 0) {
251                 fprintf(stderr, "%s: no faces use material %d\n", id_name(ob).c_str(), material_index);
252                 return;
253         }
254                 
255         Material *ma = ob->totcol ? give_current_material(ob, material_index + 1) : NULL;
256         COLLADASW::Polylist polylist(mSW);
257                 
258         // sets count attribute in <polylist>
259         polylist.setCount(faces_in_polylist);
260                 
261         // sets material name
262         if (ma) {
263                 std::string material_id = get_material_id(ma);
264                 std::ostringstream ostr;
265                 ostr << translate_id(material_id);
266                 polylist.setMaterial(ostr.str());
267         }
268                         
269         COLLADASW::InputList &til = polylist.getInputList();
270                 
271         // creates <input> in <polylist> for vertices 
272         COLLADASW::Input input1(COLLADASW::InputSemantic::VERTEX, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX), 0);
273                 
274         // creates <input> in <polylist> for normals
275         COLLADASW::Input input2(COLLADASW::InputSemantic::NORMAL, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL), 1);
276                 
277         til.push_back(input1);
278         til.push_back(input2);
279                 
280         // if mesh has uv coords writes <input> for TEXCOORD
281         int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
282         int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE)-1;
283         for (i = 0; i < num_layers; i++) {
284                 if (!this->export_settings->active_uv_only || i == active_uv_index) {
285
286                         // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, i);
287                         COLLADASW::Input input3(COLLADASW::InputSemantic::TEXCOORD,
288                                                                         makeUrl(makeTexcoordSourceId(geom_id, i)),
289                                                                         2, // offset always 2, this is only until we have optimized UV sets
290                                                                         i  // set number equals UV map index
291                                                                         );
292                         til.push_back(input3);
293                 }
294         }
295
296         if (has_color) {
297                 COLLADASW::Input input4(COLLADASW::InputSemantic::COLOR, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::COLOR), has_uvs ? 3 : 2);
298                 til.push_back(input4);
299         }
300                 
301         // sets <vcount>
302         polylist.setVCountList(vcount_list);
303                 
304         // performs the actual writing
305         polylist.prepareToAppendValues();
306         
307
308                 
309         // <p>
310         int texindex = 0;
311         for (i = 0; i < totfaces; i++) {
312                 MFace *f = &mfaces[i];
313
314                 if (f->mat_nr == material_index) {
315
316                         unsigned int *v = &f->v1;
317                         unsigned int *n = &norind[i].v1;
318                         for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) {
319                                 polylist.appendValues(v[j]);
320                                 polylist.appendValues(n[j]);
321
322                                 if (has_uvs)
323                                         polylist.appendValues(texindex + j);
324
325                                 if (has_color)
326                                         polylist.appendValues(texindex + j);
327                         }
328                 }
329
330                 texindex += 3;
331                 if (f->v4 != 0)
332                         texindex++;
333         }
334                 
335         polylist.finish();
336 }
337
338 // creates <source> for positions
339 void GeometryExporter::createVertsSource(std::string geom_id, Mesh *me)
340 {
341 #if 0
342         int totverts = dm->getNumVerts(dm);
343         MVert *verts = dm->getVertArray(dm);
344 #endif
345         int totverts = me->totvert;
346         MVert *verts = me->mvert;
347         
348         COLLADASW::FloatSourceF source(mSW);
349         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION));
350         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION) +
351                           ARRAY_ID_SUFFIX);
352         source.setAccessorCount(totverts);
353         source.setAccessorStride(3);
354         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
355         param.push_back("X");
356         param.push_back("Y");
357         param.push_back("Z");
358         /*main function, it creates <source id = "">, <float_array id = ""
359            count = ""> */
360         source.prepareToAppendValues();
361         //appends data to <float_array>
362         int i = 0;
363         for (i = 0; i < totverts; i++) {
364                 source.appendValues(verts[i].co[0], verts[i].co[1], verts[i].co[2]);                    
365         }
366         
367         source.finish();
368
369 }
370
371 void GeometryExporter::createVertexColorSource(std::string geom_id, Mesh *me)
372 {
373         if (!CustomData_has_layer(&me->fdata, CD_MCOL))
374                 return;
375
376         MFace *f;
377         int totcolor = 0, i, j;
378
379         for (i = 0, f = me->mface; i < me->totface; i++, f++)
380                 totcolor += f->v4 ? 4 : 3;
381
382         COLLADASW::FloatSourceF source(mSW);
383         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR));
384         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR) + ARRAY_ID_SUFFIX);
385         source.setAccessorCount(totcolor);
386         source.setAccessorStride(3);
387
388         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
389         param.push_back("R");
390         param.push_back("G");
391         param.push_back("B");
392
393         source.prepareToAppendValues();
394
395         int index = CustomData_get_active_layer_index(&me->fdata, CD_MCOL);
396
397         MCol *mcol = (MCol *)me->fdata.layers[index].data;
398         MCol *c = mcol;
399
400         for (i = 0, f = me->mface; i < me->totface; i++, c += 4, f++)
401                 for (j = 0; j < (f->v4 ? 4 : 3); j++)
402                         source.appendValues(c[j].b / 255.0f, c[j].g / 255.0f, c[j].r / 255.0f);
403         
404         source.finish();
405 }
406
407 std::string GeometryExporter::makeTexcoordSourceId(std::string& geom_id, int layer_index)
408 {
409         char suffix[20];
410         sprintf(suffix, "-%d", layer_index);
411         return getIdBySemantics(geom_id, COLLADASW::InputSemantic::TEXCOORD) + suffix;
412 }
413
414 //creates <source> for texcoords
415 void GeometryExporter::createTexcoordsSource(std::string geom_id, Mesh *me)
416 {
417 #if 0
418         int totfaces = dm->getNumTessFaces(dm);
419         MFace *mfaces = dm->getTessFaceArray(dm);
420 #endif
421         int totfaces = me->totface;
422         MFace *mfaces = me->mface;
423
424         int totuv = 0;
425         int i;
426
427         // count totuv
428         for (i = 0; i < totfaces; i++) {
429                 MFace *f = &mfaces[i];
430                 if (f->v4 == 0) {
431                         totuv += 3;
432                 }
433                 else {
434                         totuv += 4;
435                 }
436         }
437
438         int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
439
440         // write <source> for each layer
441         // each <source> will get id like meshName + "map-channel-1"
442         int map_index = 0;
443         int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE)-1;
444         for (int a = 0; a < num_layers; a++) {
445
446                 if (!this->export_settings->active_uv_only || a == active_uv_index) {
447                         MTFace *tface = (MTFace *)CustomData_get_layer_n(&me->fdata, CD_MTFACE, a);
448                         // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, a);
449                         
450                         COLLADASW::FloatSourceF source(mSW);
451                         std::string layer_id = makeTexcoordSourceId(geom_id, map_index++);
452                         source.setId(layer_id);
453                         source.setArrayId(layer_id + ARRAY_ID_SUFFIX);
454                         
455                         source.setAccessorCount(totuv);
456                         source.setAccessorStride(2);
457                         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
458                         param.push_back("S");
459                         param.push_back("T");
460                         
461                         source.prepareToAppendValues();
462                         
463                         for (i = 0; i < totfaces; i++) {
464                                 MFace *f = &mfaces[i];
465                                 
466                                 for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) {
467                                         source.appendValues(tface[i].uv[j][0],
468                                                                                 tface[i].uv[j][1]);
469                                 }
470                         }
471                         
472                         source.finish();
473                 }
474         }
475 }
476
477
478 //creates <source> for normals
479 void GeometryExporter::createNormalsSource(std::string geom_id, Mesh *me, std::vector<Normal>& nor)
480 {
481 #if 0
482         int totverts = dm->getNumVerts(dm);
483         MVert *verts = dm->getVertArray(dm);
484 #endif
485
486         COLLADASW::FloatSourceF source(mSW);
487         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL));
488         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL) +
489                           ARRAY_ID_SUFFIX);
490         source.setAccessorCount((unsigned long)nor.size());
491         source.setAccessorStride(3);
492         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
493         param.push_back("X");
494         param.push_back("Y");
495         param.push_back("Z");
496         
497         source.prepareToAppendValues();
498
499         std::vector<Normal>::iterator it;
500         for (it = nor.begin(); it != nor.end(); it++) {
501                 Normal& n = *it;
502                 source.appendValues(n.x, n.y, n.z);
503         }
504
505         source.finish();
506 }
507
508 void GeometryExporter::create_normals(std::vector<Normal> &nor, std::vector<Face> &ind, Mesh *me)
509 {
510         int i, j, v;
511         MVert *vert = me->mvert;
512         std::map<unsigned int, unsigned int> nshar;
513
514         for (i = 0; i < me->totface; i++) {
515                 MFace *fa = &me->mface[i];
516                 Face f;
517                 unsigned int *nn = &f.v1;
518                 unsigned int *vv = &fa->v1;
519
520                 memset(&f, 0, sizeof(f));
521                 v = fa->v4 == 0 ? 3 : 4;
522
523                 if (!(fa->flag & ME_SMOOTH)) {
524                         Normal n;
525                         if (v == 4)
526                                 normal_quad_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co, vert[fa->v4].co);
527                         else
528                                 normal_tri_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co);
529                         nor.push_back(n);
530                 }
531
532                 for (j = 0; j < v; j++) {
533                         if (fa->flag & ME_SMOOTH) {
534                                 if (nshar.find(*vv) != nshar.end())
535                                         *nn = nshar[*vv];
536                                 else {
537                                         Normal n = {
538                                                 (float)vert[*vv].no[0] / 32767.0f,
539                                                 (float)vert[*vv].no[1] / 32767.0f,
540                                                 (float)vert[*vv].no[2] / 32767.0f
541                                         };
542                                         nor.push_back(n);
543                                         *nn = (unsigned int)nor.size() - 1;
544                                         nshar[*vv] = *nn;
545                                 }
546                                 vv++;
547                         }
548                         else {
549                                 *nn = (unsigned int)nor.size() - 1;
550                         }
551                         nn++;
552                 }
553
554                 ind.push_back(f);
555         }
556 }
557
558 std::string GeometryExporter::getIdBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix)
559 {
560         return geom_id + getSuffixBySemantic(type) + other_suffix;
561 }
562
563
564 COLLADASW::URI GeometryExporter::getUrlBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix)
565 {
566         
567         std::string id(getIdBySemantics(geom_id, type, other_suffix));
568         return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id);
569         
570 }
571
572 COLLADASW::URI GeometryExporter::makeUrl(std::string id)
573 {
574         return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id);
575 }
576
577 #if 0
578 int GeometryExporter::getTriCount(MFace *faces, int totface)
579 {
580         int i;
581         int tris = 0;
582         for (i = 0; i < totface; i++) {
583                 // if quad
584                 if (faces[i].v4 != 0)
585                         tris += 2;
586                 else
587                         tris++;
588         }
589
590         return tris;
591 }
592 #endif