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

Revision 1996, 36.2 KB checked in by mattausch, 17 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 "RenderSimulator.h"
12#include "GlRenderer.h"
13#include "PlyParser.h"
14#include "SamplingStrategy.h"
15#include "VspTree.h"
16#include "OspTree.h"
17#include "ObjParser.h"
18#include "BvHierarchy.h"
19#include "HierarchyManager.h"
20#include "VssRay.h"
21#include "IntelRayCaster.h"
22#include "InternalRayCaster.h"
23#include "GlobalLinesRenderer.h"
24
25
26#define DEBUG_RAYCAST 0
27#define SHOW_RAYCAST_TIMING 1
28
29
30namespace GtpVisibilityPreprocessor {
31
32  const static bool ADDITIONAL_GEOMETRY_HACK = false;
33
34  Preprocessor *preprocessor = NULL;
35 
36// HACK: Artificially modify scene to watch rendercost changes
37static void AddGeometry(SceneGraph *scene)
38{
39        scene->GetRoot()->UpdateBox();
40
41        AxisAlignedBox3 sceneBox = scene->GetBox();
42
43        int n = 200;
44
45        if (0)
46        {
47                // form grid of boxes
48                for (int i = 0; i < n; ++ i)
49                {
50                        for (int j = 0; j < n; ++ j)
51                        {
52                                const Vector3 scale2((float)j * 0.8f / n + 0.1f,  0.05f, (float)i * 0.8f  / (float)n + 0.1f);
53
54                                const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
55
56                                const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
57                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
58                                Mesh *mesh = CreateMeshFromBox(box);
59
60                                mesh->Preprocess();
61
62                                MeshInstance *mi = new MeshInstance(mesh);
63                                scene->GetRoot()->mGeometry.push_back(mi);
64                        }
65                }
66
67                for (int i = 0; i < n; ++ i)
68                {
69                        for (int j = 0; j < n; ++ j)
70                        {
71                                const Vector3 scale2(0.15f, (float)j * 0.8f / n + 0.1f, (float)i * 0.8f  / (float)n + 0.1f);
72
73                                Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
74
75                                Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
76                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
77                                Mesh *mesh = CreateMeshFromBox(box);
78
79                                mesh->Preprocess();
80
81                                MeshInstance *mi = new MeshInstance(mesh);
82                                scene->GetRoot()->mGeometry.push_back(mi);
83                        }
84                }
85
86                for (int i = 0; i < n; ++ i)
87                {
88                        const Vector3 scale2(2, 0.2f, (float)i * 0.8f  / (float)n + 0.1f);
89
90                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
91                        Vector3 boxSize = sceneBox.Size() * Vector3(0.005f, 0.02f, 0.005f);
92
93                        AxisAlignedBox3 box(pt2 + 0.1f, pt2 + boxSize);
94                        Mesh *mesh = CreateMeshFromBox(box);
95
96                        mesh->Preprocess();
97
98                        MeshInstance *mi = new MeshInstance(mesh);
99                        scene->GetRoot()->mGeometry.push_back(mi);
100                }
101
102                scene->GetRoot()->UpdateBox();
103        }
104
105        if (1)
106        {
107                // plane separating view space regions
108                const Vector3 scale(1.0f, 0.0, 0);
109
110                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
111
112                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
113                Mesh *planeMesh = new Mesh();
114
115                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
116                IncludePolyInMesh(*poly, *planeMesh);
117
118                planeMesh->Preprocess();
119
120                MeshInstance *planeMi = new MeshInstance(planeMesh);
121                scene->GetRoot()->mGeometry.push_back(planeMi);
122        }       
123}
124
125
126Preprocessor::Preprocessor():
127mKdTree(NULL),
128mBspTree(NULL),
129mVspBspTree(NULL),
130mViewCellsManager(NULL),
131mRenderSimulator(NULL),
132mPass(0),
133mSceneGraph(NULL),
134mRayCaster(NULL),
135mStopComputation(false),
136mThread(NULL),
137mGlobalLinesRenderer(NULL)
138{
139        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
140 
141        // renderer will be constructed when the scene graph and viewcell manager will be known
142        renderer = NULL;
143       
144        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
145        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadMeshes", mLoadMeshes);
146        Environment::GetSingleton()->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
147        Environment::GetSingleton()->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
148        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
149        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
150       
151        char buffer[256];
152        Environment::GetSingleton()->GetStringValue("Preprocessor.visibilityFile",  buffer);
153        mVisibilityFileName = buffer;
154       
155        Environment::GetSingleton()->GetStringValue("Preprocessor.stats",  buffer);
156        mStats.open(buffer);
157       
158       
159        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter);
160        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
161                                                                                          mApplyVisibilitySpatialFilter );
162        Environment::GetSingleton()->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
163
164        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportObj", mExportObj);
165       
166        Environment::GetSingleton()->GetBoolValue("Preprocessor.useViewSpaceBox", mUseViewSpaceBox);
167
168        Environment::GetSingleton()->GetBoolValue("Preprocessor.Export.rays", mExportRays);
169        Environment::GetSingleton()->GetIntValue("Preprocessor.Export.numRays", mExportNumRays);
170
171
172        Environment::GetSingleton()->GetIntValue("Preprocessor.samplesPerPass", mSamplesPerPass);
173        Environment::GetSingleton()->GetIntValue("Preprocessor.totalSamples", mTotalSamples);
174        Environment::GetSingleton()->GetIntValue("Preprocessor.samplesPerEvaluation",
175                                                                                         mSamplesPerEvaluation);
176
177        Debug << "******* Preprocessor Options **********" << endl;
178        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
179        Debug << "load meshes: " << mLoadMeshes << endl;
180        Debug << "load meshes: " << mLoadMeshes << endl;
181        Debug << "export obj: " << mExportObj << endl;
182        Debug << "use view space box: " << mUseViewSpaceBox << endl;
183}
184
185
186Preprocessor::~Preprocessor()
187{
188        cout << "cleaning up" << endl;
189
190        cout << "Deleting view cells manager ... \n";
191        DEL_PTR(mViewCellsManager);
192        cout << "done.\n";
193
194        cout << "Deleting bsp tree ... \n";
195        DEL_PTR(mBspTree);
196        cout << "done.\n";
197
198        cout << "Deleting kd tree ...\n";
199        DEL_PTR(mKdTree);
200        cout << "done.\n";
201
202        cout << "Deleting vspbsp tree ... \n";
203        DEL_PTR(mVspBspTree);
204        cout << "done.\n";
205
206        cout << "Deleting scene graph ... \n";
207        DEL_PTR(mSceneGraph);
208        cout << "done.\n";
209
210        DEL_PTR(mRenderSimulator);
211        DEL_PTR(renderer);
212        DEL_PTR(mRayCaster);
213#ifdef USE_CG
214        DEL_PTR(mGlobalLinesRenderer);
215#endif
216}
217
218
219GlRendererBuffer *Preprocessor::GetRenderer()
220{
221        return renderer;
222}
223
224
225static int SplitFilenames(const string str, vector<string> &filenames)
226{
227        int pos = 0;
228
229        while(1) {
230                int npos = (int)str.find(';', pos);
231               
232                if (npos < 0 || npos - pos < 1)
233                        break;
234                filenames.push_back(string(str, pos, npos - pos));
235                pos = npos + 1;
236        }
237       
238        filenames.push_back(string(str, pos, str.size() - pos));
239        return (int)filenames.size();
240}
241
242
243void Preprocessor::SetThread(PreprocessorThread *t)
244{
245        mThread = t;
246}
247
248
249PreprocessorThread *Preprocessor::GetThread() const
250{
251        return mThread;
252}
253
254
255bool Preprocessor::LoadBinaryObj(const string filename,
256                                                                 SceneGraphNode *root,
257                                                                 vector<FaceParentInfo> *parents)
258{
259        //ifstream samplesIn(filename, ios::binary);
260        igzstream samplesIn(filename.c_str());
261       
262        if (!samplesIn.is_open())
263                return false;
264
265        cout << "binary obj dump available, loading " << filename.c_str() << endl;
266        // table associating indices with vectors
267        map<int, Vector3> hashTable;
268
269        // table for vertices
270        VertexContainer vertices;
271        FaceContainer faces;
272
273        if (parents)
274                cout << "using face parents" << endl;
275        else
276                cout << "not using face parents" << endl;
277
278        while (1)
279        {
280                Triangle3 tri;
281               
282                samplesIn.read(reinterpret_cast<char *>(tri.mVertices + 0), sizeof(Vector3));
283                samplesIn.read(reinterpret_cast<char *>(tri.mVertices + 1), sizeof(Vector3));
284                samplesIn.read(reinterpret_cast<char *>(tri.mVertices + 2), sizeof(Vector3));
285               
286                // end of file reached
287                if (samplesIn.eof())
288                        break;
289
290                TriangleIntersectable *obj = new TriangleIntersectable(tri);
291                root->mGeometry.push_back(obj);
292
293                // matt: we don't really need to keep an additional data structure
294                // if working with triangles => remove this
295                if (parents)
296                {
297                        FaceParentInfo info(obj, 0);
298                        parents->push_back(info);
299                }       
300        }
301       
302        return true;
303}
304
305
306bool Preprocessor::ExportBinaryObj(const string filename, SceneGraphNode *root)
307{
308        //ifstream samplesIn(filename, ios::binary);
309        ogzstream samplesOut(filename.c_str());
310        if (!samplesOut.is_open())
311                return false;
312
313        ObjectContainer::const_iterator oit, oit_end = root->mGeometry.end();
314
315        for (oit = root->mGeometry.begin(); oit != oit_end; ++ oit)
316        {
317                Intersectable *obj = *oit;
318
319                if (obj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
320                {
321                        Triangle3 tri = dynamic_cast<TriangleIntersectable *>(obj)->GetItem();
322
323                        samplesOut.write(reinterpret_cast<char *>(tri.mVertices + 0), sizeof(Vector3));
324                        samplesOut.write(reinterpret_cast<char *>(tri.mVertices + 1), sizeof(Vector3));
325                        samplesOut.write(reinterpret_cast<char *>(tri.mVertices + 2), sizeof(Vector3));
326                }
327                else
328                {
329                        cout << "not implemented intersectable type " << obj->Type() << endl;
330                }
331        }
332
333        return true;
334}
335
336
337bool Preprocessor::ExportObj(const string filename, const ObjectContainer &objects)
338{
339        ofstream samplesOut(filename.c_str());
340
341        if (!samplesOut.is_open())
342                return false;
343
344        ObjectContainer::const_iterator oit, oit_end = objects.end();
345
346        AxisAlignedBox3 bbox = mSceneGraph->GetBox(); bbox.Enlarge(30.0);
347        for (oit = objects.begin(); oit != oit_end; ++ oit)
348        {
349                Intersectable *obj = *oit;
350
351                if (obj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
352                {
353                        Triangle3 tri = dynamic_cast<TriangleIntersectable *>(obj)->GetItem();
354                        //if (bbox.IsInside(tri.mVertices[0]) && bbox.IsInside(tri.mVertices[1]) && bbox.IsInside(tri.mVertices[2]))
355                        //{
356                                samplesOut << "v " << tri.mVertices[0].x << " " << tri.mVertices[0].y << " " << tri.mVertices[0].z << endl;
357                                samplesOut << "v " << tri.mVertices[1].x << " " << tri.mVertices[1].y << " " << tri.mVertices[1].z << endl;
358                                samplesOut << "v " << tri.mVertices[2].x << " " << tri.mVertices[2].y << " " << tri.mVertices[2].z << endl;
359                        //}
360                }
361                else
362                {
363                        cout << "not implemented intersectable type " << obj->Type() << endl;
364                }
365        }
366
367        // write faces
368        int i = 1;
369        for (oit = objects.begin(); oit != oit_end; ++ oit)
370        {
371                Intersectable *obj = *oit;
372                if (obj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
373                {
374                        //Triangle3 tri = dynamic_cast<TriangleIntersectable *>(obj)->GetItem();
375                        //if (bbox.IsInside(tri.mVertices[0]) && bbox.IsInside(tri.mVertices[1]) && bbox.IsInside(tri.mVertices[2]))
376                        //{
377                                Triangle3 tri = dynamic_cast<TriangleIntersectable *>(obj)->GetItem();
378                                samplesOut << "f " << i << " " << i + 1 << " " << i + 2 << endl;
379                                i += 3;
380                        //}
381                }
382                else
383                {
384                        cout << "not implemented intersectable type " << obj->Type() << endl;
385                }
386        }
387
388        return true;
389
390}
391
392static string ReplaceSuffix(string filename, string a, string b)
393{
394        string result = filename;
395
396        int pos = (int)filename.rfind(a, (int)filename.size() - 1);
397        if (pos == filename.size() - a.size()) {
398                result.replace(pos, a.size(), b);
399        }
400        return result;
401}
402
403
404Intersectable *Preprocessor::GetParentObject(const int index) const
405{
406        if (index == -1)
407          return NULL;
408       
409        if (!mFaceParents.empty())
410        {
411                if (index >= (int)mFaceParents.size())
412                {
413                        cerr << "Warning: triangle index out of range! " << index << endl;
414                        return NULL;
415                }
416                else
417                {
418                        return mFaceParents[index].mObject;
419                }
420        }
421        else
422          {
423          if (index >= (int)mObjects.size()) {
424                cerr<<"Warning: triangle  index out of range! "<<index<<endl;
425                return NULL;
426          }
427          else
428                {
429                  return mObjects[index];
430                }
431          }
432}
433
434
435Vector3 Preprocessor::GetParentNormal(const int index) const
436{
437        if (!mFaceParents.empty())
438        {
439                return mFaceParents[index].mObject->GetNormal(mFaceParents[index].mFaceIndex);
440        }       
441        else
442        {
443                return mObjects[index]->GetNormal(0);
444        }
445}
446
447
448bool
449Preprocessor::LoadScene(const string filename)
450{
451    // use leaf nodes of the original spatial hierarchy as occludees
452        mSceneGraph = new SceneGraph;
453 
454        Parser *parser;
455        vector<string> filenames;
456        const int files = SplitFilenames(filename, filenames);
457        cout << "number of input files: " << files << endl;
458        bool result = false;
459        bool isObj = false;
460
461        // root for different files
462        mSceneGraph->SetRoot(new SceneGraphNode());
463
464        // intel ray caster can only trace triangles
465        int rayCastMethod;
466        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
467        vector<FaceParentInfo> *fi =
468          ((rayCastMethod == RayCaster::INTEL_RAYCASTER) && mLoadMeshes) ?
469          &mFaceParents : NULL;
470       
471        if (files == 1)
472          {
473                if (strstr(filename.c_str(), ".x3d"))
474                  {
475                        parser = new X3dParser;
476                       
477                        result = parser->ParseFile(filename,
478                                                                           mSceneGraph->GetRoot(),
479                                                                           mLoadMeshes,
480                                                                           fi);
481                        delete parser;
482                }
483                else if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
484                {
485                        parser = new PlyParser;
486
487                        result = parser->ParseFile(filename,
488                                                                           mSceneGraph->GetRoot(),
489                                                                           mLoadMeshes,
490                                                                           fi);
491                        delete parser;
492                }
493                else if (strstr(filename.c_str(), ".obj"))
494                {
495                        isObj = true;
496
497                        // hack: load binary dump
498                        string binFile = ReplaceSuffix(filename, ".obj", ".bin");
499
500                        if (!mLoadMeshes)
501                        {
502                                result = LoadBinaryObj(binFile, mSceneGraph->GetRoot(), fi);
503                        }
504
505                        if (!result)
506                        {
507                                cout << "no binary dump available or loading full meshes, parsing file" << endl;
508                                parser = new ObjParser;
509               
510                                result = parser->ParseFile(filename,
511                                                                   mSceneGraph->GetRoot(),
512                                                                   mLoadMeshes,
513                                                                   fi);
514                                               
515                                // only works for triangles
516                                if (!mLoadMeshes)
517                                {
518                                        cout << "exporting binary obj to " << binFile << "... " << endl;
519                                        ExportBinaryObj(binFile, mSceneGraph->GetRoot());
520                                        cout << "finished" << endl;
521                                }
522
523                                delete parser;
524                        }
525                        else if (0)
526                        {
527                                ExportBinaryObj("../data/test.bin", mSceneGraph->GetRoot());
528                        }
529                }
530                else
531                {
532                        parser = new UnigraphicsParser;
533                        result = parser->ParseFile(filename,
534                                                                           mSceneGraph->GetRoot(),
535                                                                           mLoadMeshes,                                                           
536                                                                           fi);
537                        delete parser;
538                }
539               
540                cout << filename << endl;
541        }
542        else
543        {
544                vector<string>::const_iterator fit, fit_end = filenames.end();
545               
546                for (fit = filenames.begin(); fit != fit_end; ++ fit)
547                {
548                        const string filename = *fit;
549
550                        cout << "parsing file " << filename.c_str() << endl;
551                        if (strstr(filename.c_str(), ".x3d"))
552                                parser = new X3dParser;
553                        else
554                                parser = new UnigraphicsParser;
555
556                        SceneGraphNode *node = new SceneGraphNode();
557                        const bool success =
558                                parser->ParseFile(filename, node, mLoadMeshes, fi);
559
560                        if (success)
561                        {
562                                mSceneGraph->GetRoot()->mChildren.push_back(node);
563                                result = true; // at least one file parsed
564                        }
565
566                        // temporare hack
567                        //if (!strstr(filename.c_str(), "plane")) mSceneGraph->GetRoot()->UpdateBox();
568
569                        delete parser;
570                }
571        }
572       
573        if (result)
574        {
575                // HACK
576                if (ADDITIONAL_GEOMETRY_HACK)
577                        AddGeometry(mSceneGraph);
578
579                mSceneGraph->AssignObjectIds();
580 
581                int intersectables, faces;
582                mSceneGraph->GetStatistics(intersectables, faces);
583 
584                cout<<filename<<" parsed successfully."<<endl;
585                cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
586                cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
587               
588                mObjects.reserve(intersectables);
589                mSceneGraph->CollectObjects(&mObjects);
590               
591                // temp hack
592                //ExportObj("cropped_vienna.obj", mObjects);
593                mSceneGraph->GetRoot()->UpdateBox();
594                               
595                cout << "finished loading" << endl;
596        }
597
598        return result;
599}
600
601bool
602Preprocessor::ExportPreprocessedData(const string filename)
603{
604        mViewCellsManager->ExportViewCells(filename, true, mObjects);
605        return true;
606}
607
608
609bool
610Preprocessor::PostProcessVisibility()
611{
612 
613  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
614        cout<<"Applying visibility filter ...";
615        cout<<"filter width = " << mVisibilityFilterWidth << endl;
616       
617        if (!mViewCellsManager)
618          return false;
619       
620        mViewCellsManager->ApplyFilter(mKdTree,
621                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
622                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
623        cout << "done." << endl;
624  }
625 
626  // export the preprocessed information to a file
627  if (mExportVisibility)
628  {
629          ExportPreprocessedData(mVisibilityFileName);
630  }
631
632  return true;
633}
634
635
636bool
637Preprocessor::BuildKdTree()
638{
639  mKdTree = new KdTree;
640
641  // add mesh instances of the scene graph to the root of the tree
642  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
643       
644  mSceneGraph->CollectObjects(&root->mObjects);
645 
646  const long startTime = GetTime();
647  cout << "building kd tree ... " << endl;
648
649  mKdTree->Construct();
650
651  cout << "finished kd tree construction in " << TimeDiff(startTime, GetTime()) * 1e-3
652           << " secs " << endl;
653
654  return true;
655}
656
657
658void
659Preprocessor::KdTreeStatistics(ostream &s)
660{
661  s<<mKdTree->GetStatistics();
662}
663
664void
665Preprocessor::BspTreeStatistics(ostream &s)
666{
667        s << mBspTree->GetStatistics();
668}
669
670bool
671Preprocessor::Export( const string filename,
672                                          const bool scene,
673                                          const bool kdtree
674                                          )
675{
676  Exporter *exporter = Exporter::GetExporter(filename);
677       
678  if (exporter) {
679    if (2 && scene)
680      exporter->ExportScene(mSceneGraph->GetRoot());
681
682    if (1 && kdtree) {
683      exporter->SetWireframe();
684      exporter->ExportKdTree(*mKdTree);
685    }
686
687    delete exporter;
688    return true;
689  }
690
691  return false;
692}
693
694
695bool Preprocessor::PrepareViewCells()
696{
697        ///////
698        //-- parse view cells construction method
699
700        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
701        char buf[100];
702
703        if (mLoadViewCells)
704        {       
705                Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
706                cout << "loading view cells from " << buf << endl<<flush;
707
708                mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, true, NULL);
709
710                cout << "view cells loaded." << endl<<flush;
711
712                if (!mViewCellsManager)
713                {
714                        return false;
715                }
716        }
717        else
718        {
719                // parse type of view cell container
720                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
721                mViewCellsManager = CreateViewCellsManager(buf);
722
723                // default view space is the extent of the scene
724                AxisAlignedBox3 viewSpaceBox;
725
726                if (mUseViewSpaceBox)
727                {
728                        viewSpaceBox = mSceneGraph->GetBox();
729
730                        // use a small box outside of the scene
731                        viewSpaceBox.Scale(Vector3(0.15f, 0.3f, 0.5f));
732                        //viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.5f, 0, 0));
733                        viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.3f, 0, 0));
734                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
735                }
736                else
737                {
738                        viewSpaceBox = mSceneGraph->GetBox();
739                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
740                }
741
742                bool loadVcGeometry;
743                Environment::GetSingleton()->GetBoolValue("ViewCells.loadGeometry", loadVcGeometry);
744
745                bool extrudeBaseTriangles;
746                Environment::GetSingleton()->GetBoolValue("ViewCells.useBaseTrianglesAsGeometry", extrudeBaseTriangles);
747
748                char vcGeomFilename[100];
749                Environment::GetSingleton()->GetStringValue("ViewCells.geometryFilename", vcGeomFilename);
750
751                // create view cells from specified geometry
752                if (loadVcGeometry)
753                {
754                        if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
755                        {
756                                if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
757                                {
758                                        cerr << "loading view cells geometry failed" << endl;
759                                }
760                        }
761                        else
762                        {
763                                cerr << "loading view cells geometry is not implemented for this manager" << endl;
764                        }
765                }
766        }
767
768        ////////
769        //-- evaluation of render cost heuristics
770
771        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
772
773        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
774        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
775        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
776
777        mRenderSimulator =
778                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
779
780        mViewCellsManager->SetRenderer(mRenderSimulator);
781       
782        mViewCellsManager->SetPreprocessor(this);
783
784        return true;
785}
786
787 
788bool Preprocessor::ConstructViewCells()
789{
790        // construct view cells using it's own set of samples
791        mViewCellsManager->Construct(this);
792
793        // visualizations and statistics
794        Debug << "finished view cells:" << endl;
795        mViewCellsManager->PrintStatistics(Debug);
796
797        return true;
798}
799
800
801ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
802{
803        ViewCellsTree *vcTree = new ViewCellsTree;
804
805        if (strcmp(name, "kdTree") == 0)
806        {
807                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
808        }
809        else if (strcmp(name, "bspTree") == 0)
810        {
811                Debug << "view cell type: Bsp" << endl;
812
813                mBspTree = new BspTree();
814                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
815        }
816        else if (strcmp(name, "vspBspTree") == 0)
817        {
818                Debug << "view cell type: VspBsp" << endl;
819
820                mVspBspTree = new VspBspTree();
821                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
822        }
823        else if (strcmp(name, "vspOspTree") == 0)
824        {
825                Debug << "view cell type: VspOsp" << endl;
826                char buf[100];         
827                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
828
829                mViewCellsManager = new VspOspViewCellsManager(vcTree, buf);
830        }
831        else if (strcmp(name, "sceneDependent") == 0) //TODO
832        {
833                Debug << "view cell type: Bsp" << endl;
834               
835                mBspTree = new BspTree();
836                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
837        }
838        else
839        {
840                cerr << "Wrong view cells type " << name << "!!!" << endl;
841                exit(1);
842        }
843
844        return mViewCellsManager;
845}
846
847
848// use ascii format to store rays
849#define USE_ASCII 0
850
851
852static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
853{
854        return obj1->mId < obj2->mId;
855}
856
857
858bool Preprocessor::LoadKdTree(const string filename)
859{
860        mKdTree = new KdTree();
861
862        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
863}
864
865
866bool Preprocessor::ExportKdTree(const string filename)
867{
868        return mKdTree->ExportBinTree(filename.c_str());
869}
870
871
872bool Preprocessor::LoadSamples(VssRayContainer &samples,
873                                                           ObjectContainer &objects) const
874{
875        std::stable_sort(objects.begin(), objects.end(), ilt);
876        char fileName[100];
877        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
878       
879    Vector3 origin, termination;
880        // HACK: needed only for lower_bound algorithm to find the
881        // intersected objects
882        MeshInstance sObj(NULL);
883        MeshInstance tObj(NULL);
884
885#if USE_ASCII
886        ifstream samplesIn(fileName);
887        if (!samplesIn.is_open())
888                return false;
889
890        string buf;
891        while (!(getline(samplesIn, buf)).eof())
892        {
893                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
894                           &origin.x, &origin.y, &origin.z,
895                           &termination.x, &termination.y, &termination.z,
896                           &(sObj.mId), &(tObj.mId));
897               
898                Intersectable *sourceObj = NULL;
899                Intersectable *termObj = NULL;
900               
901                if (sObj.mId >= 0)
902                {
903                        ObjectContainer::iterator oit =
904                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
905                        sourceObj = *oit;
906                }
907               
908                if (tObj.mId >= 0)
909                {
910                        ObjectContainer::iterator oit =
911                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
912                        termObj = *oit;
913                }
914
915                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
916        }
917#else
918        ifstream samplesIn(fileName, ios::binary);
919        if (!samplesIn.is_open())
920                return false;
921
922        while (1)
923        {
924                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
925                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
926                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
927                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
928               
929                 if (samplesIn.eof())
930                        break;
931
932                Intersectable *sourceObj = NULL;
933                Intersectable *termObj = NULL;
934               
935                if (sObj.mId >= 0)
936                {
937                        ObjectContainer::iterator oit =
938                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
939                        sourceObj = *oit;
940                }
941               
942                if (tObj.mId >= 0)
943                {
944                        ObjectContainer::iterator oit =
945                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
946                        termObj = *oit;
947                }
948
949                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
950        }
951#endif
952
953        samplesIn.close();
954
955        return true;
956}
957
958
959bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
960{
961        char fileName[100];
962        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
963       
964
965        VssRayContainer::const_iterator it, it_end = samples.end();
966       
967#if USE_ASCII
968        ofstream samplesOut(fileName);
969        if (!samplesOut.is_open())
970                return false;
971
972        for (it = samples.begin(); it != it_end; ++ it)
973        {
974                VssRay *ray = *it;
975                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
976                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
977
978                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
979                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
980                                   << sourceid << " " << termid << "\n";
981        }
982#else
983        ofstream samplesOut(fileName, ios::binary);
984        if (!samplesOut.is_open())
985                return false;
986
987        for (it = samples.begin(); it != it_end; ++ it)
988        {       
989                VssRay *ray = *it;
990                Vector3 origin(ray->GetOrigin());
991                Vector3 termination(ray->GetTermination());
992               
993                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
994                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
995
996                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
997                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
998                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
999                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
1000    }
1001#endif
1002        samplesOut.close();
1003
1004        return true;
1005}
1006
1007
1008int
1009Preprocessor::GenerateRays(const int number,
1010                                                   SamplingStrategy &strategy,
1011                                                   SimpleRayContainer &rays)
1012{
1013  return strategy.GenerateSamples(number, rays);
1014}
1015
1016
1017int
1018Preprocessor::GenerateRays(const int number,
1019                                                   const int sampleType,
1020                                                   SimpleRayContainer &rays)
1021{
1022        const int startSize = (int)rays.size();
1023        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
1024        int castRays = 0;
1025
1026        if (!strategy)
1027        {
1028                return 0;
1029        }
1030
1031#if 1
1032        castRays = strategy->GenerateSamples(number, rays);
1033#else
1034        GenerateRayBundle(rays, newRay, 16, 0);
1035        castRays += 16;
1036#endif
1037
1038        delete strategy;
1039        return castRays;
1040}
1041
1042
1043SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId)
1044{
1045        switch (strategyId)
1046        {
1047        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
1048                return new ObjectBasedDistribution(*this);
1049        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
1050                return new ObjectDirectionBasedDistribution(*this);
1051        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
1052                return new DirectionBasedDistribution(*this);
1053        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
1054                return new DirectionBoxBasedDistribution(*this);
1055        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
1056                return new SpatialBoxBasedDistribution(*this);
1057        case SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION:
1058                return new ReverseObjectBasedDistribution(*this);
1059        case SamplingStrategy::VIEWCELL_BORDER_BASED_DISTRIBUTION:
1060                return new ViewCellBorderBasedDistribution(*this);
1061        case SamplingStrategy::VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1062                return new ViewSpaceBorderBasedDistribution(*this);
1063        case SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1064                return new ReverseViewSpaceBorderBasedDistribution(*this);
1065        case SamplingStrategy::GLOBAL_LINES_DISTRIBUTION:
1066                return new GlobalLinesDistribution(*this);
1067               
1068                //case OBJECTS_INTERIOR_DISTRIBUTION:
1069                //      return new ObjectsInteriorDistribution(*this);
1070        default: // no valid strategy
1071                Debug << "warning: no valid sampling strategy" << endl;
1072                return NULL;
1073        }
1074
1075        return NULL; // should never come here
1076}
1077
1078
1079bool Preprocessor::InitRayCast(const string externKdTree,
1080                                                           const string internKdTree)
1081{
1082        // always try to load the kd tree
1083        cout << "loading kd tree file " << internKdTree << " ... " << endl;
1084
1085        if (!LoadKdTree(internKdTree))
1086        {
1087                cout << "error loading kd tree with filename "
1088                         << internKdTree << ", rebuilding it instead ... " << endl;
1089                // build new kd tree from scene geometry
1090                BuildKdTree();
1091
1092                // export kd tree?
1093                const long startTime = GetTime();
1094                cout << "exporting kd tree ... ";
1095
1096                if (!ExportKdTree(internKdTree))
1097                {
1098                        cout << " error exporting kd tree with filename "
1099                                 << internKdTree << endl;
1100                }
1101                else
1102                {
1103                        cout << "finished in "
1104                                 << TimeDiff(startTime, GetTime()) * 1e-3
1105                                 << " secs" << endl;
1106                }
1107        }
1108       
1109        KdTreeStatistics(cout);
1110        cout << mKdTree->GetBox() << endl;
1111
1112        if (0)
1113        {
1114                Exporter *exporter = Exporter::GetExporter("dummykd.x3d");
1115                       
1116                if (exporter)
1117                {
1118                        exporter->ExportKdTree(*mKdTree, true);
1119                        delete exporter;
1120                }
1121        }
1122
1123        int rayCastMethod;
1124        Environment::GetSingleton()->
1125                GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
1126
1127        if (rayCastMethod == 0)
1128        {
1129                cout << "ray cast method: internal" << endl;
1130                mRayCaster = new InternalRayCaster(*this, mKdTree);
1131        }
1132        else
1133        {
1134#ifdef GTP_INTERNAL
1135          cout << "ray cast method: intel" << endl;
1136          mRayCaster = new IntelRayCaster(*this, externKdTree);
1137#endif
1138        }
1139       
1140        return true;
1141}
1142
1143
1144void
1145Preprocessor::CastRays(
1146                                           SimpleRayContainer &rays,
1147                                           VssRayContainer &vssRays,
1148                                           const bool castDoubleRays,
1149                                           const bool pruneInvalidRays
1150                                           )
1151{
1152
1153
1154  const long t1 = GetTime();
1155
1156#if 0
1157  mRayCaster->SortRays(rays);
1158  cout<<"Rays sorted in "<<TimeDiff(t1, GetTime())<<" s."<<endl;
1159
1160  if (1) {
1161        VssRayContainer tmpRays;
1162        for (int i=0; i < 200; i++) {
1163          tmpRays.push_back(new VssRay(rays[i].mOrigin,
1164                                                                   rays[i].mOrigin + 100.0f*rays[i].mDirection,
1165                                                                   NULL,
1166                                                                   NULL
1167                                                                   )
1168                                                );
1169         
1170        }
1171        ExportRays("sorted_rays.x3d", tmpRays, 200);
1172  }
1173#endif
1174 
1175        SimpleRayContainer::const_iterator rit, rit_end = rays.end();
1176
1177        SimpleRayContainer rayBucket;
1178        int i = 0;
1179        for (rit = rays.begin(); rit != rit_end; ++ rit, ++ i)
1180        {
1181                SimpleRay ray = *rit;
1182#ifdef USE_CG
1183                // HACK: global lines must be treated special
1184                if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
1185                {
1186                        mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1187                        continue;
1188                }
1189#endif
1190                rayBucket.push_back(ray);
1191
1192                // 16 rays gathered => do ray casting
1193                if ((int)rayBucket.size() >= 16)
1194                {
1195                        mRayCaster->CastRays16(
1196                                                                   rayBucket,                           
1197                                                                   vssRays,
1198                                                                   mViewCellsManager->GetViewSpaceBox(),
1199                                                                   castDoubleRays,
1200                                                                   pruneInvalidRays);
1201
1202                        rayBucket.clear();
1203                }
1204       
1205                if ((int)rays.size() > 10000 && i % 10000 == 0)
1206                  cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
1207        }
1208   
1209        // cast rest of rays
1210        SimpleRayContainer::const_iterator sit, sit_end = rayBucket.end();
1211
1212        for (sit = rayBucket.begin(); sit != sit_end; ++ sit)
1213        {
1214                SimpleRay ray = *sit;
1215
1216#ifdef USE_CG
1217                // HACK: global lines must be treated special
1218                if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
1219                {
1220                        mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1221                        continue;
1222                }
1223#endif
1224                mRayCaster->CastRay(
1225                                                        ray,
1226                                                        vssRays,
1227                                                        mViewCellsManager->GetViewSpaceBox(),
1228                                                        castDoubleRays,
1229                                                        pruneInvalidRays);
1230               
1231        }
1232
1233        if ((int)rays.size() > 10000)
1234        {
1235                cout << endl;
1236        long t2 = GetTime();
1237
1238#if SHOW_RAYCAST_TIMING
1239                if (castDoubleRays)
1240                        cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1241                else
1242                        cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1243#endif
1244        }
1245}
1246
1247
1248bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
1249                                                                         const SimpleRay &mainRay,
1250                                                                         const int number,
1251                                                                         const int pertubType) const
1252{
1253        rayBundle.push_back(mainRay);
1254
1255        const float pertubOrigin = 0.0f;
1256        const float pertubDir = 0.2f;
1257
1258        for (int i = 0; i < number - 1; ++ i)
1259        {
1260                Vector3 pertub;
1261
1262                pertub.x = RandomValue(0.0f, pertubDir);
1263                pertub.y = RandomValue(0.0f, pertubDir);
1264                pertub.z = RandomValue(0.0f, pertubDir);
1265
1266                const Vector3 newDir = mainRay.mDirection + pertub;
1267                //const Vector3 newDir = mainRay.mDirection;
1268
1269                pertub.x = RandomValue(0.0f, pertubOrigin);
1270                pertub.y = RandomValue(0.0f, pertubOrigin);
1271                pertub.z = RandomValue(0.0f, pertubOrigin);
1272
1273                const Vector3 newOrigin = mainRay.mOrigin + pertub;
1274                //const Vector3 newOrigin = mainRay.mOrigin;
1275
1276                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0, 1.0f));
1277        }
1278
1279        return true;
1280}
1281
1282
1283void Preprocessor::SetupRay(Ray &ray,
1284                                                        const Vector3 &point,
1285                                                        const Vector3 &direction) const
1286{
1287        ray.Clear();
1288        // do not store anything else then intersections at the ray
1289        ray.Init(point, direction, Ray::LOCAL_RAY);     
1290}
1291
1292
1293void Preprocessor::EvalViewCellHistogram()
1294{
1295        char filename[256];
1296        Environment::GetSingleton()->GetStringValue("Preprocessor.histogram.file", filename);
1297 
1298        // mViewCellsManager->EvalViewCellHistogram(filename, 1000000);
1299        mViewCellsManager->EvalViewCellHistogramForPvsSize(filename, 1000000);
1300}
1301
1302
1303bool
1304Preprocessor::ExportRays(const char *filename,
1305                                                 const VssRayContainer &vssRays,
1306                                                 const int number
1307                                                 )
1308{
1309  cout<<"Exporting vss rays..."<<endl<<flush;
1310 
1311  Exporter *exporter = NULL;
1312  exporter = Exporter::GetExporter(filename);
1313
1314  if (0) {
1315        exporter->SetWireframe();
1316        exporter->ExportKdTree(*mKdTree);
1317  }
1318 
1319  exporter->SetFilled();
1320  // $$JB temporarily do not export the scene
1321  if (0)
1322        exporter->ExportScene(mSceneGraph->GetRoot());
1323
1324  exporter->SetWireframe();
1325
1326  if (1) {
1327        exporter->SetForcedMaterial(RgbColor(1,0,1));
1328        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1329        exporter->ResetForcedMaterial();
1330  }
1331 
1332  VssRayContainer rays;
1333  vssRays.SelectRays(number, rays);
1334  exporter->ExportRays(rays, RgbColor(1, 0, 0));
1335  delete exporter;
1336  cout<<"done."<<endl<<flush;
1337
1338  return true;
1339}
1340
1341void
1342Preprocessor::ComputeRenderError()
1343{
1344  // compute rendering error
1345       
1346  if (renderer && renderer->mPvsStatFrames) {
1347        //      emit EvalPvsStat();
1348        //      QMutex mutex;
1349        //      mutex.lock();
1350        //      renderer->mRenderingFinished.wait(&mutex);
1351        //      mutex.unlock();
1352       
1353        renderer->EvalPvsStat();
1354
1355        mStats <<
1356          "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
1357          "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
1358          "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
1359          "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
1360  }
1361}
1362
1363
1364Intersectable *Preprocessor::GetObjectById(const int id)
1365{
1366#if 1
1367        // create a dummy mesh instance to be able to use stl
1368        MeshInstance object(NULL);
1369        object.SetId(id);
1370
1371        ObjectContainer::const_iterator oit =
1372                lower_bound(mObjects.begin(), mObjects.end(), &object, ilt);
1373                               
1374        // objects sorted by id
1375        if ((oit != mObjects.end()) && ((*oit)->GetId() == object.GetId()))
1376        {
1377                return (*oit);
1378        }
1379        else
1380        {
1381                return NULL;
1382        }
1383#else
1384        return mObjects[id - 1];
1385#endif
1386}
1387
1388
1389void Preprocessor::PrepareHwGlobalLines()
1390{
1391        int texHeight, texWidth;
1392        float eps;
1393        int maxDepth;
1394        bool sampleReverse;
1395
1396        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texHeight", texHeight);
1397        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texWidth", texWidth);
1398        Environment::GetSingleton()->GetFloatValue("Preprocessor.HwGlobalLines.stepSize", eps);
1399        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.maxDepth", maxDepth);
1400        Environment::GetSingleton()->GetBoolValue("Preprocessor.HwGlobalLines.sampleReverse", sampleReverse);
1401
1402        Debug << "****** hw global line options *******" << endl;
1403        Debug << "texWidth: " << texWidth << endl;
1404        Debug << "texHeight: " << texHeight << endl;
1405        Debug << "sampleReverse: " << sampleReverse << endl;
1406        Debug << "max depth: " << maxDepth << endl;
1407        Debug << "step size: " << eps << endl;
1408        Debug << endl;
1409
1410#ifdef USE_CG
1411        globalLinesRenderer = mGlobalLinesRenderer =
1412                new GlobalLinesRenderer(this,
1413                                                                texHeight,
1414                                                                texWidth,
1415                                                                eps,
1416                                                                maxDepth,
1417                                                                sampleReverse);
1418
1419        mGlobalLinesRenderer->InitGl();
1420
1421#endif
1422}
1423
1424}
Note: See TracBrowser for help on using the repository browser.