source: GTP/trunk/App/Demos/Vis/FriendlyCulling/Converter/ObjConverter2.cpp @ 3360

Revision 3360, 14.3 KB checked in by mattausch, 15 years ago (diff)
Line 
1#include "ObjConverter2.h"
2#include "SimpleTri.h"
3#include "SimpleVec.h"
4#include "gzstream.h"
5#include <iostream>
6
7
8using namespace std;
9
10
11static void LoadIndices(char *str,
12                                                const VertexArray &vertices,
13                                                const VertexArray &normals,
14                                                const TexcoordArray &texcoords,
15                                                VertexArray &faceVertices,
16                                                VertexArray &faceNormals,
17                                                TexcoordArray &faceTexcoords
18                                                )
19{
20        vector<string> triples;
21
22        char *next_token;
23
24        // extract the triples of the form v/t/n v/t/n ...
25        char *pch = strtok_s(str + 1, " ", &next_token);
26
27        while (pch)
28        {
29                string s(pch);
30                triples.push_back(s);
31               
32                pch = strtok_s(NULL, " ", &next_token);   
33        }
34
35        // throw away last symbol (\n)
36        triples.back().resize(triples.back().size() - 1);
37
38        vector<int> indices;
39        vector<int> nIndices;
40        vector<int> tIndices;
41
42        char seps[] = " ";
43        char seps2[] = "/";
44
45        for (size_t i = 0; i < triples.size(); ++ i)
46        {
47                //cout << "triple " << i << " " << triples[i] << endl;
48                size_t found;
49                found = triples[i].find_first_of(seps2);
50                size_t prevfound = 0;
51
52                // extract vertex, normal, texture indices
53                string str = triples[i].substr(prevfound, found);
54
55                int index = (int)strtol(str.c_str(), NULL, 10) - 1;
56                int tIndex = index;
57                int nIndex = index;     
58               
59                // try to extract texture and normal indices
60                prevfound = found + 1;
61                found = triples[i].find_first_of(seps2, prevfound); 
62
63                if (found != string::npos)
64                {
65                        str = triples[i].substr(prevfound, found);
66
67                        int idx = (int)strtol(str.c_str(), NULL, 10) - 1;
68                        if (idx > 0) tIndex = idx;
69                }
70               
71                if (found != string::npos)
72                {
73                        str = triples[i].substr(found + 1);
74
75                        int idx = (int)strtol(str.c_str(), NULL, 10) - 1;
76                        if (idx > 0) nIndex = idx;
77                }
78
79                // store indices
80                if (index >= 0)
81                {
82                        indices.push_back(index);
83                        nIndices.push_back(nIndex);
84                        tIndices.push_back(tIndex);
85
86                        //cout << index << " " << tIndex << " " << nIndex << endl;
87                }
88
89                int idx[3];
90                // new triangle found
91                if (indices.size() > 2)
92                {
93                        // change orientation of faces?
94#if 1
95                        idx[0] = 0;
96                        idx[1] = (int)indices.size() - 2;
97                        idx[2] = (int)indices.size() - 1;
98#else
99                        idx[2] = 0;
100                        idx[1] = (int)indices.size() - 2;
101                        idx[0] = (int)indices.size() - 1;
102#endif
103
104                        for (int j = 0; j < 3; ++ j)
105                                faceVertices.push_back(vertices[indices[idx[j]]]);
106
107
108                        if (!normals.empty())
109                        {
110                                for (int j = 0; j < 3; ++ j)
111                                        faceNormals.push_back(Normalize(normals[nIndices[idx[j]]]));
112                        }
113                        else
114                        {
115                                // no face normals? => create normals
116                                const SimpleTri tri(vertices[indices[idx[0]]],
117                                                        vertices[indices[idx[1]]],
118                                                                        vertices[indices[idx[2]]]);
119
120                                const SimpleVec n = tri.GetNormal();
121
122                                faceNormals.push_back(n);
123                                faceNormals.push_back(n);
124                                faceNormals.push_back(n);
125                        }
126
127                        if (!texcoords.empty())
128                        {
129                                for (int j = 0; j < 3; ++ j)
130                                {
131                                        //if (tIndices[idx[j]] >= (int)texcoords.size())
132                                                //cerr << "error: texcoord indices exceed array size " << texcoords.size() << " " << tIndices[idx[j]] << endl;
133                                        const int tidx = min((int)texcoords.size() - 1, tIndices[idx[j]]);
134
135                                        faceTexcoords.push_back(texcoords[tidx]);
136                                }
137                        }
138                }
139        }
140}
141
142
143ObjConverter2::ObjConverter2()
144{}
145
146
147ObjConverter2::~ObjConverter2()
148{
149        for (size_t i = 0; i < mGeometry.size(); ++ i)
150                delete mGeometry[i];
151       
152        mGeometry.clear();
153}
154
155
156void ObjConverter2::LoadShape(const VertexArray &faceVertices,
157                                                          const VertexArray &faceNormals,
158                                                          const vector<Texcoord> &faceTexcoords,
159                                                          Material *mat)
160{
161        int numElements = (int)faceVertices.size();
162        Geometry *geom = new Geometry();
163
164        // convert the triangles to geometry
165        geom->mVertices = new SimpleVec[numElements];
166        geom->mNormals = new SimpleVec[numElements];
167        geom->mTexcoords = new Texcoord[numElements];
168
169        geom->mVertexCount = numElements;
170        geom->mTexcoordCount = (int)faceTexcoords.size();
171
172        geom->mMaterial = mat;
173
174        cout << "creating new geometry with " << numElements << " vertices" << endl;
175
176        for (int i = 0; i < numElements; ++ i)
177        {
178#if 1
179                // convert to our camera system: change y and z
180                geom->mVertices[i].x = faceVertices[i].x;
181                geom->mVertices[i].y = -faceVertices[i].z;
182                geom->mVertices[i].z = faceVertices[i].y;
183       
184                geom->mNormals[i].x = faceNormals[i].x;
185                geom->mNormals[i].y = -faceNormals[i].z;
186                geom->mNormals[i].z = faceNormals[i].y;
187
188#else
189
190                geom->mVertices[i].x = faceVertices[i].x;
191                geom->mVertices[i].y = faceVertices[i].y;
192                geom->mVertices[i].z = faceVertices[i].z;
193       
194                geom->mNormals[i].x = faceNormals[i].x;
195                geom->mNormals[i].y = faceNormals[i].y;
196                geom->mNormals[i].z = faceNormals[i].z;
197
198#endif
199
200                if (i < geom->mTexcoordCount)
201                {
202                        geom->mTexcoords[i].first = faceTexcoords[i].first;
203                        geom->mTexcoords[i].second = faceTexcoords[i].second;
204                }
205        }
206
207        mGeometry.push_back(geom);
208}
209
210
211bool ObjConverter2::Convert(const string &filename,
212                                                        const std::string &outputFilename)
213{
214        mNumShapes = 0;
215       
216        for (size_t i = 0; i < mGeometry.size(); ++ i)
217                delete mGeometry[i];
218       
219        mGeometry.clear();
220
221        if (!ReadFile(filename))
222        {
223                cerr << "could not read file" << endl;
224                return false;
225        }
226
227        if (!WriteFile(outputFilename))
228        {
229                cerr << "could not write file" << endl;
230                return false;
231        }
232
233        return true;
234}
235
236
237bool ObjConverter2::Convert2(const vector<string> &filenames,
238                                                         const std::string &outputFilename)
239{
240        mNumShapes = 0;
241
242        vector<string>::const_iterator it, it_end = filenames.end();
243
244        ofstream outstr("mydebug.log");
245
246        for (it = filenames.begin(); it != it_end; ++ it)
247        {
248                const string filename = *it;
249
250                cout << "\n==================\n loading file " << filename << endl;
251
252                outstr << "loading file: " << filename << endl;
253                outstr << flush;
254
255                if (!ReadFile(filename))
256                {
257                        cerr << "could not read file ... skipping " << filename << endl;
258                        //return false;
259                }
260        }
261
262        cout << "\n*******************\nwriting file " << outputFilename << endl;
263
264        if (!WriteFile(outputFilename))
265        {
266                cerr << "could not write file" << endl;
267                return false;
268        }
269
270        return true;
271}
272
273
274
275bool ObjConverter2::ReadFile(const string &filename)
276{
277        FILE *file;
278
279        if ((file = fopen(filename.c_str(), "r")) == NULL)
280        {       
281                return false;
282        }
283       
284        Material *currentMat = NULL;
285        VertexArray faceVertices;
286        VertexArray faceNormals;
287        vector<Texcoord> faceTexcoords;
288
289        VertexArray vertices;
290        VertexArray normals;
291        vector<Texcoord> texcoords;
292
293        vector<int> indices;
294
295        int line = 0;
296        const int len = 10000;
297        char str[len];
298
299        while (fgets(str, len, file) != NULL)
300        {
301                //cout << "line: " << line << endl;
302                switch (str[0])
303                {
304                case 'v': // vertex or normal
305                        {
306                                // still an object to load
307                                if (!faceVertices.empty())
308                                {
309                                        ++ mNumShapes;
310
311                                        //if (!currentMat){ cerr << "no mat!!" << endl; std::cin.get(); }
312                                        LoadShape(faceVertices, faceNormals, faceTexcoords, currentMat);
313
314                                        faceVertices.clear();
315                                        faceNormals.clear();
316                                        faceTexcoords.clear();
317
318                                        currentMat = NULL;
319                                }
320
321                                float x, y, z;
322
323                                switch (str[1])
324                                {
325                                case 'n' :
326                                        sscanf(str + 2, "%f %f %f", &x, &y, &z);
327                                        normals.push_back(SimpleVec(x, y, z));
328                                        break;
329                                case 't':
330                                        sscanf(str + 2, "%f %f", &x, &y);
331                                        texcoords.push_back(pair<float, float>(x, y));
332                                        break;
333                                default:
334                                        sscanf(str + 1, "%f %f %f", &x, &y, &z);
335                                        //const float scale = 5e-3f;
336                                        const float scale = 5.0f;
337                                        vertices.push_back(SimpleVec(x * scale, y * scale, z* scale));
338                                }
339                                break;
340                        }
341                case 'f':
342                        {
343                                //////////
344                                //-- indices in the current line
345
346                                //cout << "f: " << vertices.size() << " n: " << normals.size() << " " << texcoords.size() << endl;
347
348                                LoadIndices(str,
349                                                vertices, normals, texcoords,
350                                                faceVertices, faceNormals, faceTexcoords);
351
352                                break;
353                        }   // end face
354                /*case 'g': // load a new shape
355                        {
356                                if (!faceVertices.empty())
357                                {
358                                        ++ mNumShapes;
359
360                                        LoadShape(faceVertices, faceNormals, faceTexcoords, currentMat);
361
362                                        faceVertices.clear();
363                                        faceNormals.clear();
364                                        faceTexcoords.clear();
365
366                                        currentMat = NULL;
367                                }
368                        }
369                        break;*/
370                case 'u': // usemtl => material
371                        {
372                                string matName(str + 7);
373                                // throw away linebreak character
374                                matName.resize(matName.size() - 1);
375
376                                currentMat = mMaterialTable[matName];
377                                //cout << "matname: " << matName << endl;
378                                //cout << "currentMat: " << currentMat << endl;
379                        }
380                        break;
381                case 'm': // material library
382                        {
383                                string matLibName(model_path + string(str + 7));
384                                // throw away linebreak character
385                                matLibName.resize(matLibName.size() - 1);
386                               
387                                cout << "loading mat library " << matLibName << endl;
388
389                                // load the materials
390                                if (!LoadMaterials(matLibName))
391                                {
392                                        cerr << "loading material library failed" << endl;
393                                        return false;
394                                }
395                        }
396
397                default:
398                        // throw away line
399                        break;
400                }
401
402                ++ line;
403        }
404
405        // convert the rest of the vertives
406        if (!faceVertices.empty())
407        {
408                ++ mNumShapes;
409
410                LoadShape(faceVertices, faceNormals, faceTexcoords, currentMat);
411
412                faceVertices.clear();
413                faceNormals.clear();
414                faceTexcoords.clear();
415        }
416
417        fclose(file);
418       
419        return true;
420}
421
422
423void ObjConverter2::WriteGeometry(ogzstream &str, Geometry *geom)
424{
425        int vertexCount = geom->mVertexCount;
426        str.write(reinterpret_cast<char *>(&vertexCount), sizeof(int));
427 
428        str.write(reinterpret_cast<char *>(geom->mVertices), sizeof(SimpleVec) * vertexCount);
429        str.write(reinterpret_cast<char *>(geom->mNormals), sizeof(SimpleVec) * vertexCount);
430
431        int texCoordCount = geom->mTexcoordCount;
432        str.write(reinterpret_cast<char *>(&texCoordCount), sizeof(int));
433
434        if (texCoordCount)
435                str.write(reinterpret_cast<char *>(geom->mTexcoords), sizeof(float) * texCoordCount * 2);
436}
437
438
439bool ObjConverter2::WriteFile(const string &filename)
440{
441        ogzstream ofile(filename.c_str());
442        if (!ofile.is_open()) return false;
443       
444
445        /////////
446        //-- write textures
447
448        int textureCount = (int)mTextures.size();
449
450        ofile.write(reinterpret_cast<char *>(&textureCount), sizeof(int));
451
452        TextureArray::const_iterator tit, tit_end = mTextures.end();
453       
454        for (tit = mTextures.begin(); tit != tit_end; ++ tit)
455        {
456                const string texName = (*tit);
457
458                int texnameSize = (int)texName.length() + 1;
459                ofile.write(reinterpret_cast<char *>(&texnameSize), sizeof(int));
460
461                ofile.write(texName.c_str(), sizeof(char) * texnameSize);
462
463                int boundS = 1, boundT = 1;
464
465                ofile.write(reinterpret_cast<char *>(&boundS), sizeof(int));
466                ofile.write(reinterpret_cast<char *>(&boundT), sizeof(int));
467        }
468
469
470        ///////////
471        //-- write shapes
472
473        ofile.write(reinterpret_cast<char *>(&mNumShapes), sizeof(int));
474
475        vector<Geometry *>::const_iterator it, it_end = mGeometry.end();
476
477        for (it = mGeometry.begin(); it != it_end; ++ it)
478        {
479                WriteGeometry(ofile, *it);
480
481               
482                /////////
483                //-- material
484
485                Material *mat = (*it)->mMaterial;
486
487                if (!mat) cerr << "error: no material specified!!" << endl;
488
489                ofile.write(reinterpret_cast<char *>(&mat->texture), sizeof(int));
490
491                bool alphaTestEnabled = false;
492                bool cullFaceEnabled = true;
493                //bool cullFaceEnabled = false;
494               
495                ofile.write(reinterpret_cast<char *>(&alphaTestEnabled), sizeof(bool));
496                ofile.write(reinterpret_cast<char *>(&cullFaceEnabled), sizeof(bool));
497
498                // material
499                bool hasMaterial = true;
500                ofile.write(reinterpret_cast<char *>(&hasMaterial), sizeof(bool));
501       
502                SimpleVec ambient, diffuse, spec, emm;
503
504                ambient.x = ambient.y = ambient.z = 0.2f;
505                //diffuse.x = diffuse.y = diffuse.z = 1.0f;
506                diffuse.x = mat->rgb[0]; diffuse.y =mat->rgb[1]; diffuse.z = mat->rgb[2];
507                spec.x = spec.y = spec.z = .0f;
508                emm = spec;
509
510                // only write rgb part of the material
511                ofile.write(reinterpret_cast<char *>(&ambient), sizeof(SimpleVec));
512                ofile.write(reinterpret_cast<char *>(&diffuse), sizeof(SimpleVec));
513                ofile.write(reinterpret_cast<char *>(&spec), sizeof(SimpleVec));
514                ofile.write(reinterpret_cast<char *>(&emm), sizeof(SimpleVec));
515        }
516
517
518        int entityCount = mNumShapes;
519        ofile.write(reinterpret_cast<char *>(&entityCount), sizeof(int));
520
521
522        //////////
523        //-- write scene entities
524
525        // all shapes belong to this scene entity
526        for (int i = 0; i < mNumShapes; ++ i)
527        {
528                // no transformation
529                bool hasTrafo = false;
530                ofile.write(reinterpret_cast<char *>(&hasTrafo), sizeof(bool));
531
532                // a dummy lod
533                int numLODs = 1;
534                ofile.write(reinterpret_cast<char *>(&numLODs), sizeof(int));
535
536                float dist = 0;
537                ofile.write(reinterpret_cast<char *>(&dist), sizeof(float));
538
539                int numShapes = 1;
540                ofile.write(reinterpret_cast<char *>(&numShapes), sizeof(int));
541
542                int shapeId = i;
543                ofile.write(reinterpret_cast<char *>(&shapeId), sizeof(int));
544        }
545
546        ofile.close();
547
548        return true;
549}
550
551
552bool ObjConverter2::LoadMaterials(const std::string &matFileName)
553{
554        FILE *file;
555        if ((file = fopen(matFileName.c_str(), "r")) == NULL) return false;
556       
557        int line = 0;
558        const int len = 10000;
559        char str[len];
560
561        Material *currentMat = NULL;
562
563
564        while (fgets(str, len, file) != NULL)
565        {
566                //sscanf(str + 1, "%f %f %f", &x, &y, &z);
567                vector<string> strings;
568
569                char *next_token;
570
571                // extract the triples of the form v/t/n v/t/n ...
572                char *pch = strtok_s(str, " \n", &next_token);
573
574                while (pch)
575                {
576                        string s(pch);
577                        strings.push_back(s);
578
579                        pch = strtok_s(NULL, " \n", &next_token);       
580                }
581               
582                if ((strings.size() == 2) && (strcmp(strings[0].c_str(),"newmtl") == 0))
583                {
584                        currentMat = new Material();
585                        mMaterialTable[strings[1].c_str()] = currentMat;
586                }
587
588                if ((strings.size() == 2) &&
589                        ((strcmp(strings[0].c_str(),"map_Kd") == 0) || (strcmp(strings[0].c_str(),"map_Ka") == 0)))
590                {
591                        TextureTable::const_iterator it = mTextureTable.find(strings[1]);
592
593                        int id;
594
595                        if (it == mTextureTable.end()) // parameter not found
596                        {
597                                mTextures.push_back(strings[1]);
598                                id = (int)mTextures.size();
599                                mTextureTable[strings[1]] = id;
600                        }
601                        else
602                        {
603                                id = (*it).second;
604                        }
605
606                        currentMat->texture = id;
607                }
608
609                if ((strings.size() == 4) && (strcmp(strings[0].c_str(),"Kd") == 0))
610                {
611                        currentMat->rgb[0] = (float)atof(strings[1].c_str());
612                        currentMat->rgb[1] = (float)atof(strings[2].c_str());
613                        currentMat->rgb[2] = (float)atof(strings[3].c_str());
614                }
615
616                ++ line;
617        }
618
619        fclose(file);
620
621        return true;
622}
Note: See TracBrowser for help on using the repository browser.