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

Revision 1984, 36.1 KB checked in by bittner, 17 years ago (diff)

ray sort updates

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