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

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