source: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp @ 991

Revision 991, 16.5 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include "SceneGraph.h"
2#include "Exporter.h"
3#include "UnigraphicsParser.h"
4#include "X3dParser.h"
5#include "Preprocessor.h"
6#include "ViewCell.h"
7#include "Environment.h"
8#include "ViewCellsManager.h"
9#include "ViewCellBsp.h"
10#include "VspBspTree.h"
11#include "VspKdTree.h"
12#include "RenderSimulator.h"
13#include "GlRenderer.h"
14#include "PlyParser.h"
15
16namespace GtpVisibilityPreprocessor {
17
18
19Preprocessor *preprocessor;
20
21
22// HACK
23static void AddGeometry(SceneGraph *scene)
24{
25        scene->mRoot->UpdateBox();
26
27        AxisAlignedBox3 sceneBox = scene->GetBox();
28
29        int n = 200;
30
31        if (0){
32        // form grid of boxes
33        for (int i = 0; i < n; ++ i)
34        {
35                for (int j = 0; j < n; ++ j)
36                {
37                        const Vector3 scale2((float)j * 0.8 / n + 0.1,  0.05, (float)i * 0.8  / (float)n + 0.1);
38               
39                        const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
40               
41                        const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
42                        AxisAlignedBox3 box(pt2, pt2 + boxSize);
43                        Mesh *mesh = CreateMeshFromBox(box);
44
45                        mesh->Preprocess();
46               
47                        MeshInstance *mi = new MeshInstance(mesh);
48                        scene->mRoot->mGeometry.push_back(mi);
49                }
50        }
51
52        for (int i = 0; i < n; ++ i)
53        {
54                for (int j = 0; j < n; ++ j)
55                {
56                        const Vector3 scale2(0.15, (float)j * 0.8 / n + 0.1, (float)i * 0.8  / (float)n + 0.1);
57               
58                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
59               
60                        Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
61                        AxisAlignedBox3 box(pt2, pt2 + boxSize);
62                        Mesh *mesh = CreateMeshFromBox(box);
63
64                        mesh->Preprocess();
65               
66                        MeshInstance *mi = new MeshInstance(mesh);
67                        scene->mRoot->mGeometry.push_back(mi);
68                }
69        }
70
71        for (int i = 0; i < n; ++ i)
72        {
73                const Vector3 scale2(2, 0.2, (float)i * 0.8  / (float)n + 0.1);
74               
75                Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
76               
77                //Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
78                Vector3 boxSize = sceneBox.Size() * Vector3(0.005, 0.02, 0.005);
79                AxisAlignedBox3 box(pt2 + 0.1, pt2 + boxSize);
80                Mesh *mesh = CreateMeshFromBox(box);
81
82                mesh->Preprocess();
83               
84                MeshInstance *mi = new MeshInstance(mesh);
85                scene->mRoot->mGeometry.push_back(mi);
86        }
87       
88        scene->mRoot->UpdateBox();
89        }
90       
91        // plane separating view space regions
92        if (1)
93        {
94                const Vector3 scale(1.0, 0.0, 0);
95
96                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
97
98                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
99                Mesh *planeMesh = new Mesh();
100               
101                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
102                IncludePolyInMesh(*poly, *planeMesh);
103               
104                planeMesh->Preprocess();
105               
106                MeshInstance *planeMi = new MeshInstance(planeMesh);
107                scene->mRoot->mGeometry.push_back(planeMi);
108        }       
109}
110
111
112Preprocessor::Preprocessor():
113mKdTree(NULL),
114mBspTree(NULL),
115mVspKdTree(NULL),
116mVspBspTree(NULL),
117mViewCellsManager(NULL)
118{
119        environment->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
120 
121        // renderer will be constructed when the scene graph and viewcell manager will be known
122        renderer = NULL;
123 
124        environment->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
125        environment->GetBoolValue("Preprocessor.loadPolygonsAsMeshes", mLoadPolygonsAsMeshes);
126        environment->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
127        environment->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
128        environment->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
129        environment->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
130
131        char buffer[256];
132        environment->GetStringValue("Preprocessor.visibilityFile",  buffer);
133        mVisibilityFileName = buffer;
134        environment->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter );
135        environment->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
136                                                          mApplyVisibilitySpatialFilter );
137        environment->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
138
139        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
140        Debug << "load polygons as meshes: " << mLoadPolygonsAsMeshes << endl;
141}
142
143
144Preprocessor::~Preprocessor()
145{
146  cout << "cleaning up" << endl;
147
148  cout << "Deleting view cells manager ... \n";
149  DEL_PTR(mViewCellsManager);
150  cout << "done.\n";
151
152  cout << "Deleting bsp tree ... \n";
153  DEL_PTR(mBspTree);
154  cout << "done.\n";
155
156  cout << "Deleting kd tree...\n";
157  DEL_PTR(mKdTree);
158  cout << "done.\n";
159 
160  cout << "Deleting vspkd tree...\n";
161  DEL_PTR(mVspKdTree);
162  cout << "done.\n";
163
164  cout << "Deleting vspbsp tree...\n";
165  DEL_PTR(mVspBspTree);
166  cout << "done.\n";
167}
168
169int
170SplitFilenames(const string str, vector<string> &filenames)
171{
172        int pos = 0;
173
174        while(1) {
175                int npos = (int)str.find(';', pos);
176               
177                if (npos < 0 || npos - pos < 1)
178                        break;
179                filenames.push_back(string(str, pos, npos - pos));
180                pos = npos + 1;
181        }
182       
183        filenames.push_back(string(str, pos, str.size() - pos));
184        return (int)filenames.size();
185}
186
187
188bool
189Preprocessor::LoadScene(const string filename)
190{
191        // use leaf nodes of the original spatial hierarchy as occludees
192        mSceneGraph = new SceneGraph;
193 
194        Parser *parser;
195        vector<string> filenames;
196        int files = SplitFilenames(filename, filenames);
197        cout << "number of input files: " << files << endl;
198        bool result = false;
199        if (files == 1) {
200               
201                if (strstr(filename.c_str(), ".x3d"))
202                  parser = new X3dParser;
203                else
204                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
205                        parser = new PlyParser;
206                  else
207                        parser = new UnigraphicsParser;
208
209                cout<<filename<<endl;
210                result = parser->ParseFile(filename, &mSceneGraph->mRoot, mLoadPolygonsAsMeshes);
211
212                delete parser;
213
214        } else {
215                // root for different files
216                mSceneGraph->mRoot = new SceneGraphNode;
217                for (int i= 0; i < filenames.size(); i++) {
218                        if (strstr(filenames[i].c_str(), ".x3d"))
219                                parser = new X3dParser;
220                        else
221                                parser = new UnigraphicsParser;
222                       
223                        SceneGraphNode *node;
224                        if (parser->ParseFile(filenames[i], &node)) {
225                                mSceneGraph->mRoot->mChildren.push_back(node);
226                                // at least one file parsed
227                                result = true;
228                        }
229                        delete parser;
230                }
231        }
232       
233
234        if (result)
235        {
236                // HACK
237                //AddGeometry(mSceneGraph);
238          mSceneGraph->AssignObjectIds();
239               
240          int intersectables, faces;
241          mSceneGraph->GetStatistics(intersectables, faces);
242
243          cout<<filename<<" parsed successfully."<<endl;
244          cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
245          cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
246          mSceneGraph->CollectObjects(&mObjects);
247          mSceneGraph->mRoot->UpdateBox();
248
249         /* Exporter *exporter = Exporter::GetExporter("testload.x3d");
250
251          if (exporter)
252          {
253                  exporter->ExportGeometry(mObjects);
254                  delete exporter;
255          }*/
256
257        }
258       
259       
260        return result;
261}
262
263bool
264Preprocessor::ExportPreprocessedData(const string filename)
265{
266 
267  mViewCellsManager->ExportViewCells(filename, true, mObjects);
268 
269  return true;
270}
271
272bool
273Preprocessor::PostProcessVisibility()
274{
275 
276  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
277        cout<<"Applying visibility filter...";
278        cout<<"filyter width = "<<mVisibilityFilterWidth<<endl;
279       
280        mViewCellsManager->ApplyFilter(mKdTree,
281                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
282                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
283        cout<<"done.";
284  }
285 
286  // export the preprocessed information to a file
287  if (mExportVisibility)
288        ExportPreprocessedData(mVisibilityFileName);
289 
290  return true;
291}
292
293
294bool
295Preprocessor::BuildKdTree()
296{
297  mKdTree = new KdTree;
298  // add mesh instances of the scene graph to the root of the tree
299  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
300  mSceneGraph->CollectObjects(&root->mObjects);
301 
302  mKdTree->Construct();
303  return true;
304}
305
306void
307Preprocessor::KdTreeStatistics(ostream &s)
308{
309  s<<mKdTree->GetStatistics();
310}
311
312void
313Preprocessor::BspTreeStatistics(ostream &s)
314{
315        s << mBspTree->GetStatistics();
316}
317
318bool
319Preprocessor::Export( const string filename,
320                                          const bool scene,
321                                          const bool kdtree,
322                                          const bool bsptree
323                                          )
324{
325  Exporter *exporter = Exporter::GetExporter(filename);
326       
327  if (exporter) {
328    if (scene)
329      exporter->ExportScene(mSceneGraph->mRoot);
330
331    if (kdtree) {
332      exporter->SetWireframe();
333      exporter->ExportKdTree(*mKdTree);
334    }
335
336        if (bsptree) {
337                //exporter->SetWireframe();
338                exporter->ExportBspTree(*mBspTree);
339        }
340
341    delete exporter;
342    return true;
343  }
344
345  return false;
346}
347
348
349bool Preprocessor::PrepareViewCells()
350{
351        //-- parse view cells construction method
352        environment->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
353        char buf[100];
354       
355        if (mLoadViewCells)
356        {
357                environment->GetStringValue("ViewCells.filename", buf);
358                mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, environment, true);
359        }
360        else
361        {
362                //-- parse type of view cell container
363                char viewCellsStr[64];
364                environment->GetStringValue("ViewCells.type", viewCellsStr);
365            mViewCellsManager = CreateViewCellsManager(viewCellsStr);
366        }
367
368        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
369
370        environment->GetFloatValue("Simulation.objRenderCost",objRenderCost);
371        environment->GetFloatValue("Simulation.vcOverhead", vcOverhead);
372        environment->GetFloatValue("Simulation.moveSpeed", moveSpeed);
373       
374        mRenderSimulator =
375                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
376
377        mViewCellsManager->SetRenderer(mRenderSimulator);
378
379
380        if (mUseGlRenderer || mUseGlDebugger)
381        {
382                // NOTE: render texture should be power of 2 and square
383                // renderer must be initialised
384                renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
385                //              renderer->makeCurrent();
386               
387        }
388       
389        return true;
390}
391
392
393ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
394{
395        if (strcmp(name, "kdTree") == 0)
396        {
397                mViewCellsManager = new KdViewCellsManager(mKdTree, environment);
398        }
399        else if (strcmp(name, "bspTree") == 0)
400        {
401                Debug << "view cell type: Bsp" << endl;
402
403                mBspTree = new BspTree();
404                mViewCellsManager = new BspViewCellsManager(mBspTree, environment);
405        }
406        else if (strcmp(name, "vspBspTree") == 0)
407        {
408                Debug << "view cell type: VspBsp" << endl;
409
410                mVspBspTree = new VspBspTree(environment);
411                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree, environment);
412        }
413        else if (strcmp(name, "vspKdTree") == 0)
414        {
415                mVspKdTree = new VspKdTree();           
416       
417                mViewCellsManager = new VspKdViewCellsManager(mVspKdTree, environment);
418        }
419        else if (strcmp(name, "sceneDependent") == 0)
420        {
421                //TODO
422                mBspTree = new BspTree();
423
424                Debug << "view cell type: Bsp" << endl;
425               
426                mViewCellsManager = new BspViewCellsManager(mBspTree, environment);
427        }
428        else
429        {
430                cerr << "Wrong view cells type " << name << "!!!" << endl;
431                exit(1);
432        }
433
434        return mViewCellsManager;
435}
436
437
438// use ascii format to store rays
439#define USE_ASCII 0
440
441
442inline bool ilt(Intersectable *obj1, Intersectable *obj2)
443{
444        return obj1->mId < obj2->mId;
445}
446
447
448bool Preprocessor::LoadSamples(VssRayContainer &samples,
449                                                           ObjectContainer &objects) const
450{
451        std::stable_sort(objects.begin(), objects.end(), ilt);
452        char fileName[100];
453        environment->GetStringValue("Preprocessor.samplesFilename", fileName);
454       
455    Vector3 origin, termination;
456        // HACK: needed only for lower_bound algorithm to find the
457        // intersected objects
458        MeshInstance sObj(NULL);
459        MeshInstance tObj(NULL);
460
461#if USE_ASCII
462        ifstream samplesIn(fileName);
463        if (!samplesIn.is_open())
464                return false;
465
466        string buf;
467        while (!(getline(samplesIn, buf)).eof())
468        {
469                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
470                           &origin.x, &origin.y, &origin.z,
471                           &termination.x, &termination.y, &termination.z,
472                           &(sObj.mId), &(tObj.mId));
473               
474                Intersectable *sourceObj = NULL;
475                Intersectable *termObj = NULL;
476               
477                if (sObj.mId >= 0)
478                {
479                        ObjectContainer::iterator oit =
480                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
481                        sourceObj = *oit;
482                }
483               
484                if (tObj.mId >= 0)
485                {
486                        ObjectContainer::iterator oit =
487                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
488                        termObj = *oit;
489                }
490
491                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
492        }
493#else
494        ifstream samplesIn(fileName, ios::binary);
495        if (!samplesIn.is_open())
496                return false;
497
498        while (1)
499        {
500                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
501                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
502                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
503                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
504               
505                 if (samplesIn.eof())
506                        break;
507
508                Intersectable *sourceObj = NULL;
509                Intersectable *termObj = NULL;
510               
511                if (sObj.mId >= 0)
512                {
513                        ObjectContainer::iterator oit =
514                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
515                        sourceObj = *oit;
516                }
517               
518                if (tObj.mId >= 0)
519                {
520                        ObjectContainer::iterator oit =
521                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
522                        termObj = *oit;
523                }
524
525                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
526        }
527
528#endif
529        samplesIn.close();
530
531        return true;
532}
533
534
535bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
536{
537        char fileName[100];
538        environment->GetStringValue("Preprocessor.samplesFilename", fileName);
539       
540
541        VssRayContainer::const_iterator it, it_end = samples.end();
542       
543#if USE_ASCII
544        ofstream samplesOut(fileName);
545        if (!samplesOut.is_open())
546                return false;
547
548        for (it = samples.begin(); it != it_end; ++ it)
549        {
550                VssRay *ray = *it;
551                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
552                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
553
554                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
555                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
556                                   << sourceid << " " << termid << "\n";
557        }
558#else
559        ofstream samplesOut(fileName, ios::binary);
560        if (!samplesOut.is_open())
561                return false;
562
563        for (it = samples.begin(); it != it_end; ++ it)
564        {       
565                VssRay *ray = *it;
566                Vector3 origin(ray->GetOrigin());
567                Vector3 termination(ray->GetTermination());
568               
569                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
570                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
571
572                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
573                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
574                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
575                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
576    }
577#endif
578        samplesOut.close();
579        return true;
580}
581
582
583
584bool
585Preprocessor::GenerateRays(
586                                                   const int number,
587                                                   const int sampleType,
588                                                   SimpleRayContainer &rays
589                                                   )
590{
591  Vector3 origin, direction;
592  int startSize = (int)rays.size();
593  for (int i=0; (int)rays.size() - startSize  < number; i ++) {
594        // now get the direction
595        switch (sampleType) {
596        case OBJECT_BASED_DISTRIBUTION: {
597          mViewCellsManager->GetViewPoint(origin);
598          Vector3 point;
599          Vector3 normal;
600          int i = RandomValue(0, mObjects.size() - 1);
601          Intersectable *object = mObjects[i];
602          object->GetRandomSurfacePoint(point, normal);
603          direction = point - origin;
604        }
605          break;
606        case OBJECT_DIRECTION_BASED_DISTRIBUTION: {
607          int i = RandomValue(0, mObjects.size() - 1);
608          Intersectable *object = mObjects[i];
609          Vector3 normal;
610          object->GetRandomSurfacePoint(origin, normal);
611          direction = UniformRandomVector(normal);
612          origin += 0.1f*direction;
613        }
614          break;
615        case DIRECTION_BASED_DISTRIBUTION:
616          mViewCellsManager->GetViewPoint(origin);
617          direction = UniformRandomVector();
618          break;
619        case DIRECTION_BOX_BASED_DISTRIBUTION: {
620          mViewCellsManager->GetViewPoint(origin);
621          float alpha = RandomValue(0.0f, 2*M_PI);
622          float beta = RandomValue(-M_PI/2, M_PI/2);
623          direction = VssRay::GetDirection(alpha, beta);
624          break;
625        }
626        case SPATIAL_BOX_BASED_DISTRIBUTION:
627          mViewCellsManager->GetViewPoint(origin);
628          direction = mKdTree->GetBox().GetRandomPoint() - origin;
629          break;
630        default:
631          // unsuported distribution type
632          return false;
633        }
634        // $$ jb the pdf is yet not correct for all sampling methods!
635        float pdf = 1.0f;
636        float c = Magnitude(direction);
637        if (c > Limits::Small) {
638          direction*=1.0f/c;
639          rays.AddRay(SimpleRay(origin, direction, pdf));
640        }
641  }
642  return true;
643}
644
645}
Note: See TracBrowser for help on using the repository browser.