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

Revision 2575, 40.8 KB checked in by bittner, 17 years ago (diff)

big merge: preparation for havran ray caster, check if everything works

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