29ffcf53ee96467f8282f9a83dcd655f1e455b34
[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
283         for (i = 0; i < num_layers; i++) {
284                 // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, i);
285                 COLLADASW::Input input3(COLLADASW::InputSemantic::TEXCOORD,
286                                         makeUrl(makeTexcoordSourceId(geom_id, i)),
287                                         2, // offset always 2, this is only until we have optimized UV sets
288                                         i  // set number equals UV map index
289                                         );
290                 til.push_back(input3);
291         }
292
293         if (has_color) {
294                 COLLADASW::Input input4(COLLADASW::InputSemantic::COLOR, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::COLOR), has_uvs ? 3 : 2);
295                 til.push_back(input4);
296         }
297                 
298         // sets <vcount>
299         polylist.setVCountList(vcount_list);
300                 
301         // performs the actual writing
302         polylist.prepareToAppendValues();
303         
304
305                 
306         // <p>
307         int texindex = 0;
308         for (i = 0; i < totfaces; i++) {
309                 MFace *f = &mfaces[i];
310
311                 if (f->mat_nr == material_index) {
312
313                         unsigned int *v = &f->v1;
314                         unsigned int *n = &norind[i].v1;
315                         for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) {
316                                 polylist.appendValues(v[j]);
317                                 polylist.appendValues(n[j]);
318
319                                 if (has_uvs)
320                                         polylist.appendValues(texindex + j);
321
322                                 if (has_color)
323                                         polylist.appendValues(texindex + j);
324                         }
325                 }
326
327                 texindex += 3;
328                 if (f->v4 != 0)
329                         texindex++;
330         }
331                 
332         polylist.finish();
333 }
334
335 // creates <source> for positions
336 void GeometryExporter::createVertsSource(std::string geom_id, Mesh *me)
337 {
338 #if 0
339         int totverts = dm->getNumVerts(dm);
340         MVert *verts = dm->getVertArray(dm);
341 #endif
342         int totverts = me->totvert;
343         MVert *verts = me->mvert;
344         
345         COLLADASW::FloatSourceF source(mSW);
346         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION));
347         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::POSITION) +
348                           ARRAY_ID_SUFFIX);
349         source.setAccessorCount(totverts);
350         source.setAccessorStride(3);
351         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
352         param.push_back("X");
353         param.push_back("Y");
354         param.push_back("Z");
355         /*main function, it creates <source id = "">, <float_array id = ""
356            count = ""> */
357         source.prepareToAppendValues();
358         //appends data to <float_array>
359         int i = 0;
360         for (i = 0; i < totverts; i++) {
361                 source.appendValues(verts[i].co[0], verts[i].co[1], verts[i].co[2]);                    
362         }
363         
364         source.finish();
365
366 }
367
368 void GeometryExporter::createVertexColorSource(std::string geom_id, Mesh *me)
369 {
370         if (!CustomData_has_layer(&me->fdata, CD_MCOL))
371                 return;
372
373         MFace *f;
374         int totcolor = 0, i, j;
375
376         for (i = 0, f = me->mface; i < me->totface; i++, f++)
377                 totcolor += f->v4 ? 4 : 3;
378
379         COLLADASW::FloatSourceF source(mSW);
380         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR));
381         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::COLOR) + ARRAY_ID_SUFFIX);
382         source.setAccessorCount(totcolor);
383         source.setAccessorStride(3);
384
385         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
386         param.push_back("R");
387         param.push_back("G");
388         param.push_back("B");
389
390         source.prepareToAppendValues();
391
392         int index = CustomData_get_active_layer_index(&me->fdata, CD_MCOL);
393
394         MCol *mcol = (MCol *)me->fdata.layers[index].data;
395         MCol *c = mcol;
396
397         for (i = 0, f = me->mface; i < me->totface; i++, c += 4, f++)
398                 for (j = 0; j < (f->v4 ? 4 : 3); j++)
399                         source.appendValues(c[j].b / 255.0f, c[j].g / 255.0f, c[j].r / 255.0f);
400         
401         source.finish();
402 }
403
404 std::string GeometryExporter::makeTexcoordSourceId(std::string& geom_id, int layer_index)
405 {
406         char suffix[20];
407         sprintf(suffix, "-%d", layer_index);
408         return getIdBySemantics(geom_id, COLLADASW::InputSemantic::TEXCOORD) + suffix;
409 }
410
411 //creates <source> for texcoords
412 void GeometryExporter::createTexcoordsSource(std::string geom_id, Mesh *me)
413 {
414 #if 0
415         int totfaces = dm->getNumTessFaces(dm);
416         MFace *mfaces = dm->getTessFaceArray(dm);
417 #endif
418         int totfaces = me->totface;
419         MFace *mfaces = me->mface;
420
421         int totuv = 0;
422         int i;
423
424         // count totuv
425         for (i = 0; i < totfaces; i++) {
426                 MFace *f = &mfaces[i];
427                 if (f->v4 == 0) {
428                         totuv += 3;
429                 }
430                 else {
431                         totuv += 4;
432                 }
433         }
434
435         int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
436
437         // write <source> for each layer
438         // each <source> will get id like meshName + "map-channel-1"
439         int map_index = 0;
440         int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE)-1;
441         for (int a = 0; a < num_layers; a++) {
442
443                 if (!this->export_settings->active_uv_only || a == active_uv_index) {
444                         MTFace *tface = (MTFace *)CustomData_get_layer_n(&me->fdata, CD_MTFACE, a);
445                         // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, a);
446                         
447                         COLLADASW::FloatSourceF source(mSW);
448                         std::string layer_id = makeTexcoordSourceId(geom_id, map_index++);
449                         source.setId(layer_id);
450                         source.setArrayId(layer_id + ARRAY_ID_SUFFIX);
451                         
452                         source.setAccessorCount(totuv);
453                         source.setAccessorStride(2);
454                         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
455                         param.push_back("S");
456                         param.push_back("T");
457                         
458                         source.prepareToAppendValues();
459                         
460                         for (i = 0; i < totfaces; i++) {
461                                 MFace *f = &mfaces[i];
462                                 
463                                 for (int j = 0; j < (f->v4 == 0 ? 3 : 4); j++) {
464                                         source.appendValues(tface[i].uv[j][0],
465                                                                                 tface[i].uv[j][1]);
466                                 }
467                         }
468                         
469                         source.finish();
470                 }
471         }
472 }
473
474
475 //creates <source> for normals
476 void GeometryExporter::createNormalsSource(std::string geom_id, Mesh *me, std::vector<Normal>& nor)
477 {
478 #if 0
479         int totverts = dm->getNumVerts(dm);
480         MVert *verts = dm->getVertArray(dm);
481 #endif
482
483         COLLADASW::FloatSourceF source(mSW);
484         source.setId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL));
485         source.setArrayId(getIdBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL) +
486                           ARRAY_ID_SUFFIX);
487         source.setAccessorCount((unsigned long)nor.size());
488         source.setAccessorStride(3);
489         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
490         param.push_back("X");
491         param.push_back("Y");
492         param.push_back("Z");
493         
494         source.prepareToAppendValues();
495
496         std::vector<Normal>::iterator it;
497         for (it = nor.begin(); it != nor.end(); it++) {
498                 Normal& n = *it;
499                 source.appendValues(n.x, n.y, n.z);
500         }
501
502         source.finish();
503 }
504
505 void GeometryExporter::create_normals(std::vector<Normal> &nor, std::vector<Face> &ind, Mesh *me)
506 {
507         int i, j, v;
508         MVert *vert = me->mvert;
509         std::map<unsigned int, unsigned int> nshar;
510
511         for (i = 0; i < me->totface; i++) {
512                 MFace *fa = &me->mface[i];
513                 Face f;
514                 unsigned int *nn = &f.v1;
515                 unsigned int *vv = &fa->v1;
516
517                 memset(&f, 0, sizeof(f));
518                 v = fa->v4 == 0 ? 3 : 4;
519
520                 if (!(fa->flag & ME_SMOOTH)) {
521                         Normal n;
522                         if (v == 4)
523                                 normal_quad_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co, vert[fa->v4].co);
524                         else
525                                 normal_tri_v3(&n.x, vert[fa->v1].co, vert[fa->v2].co, vert[fa->v3].co);
526                         nor.push_back(n);
527                 }
528
529                 for (j = 0; j < v; j++) {
530                         if (fa->flag & ME_SMOOTH) {
531                                 if (nshar.find(*vv) != nshar.end())
532                                         *nn = nshar[*vv];
533                                 else {
534                                         Normal n = {
535                                                 (float)vert[*vv].no[0] / 32767.0f,
536                                                 (float)vert[*vv].no[1] / 32767.0f,
537                                                 (float)vert[*vv].no[2] / 32767.0f
538                                         };
539                                         nor.push_back(n);
540                                         *nn = (unsigned int)nor.size() - 1;
541                                         nshar[*vv] = *nn;
542                                 }
543                                 vv++;
544                         }
545                         else {
546                                 *nn = (unsigned int)nor.size() - 1;
547                         }
548                         nn++;
549                 }
550
551                 ind.push_back(f);
552         }
553 }
554
555 std::string GeometryExporter::getIdBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix)
556 {
557         return geom_id + getSuffixBySemantic(type) + other_suffix;
558 }
559
560
561 COLLADASW::URI GeometryExporter::getUrlBySemantics(std::string geom_id, COLLADASW::InputSemantic::Semantics type, std::string other_suffix)
562 {
563         
564         std::string id(getIdBySemantics(geom_id, type, other_suffix));
565         return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id);
566         
567 }
568
569 COLLADASW::URI GeometryExporter::makeUrl(std::string id)
570 {
571         return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id);
572 }
573
574 #if 0
575 int GeometryExporter::getTriCount(MFace *faces, int totface)
576 {
577         int i;
578         int tris = 0;
579         for (i = 0; i < totface; i++) {
580                 // if quad
581                 if (faces[i].v4 != 0)
582                         tris += 2;
583                 else
584                         tris++;
585         }
586
587         return tris;
588 }
589 #endif