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

Revision 2117, 42.7 KB checked in by mattausch, 17 years ago (diff)

implemented bit pvs (warnin: only worjs for preprocessing)

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