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

Revision 2592, 41.2 KB checked in by bittner, 16 years ago (diff)

havran ray caster update

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