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

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