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

Revision 2610, 42.9 KB checked in by bittner, 16 years ago (diff)

pixel error computation revival

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