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

Revision 2698, 44.6 KB checked in by bittner, 16 years ago (diff)

merge on nemo

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