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

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