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

Revision 925, 16.4 KB checked in by mattausch, 18 years ago (diff)

update for ogre 1.2
OcclusionCullingSceneManager? is the only scenemanager in the solution now

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 = CreateBox(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 = CreateBox(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 = CreateBox(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,
268                                                                         true);
269 
270  return true;
271}
272
273bool
274Preprocessor::PostProcessVisibility()
275{
276 
277  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
278        cout<<"Applying visibility filter...";
279        cout<<"filyter width = "<<mVisibilityFilterWidth<<endl;
280       
281        mViewCellsManager->ApplyFilter(mKdTree,
282                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
283                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
284        cout<<"done.";
285  }
286 
287  // export the preprocessed information to a file
288  if (mExportVisibility)
289        ExportPreprocessedData(mVisibilityFileName);
290 
291  return true;
292}
293
294
295bool
296Preprocessor::BuildKdTree()
297{
298  mKdTree = new KdTree;
299  // add mesh instances of the scene graph to the root of the tree
300  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
301  mSceneGraph->CollectObjects(&root->mObjects);
302 
303  mKdTree->Construct();
304  return true;
305}
306
307void
308Preprocessor::KdTreeStatistics(ostream &s)
309{
310  s<<mKdTree->GetStatistics();
311}
312
313void
314Preprocessor::BspTreeStatistics(ostream &s)
315{
316        s << mBspTree->GetStatistics();
317}
318
319bool
320Preprocessor::Export( const string filename,
321                                          const bool scene,
322                                          const bool kdtree,
323                                          const bool bsptree
324                                          )
325{
326  Exporter *exporter = Exporter::GetExporter(filename);
327       
328  if (exporter) {
329    if (scene)
330      exporter->ExportScene(mSceneGraph->mRoot);
331
332    if (kdtree) {
333      exporter->SetWireframe();
334      exporter->ExportKdTree(*mKdTree);
335    }
336
337        if (bsptree) {
338                //exporter->SetWireframe();
339                exporter->ExportBspTree(*mBspTree);
340        }
341
342    delete exporter;
343    return true;
344  }
345
346  return false;
347}
348
349
350bool Preprocessor::PrepareViewCells()
351{
352        //-- parse view cells construction method
353        environment->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
354        char buf[100];
355       
356        if (mLoadViewCells)
357        {
358                environment->GetStringValue("ViewCells.filename", buf);
359                mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects);
360        }
361        else
362        {
363                //-- parse type of view cell container
364                char viewCellsStr[64];
365                environment->GetStringValue("ViewCells.type", viewCellsStr);
366            mViewCellsManager = CreateViewCellsManager(viewCellsStr);
367        }
368
369        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
370
371        environment->GetFloatValue("Simulation.objRenderCost",objRenderCost);
372        environment->GetFloatValue("Simulation.vcOverhead", vcOverhead);
373        environment->GetFloatValue("Simulation.moveSpeed", moveSpeed);
374       
375        mRenderSimulator =
376                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
377
378        mViewCellsManager->SetRenderer(mRenderSimulator);
379
380
381        if (mUseGlRenderer || mUseGlDebugger)
382        {
383                // NOTE: render texture should be power of 2 and square
384                // renderer must be initialised
385                renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
386                //              renderer->makeCurrent();
387               
388        }
389       
390        return true;
391}
392
393
394ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
395{
396        if (strcmp(name, "kdTree") == 0)
397        {
398                mViewCellsManager = new KdViewCellsManager(mKdTree);
399        }
400        else if (strcmp(name, "bspTree") == 0)
401        {
402                Debug << "view cell type: Bsp" << endl;
403
404                mBspTree = new BspTree();
405                mViewCellsManager = new BspViewCellsManager(mBspTree);
406        }
407        else if (strcmp(name, "vspBspTree") == 0)
408        {
409                Debug << "view cell type: VspBsp" << endl;
410
411                mVspBspTree = new VspBspTree(environment);
412                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree);
413        }
414        else if (strcmp(name, "vspKdTree") == 0)
415        {
416                mVspKdTree = new VspKdTree();           
417       
418                mViewCellsManager = new VspKdViewCellsManager(mVspKdTree);
419        }
420        else if (strcmp(name, "sceneDependent") == 0)
421        {
422                //TODO
423                mBspTree = new BspTree();
424
425                Debug << "view cell type: Bsp" << endl;
426               
427                mViewCellsManager = new BspViewCellsManager(mBspTree);
428        }
429        else
430        {
431                cerr << "Wrong view cells type " << name << "!!!" << endl;
432                exit(1);
433        }
434
435        return mViewCellsManager;
436}
437
438
439// use ascii format to store rays
440#define USE_ASCII 0
441
442
443inline bool ilt(Intersectable *obj1, Intersectable *obj2)
444{
445        return obj1->mId < obj2->mId;
446}
447
448
449bool Preprocessor::LoadSamples(VssRayContainer &samples,
450                                                           ObjectContainer &objects) const
451{
452        std::stable_sort(objects.begin(), objects.end(), ilt);
453        char fileName[100];
454        environment->GetStringValue("Preprocessor.samplesFilename", fileName);
455       
456    Vector3 origin, termination;
457        // HACK: needed only for lower_bound algorithm to find the
458        // intersected objects
459        MeshInstance sObj(NULL);
460        MeshInstance tObj(NULL);
461
462#if USE_ASCII
463        ifstream samplesIn(fileName);
464        if (!samplesIn.is_open())
465                return false;
466
467        string buf;
468        while (!(getline(samplesIn, buf)).eof())
469        {
470                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
471                           &origin.x, &origin.y, &origin.z,
472                           &termination.x, &termination.y, &termination.z,
473                           &(sObj.mId), &(tObj.mId));
474               
475                Intersectable *sourceObj = NULL;
476                Intersectable *termObj = NULL;
477               
478                if (sObj.mId >= 0)
479                {
480                        ObjectContainer::iterator oit =
481                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
482                        sourceObj = *oit;
483                }
484               
485                if (tObj.mId >= 0)
486                {
487                        ObjectContainer::iterator oit =
488                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
489                        termObj = *oit;
490                }
491
492                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
493        }
494#else
495        ifstream samplesIn(fileName, ios::binary);
496        if (!samplesIn.is_open())
497                return false;
498
499        while (1)
500        {
501                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
502                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
503                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
504                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
505               
506                 if (samplesIn.eof())
507                        break;
508
509                Intersectable *sourceObj = NULL;
510                Intersectable *termObj = NULL;
511               
512                if (sObj.mId >= 0)
513                {
514                        ObjectContainer::iterator oit =
515                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
516                        sourceObj = *oit;
517                }
518               
519                if (tObj.mId >= 0)
520                {
521                        ObjectContainer::iterator oit =
522                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
523                        termObj = *oit;
524                }
525
526                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
527        }
528
529#endif
530        samplesIn.close();
531
532        return true;
533}
534
535
536bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
537{
538        char fileName[100];
539        environment->GetStringValue("Preprocessor.samplesFilename", fileName);
540       
541
542        VssRayContainer::const_iterator it, it_end = samples.end();
543       
544#if USE_ASCII
545        ofstream samplesOut(fileName);
546        if (!samplesOut.is_open())
547                return false;
548
549        for (it = samples.begin(); it != it_end; ++ it)
550        {
551                VssRay *ray = *it;
552                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
553                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
554
555                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
556                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
557                                   << sourceid << " " << termid << "\n";
558        }
559#else
560        ofstream samplesOut(fileName, ios::binary);
561        if (!samplesOut.is_open())
562                return false;
563
564        for (it = samples.begin(); it != it_end; ++ it)
565        {       
566                VssRay *ray = *it;
567                Vector3 origin(ray->GetOrigin());
568                Vector3 termination(ray->GetTermination());
569               
570                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
571                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
572
573                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
574                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
575                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
576                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
577    }
578#endif
579        samplesOut.close();
580        return true;
581}
582
583
584
585bool
586Preprocessor::GenerateRays(
587                                                   const int number,
588                                                   const int sampleType,
589                                                   SimpleRayContainer &rays
590                                                   )
591{
592  Vector3 origin, direction;
593  int startSize = (int)rays.size();
594  for (int i=0; (int)rays.size() - startSize  < number; i ++) {
595        // now get the direction
596        switch (sampleType) {
597        case OBJECT_BASED_DISTRIBUTION: {
598          mViewCellsManager->GetViewPoint(origin);
599          Vector3 point;
600          Vector3 normal;
601          int i = RandomValue(0, mObjects.size() - 1);
602          Intersectable *object = mObjects[i];
603          object->GetRandomSurfacePoint(point, normal);
604          direction = point - origin;
605        }
606          break;
607        case OBJECT_DIRECTION_BASED_DISTRIBUTION: {
608          int i = RandomValue(0, mObjects.size() - 1);
609          Intersectable *object = mObjects[i];
610          Vector3 normal;
611          object->GetRandomSurfacePoint(origin, normal);
612          direction = UniformRandomVector(normal);
613          origin += 0.1f*direction;
614        }
615          break;
616        case DIRECTION_BASED_DISTRIBUTION:
617          mViewCellsManager->GetViewPoint(origin);
618          direction = UniformRandomVector();
619          break;
620        case DIRECTION_BOX_BASED_DISTRIBUTION: {
621          mViewCellsManager->GetViewPoint(origin);
622          float alpha = RandomValue(0.0f, 2*M_PI);
623          float beta = RandomValue(-M_PI/2, M_PI/2);
624          direction = VssRay::GetDirection(alpha, beta);
625          break;
626        }
627        case SPATIAL_BOX_BASED_DISTRIBUTION:
628          mViewCellsManager->GetViewPoint(origin);
629          direction = mKdTree->GetBox().GetRandomPoint() - origin;
630          break;
631        default:
632          // unsuported distribution type
633          return false;
634        }
635        // $$ jb the pdf is yet not correct for all sampling methods!
636        float pdf = 1.0f;
637        float c = Magnitude(direction);
638        if (c > Limits::Small) {
639          direction*=1.0f/c;
640          rays.AddRay(SimpleRay(origin, direction, pdf));
641        }
642  }
643  return true;
644}
645
646}
Note: See TracBrowser for help on using the repository browser.