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

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