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

Revision 2046, 39.3 KB checked in by bittner, 17 years ago (diff)

time termination

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