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

Revision 863, 15.2 KB checked in by mattausch, 18 years ago (diff)

working on preprocessor integration
added iv stuff

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