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

Revision 1006, 17.1 KB checked in by mattausch, 18 years ago (diff)

started viewspace-objectspace subdivision
removed memory leaks

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