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

Revision 871, 16.0 KB checked in by bittner, 18 years ago (diff)

RenderSampler?

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