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

Revision 2124, 42.7 KB checked in by mattausch, 17 years ago (diff)
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
482        bool result = false;
483        bool isObj = false;
484
485        // root for different files
486        mSceneGraph->SetRoot(new SceneGraphNode());
487
488        // intel ray caster can only trace triangles
489        int rayCastMethod;
490        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
491        vector<FaceParentInfo> *fi =
492          ((rayCastMethod == RayCaster::INTEL_RAYCASTER) && mLoadMeshes) ?
493          &mFaceParents : NULL;
494       
495        if (files == 1)
496          {
497                if (strstr(filename.c_str(), ".x3d"))
498                  {
499                        parser = new X3dParser;
500                       
501                        result = parser->ParseFile(filename,
502                                                                           mSceneGraph->GetRoot(),
503                                                                           mLoadMeshes,
504                                                                           fi);
505                        delete parser;
506                }
507                else if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
508                {
509                        parser = new PlyParser;
510
511                        result = parser->ParseFile(filename,
512                                                                           mSceneGraph->GetRoot(),
513                                                                           mLoadMeshes,
514                                                                           fi);
515                        delete parser;
516                }
517                else if (strstr(filename.c_str(), ".obj"))
518                {
519                        isObj = true;
520
521                        // hack: load binary dump
522                        const string bnFile = ReplaceSuffix(filename, ".obj", ".bn");
523                       
524                        if (!mLoadMeshes)
525                        {
526                                result = LoadBinaryObj(bnFile, mSceneGraph->GetRoot(), fi);
527                        }
528
529                        // parse obj
530            if (!result)
531                        {
532                                cout << "no binary dump available or loading full meshes, parsing file" << endl;
533                                parser = new ObjParser;
534               
535                                result = parser->ParseFile(filename,
536                                                                                   mSceneGraph->GetRoot(),
537                                                                                   mLoadMeshes,
538                                                                                   fi);
539
540                                cout << "loaded " << (int)mSceneGraph->GetRoot()->mGeometry.size() << " entities" << endl;
541
542                                // only works for triangles
543                                if (result && !mLoadMeshes)
544                                {
545                                        cout << "exporting binary obj to " << bnFile << "... " << endl;
546
547                                        ExportBinaryObj(bnFile, mSceneGraph->GetRoot());
548                               
549                                        cout << "finished" << endl;
550                                }
551
552                                delete parser;
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                cout << "loading objects from " << buf << endl;
744
745                // load objects which will be used as pvs entries
746                ObjectContainer pvsObjects;
747                if (0) LoadObjects(buf, pvsObjects, mObjects);
748
749                const bool finalizeViewCells = true;
750                cout << "loading view cells from " << buf << endl;
751
752                mViewCellsManager = ViewCellsManager::LoadViewCells(buf,
753                                                                                                                        pvsObjects,
754                                                                                                                        mObjects,
755                                                                                                                        finalizeViewCells,
756                                                                                                                        NULL);
757
758                cout << "view cells loaded." << endl<<flush;
759
760                if (!mViewCellsManager)
761                {
762                        cerr << "no view cells manager could be loaded" << endl;
763                        return false;
764                }
765        }
766        else
767        {
768                // parse type of view cell container
769                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
770                mViewCellsManager = CreateViewCellsManager(buf);
771
772                // default view space is the extent of the scene
773                AxisAlignedBox3 viewSpaceBox;
774
775                if (mUseViewSpaceBox)
776                {
777                        viewSpaceBox = mSceneGraph->GetBox();
778
779                        // use a small box outside of the scene
780                        viewSpaceBox.Scale(Vector3(0.15f, 0.3f, 0.5f));
781                        //viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.5f, 0, 0));
782                        viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.3f, 0, 0));
783                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
784                }
785                else
786                {
787                        viewSpaceBox = mSceneGraph->GetBox();
788                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
789                }
790
791                bool loadVcGeometry;
792                Environment::GetSingleton()->GetBoolValue("ViewCells.loadGeometry", loadVcGeometry);
793
794                bool extrudeBaseTriangles;
795                Environment::GetSingleton()->GetBoolValue("ViewCells.useBaseTrianglesAsGeometry", extrudeBaseTriangles);
796
797                char vcGeomFilename[100];
798                Environment::GetSingleton()->GetStringValue("ViewCells.geometryFilename", vcGeomFilename);
799
800                // create view cells from specified geometry
801                if (loadVcGeometry)
802                {
803                        if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
804                        {
805                                if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
806                                {
807                                        cerr << "loading view cells geometry failed" << endl;
808                                }
809                        }
810                        else
811                        {
812                                cerr << "loading view cells geometry is not implemented for this manager" << endl;
813                        }
814                }
815        }
816
817        ////////
818        //-- evaluation of render cost heuristics
819
820        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
821
822        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
823        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
824        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
825
826        mRenderSimulator =
827                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
828
829        mViewCellsManager->SetRenderer(mRenderSimulator);
830       
831        mViewCellsManager->SetPreprocessor(this);
832
833        return true;
834}
835
836 
837bool Preprocessor::ConstructViewCells()
838{
839        // construct view cells using it's own set of samples
840        mViewCellsManager->Construct(this);
841
842        // visualizations and statistics
843        Debug << "finished view cells:" << endl;
844        mViewCellsManager->PrintStatistics(Debug);
845
846        return true;
847}
848
849
850ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
851{
852        ViewCellsTree *vcTree = new ViewCellsTree;
853
854        if (strcmp(name, "kdTree") == 0)
855        {
856                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
857        }
858        else if (strcmp(name, "bspTree") == 0)
859        {
860                Debug << "view cell type: Bsp" << endl;
861
862                mBspTree = new BspTree();
863                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
864        }
865        else if (strcmp(name, "vspBspTree") == 0)
866        {
867                Debug << "view cell type: VspBsp" << endl;
868
869                mVspBspTree = new VspBspTree();
870                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
871        }
872        else if (strcmp(name, "vspOspTree") == 0)
873        {
874                Debug << "view cell type: VspOsp" << endl;
875                char buf[100];         
876                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
877
878                mViewCellsManager = new VspOspViewCellsManager(vcTree, buf);
879        }
880        else if (strcmp(name, "sceneDependent") == 0) //TODO
881        {
882                Debug << "view cell type: Bsp" << endl;
883               
884                mBspTree = new BspTree();
885                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
886        }
887        else
888        {
889                cerr << "Wrong view cells type " << name << "!!!" << endl;
890                exit(1);
891        }
892
893        return mViewCellsManager;
894}
895
896
897// use ascii format to store rays
898#define USE_ASCII 0
899
900
901static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
902{
903        return obj1->mId < obj2->mId;
904}
905
906
907bool Preprocessor::LoadKdTree(const string filename)
908{
909        mKdTree = new KdTree();
910
911        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
912}
913
914
915bool Preprocessor::ExportKdTree(const string filename)
916{
917        return mKdTree->ExportBinTree(filename.c_str());
918}
919
920
921bool Preprocessor::LoadSamples(VssRayContainer &samples,
922                                                           ObjectContainer &objects) const
923{
924        std::stable_sort(objects.begin(), objects.end(), ilt);
925        char fileName[100];
926        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
927       
928    Vector3 origin, termination;
929        // HACK: needed only for lower_bound algorithm to find the
930        // intersected objects
931        MeshInstance sObj(NULL);
932        MeshInstance tObj(NULL);
933
934#if USE_ASCII
935        ifstream samplesIn(fileName);
936        if (!samplesIn.is_open())
937                return false;
938
939        string buf;
940        while (!(getline(samplesIn, buf)).eof())
941        {
942                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
943                           &origin.x, &origin.y, &origin.z,
944                           &termination.x, &termination.y, &termination.z,
945                           &(sObj.mId), &(tObj.mId));
946               
947                Intersectable *sourceObj = NULL;
948                Intersectable *termObj = NULL;
949               
950                if (sObj.mId >= 0)
951                {
952                        ObjectContainer::iterator oit =
953                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
954                        sourceObj = *oit;
955                }
956               
957                if (tObj.mId >= 0)
958                {
959                        ObjectContainer::iterator oit =
960                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
961                        termObj = *oit;
962                }
963
964                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
965        }
966#else
967        ifstream samplesIn(fileName, ios::binary);
968        if (!samplesIn.is_open())
969                return false;
970
971        while (1)
972        {
973                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
974                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
975                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
976                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
977               
978                 if (samplesIn.eof())
979                        break;
980
981                Intersectable *sourceObj = NULL;
982                Intersectable *termObj = NULL;
983               
984                if (sObj.mId >= 0)
985                {
986                        ObjectContainer::iterator oit =
987                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
988                        sourceObj = *oit;
989                }
990               
991                if (tObj.mId >= 0)
992                {
993                        ObjectContainer::iterator oit =
994                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
995                        termObj = *oit;
996                }
997
998                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
999        }
1000#endif
1001
1002        samplesIn.close();
1003
1004        return true;
1005}
1006
1007
1008bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
1009{
1010        char fileName[100];
1011        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
1012       
1013
1014        VssRayContainer::const_iterator it, it_end = samples.end();
1015       
1016#if USE_ASCII
1017        ofstream samplesOut(fileName);
1018        if (!samplesOut.is_open())
1019                return false;
1020
1021        for (it = samples.begin(); it != it_end; ++ it)
1022        {
1023                VssRay *ray = *it;
1024                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
1025                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
1026
1027                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
1028                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
1029                                   << sourceid << " " << termid << "\n";
1030        }
1031#else
1032        ofstream samplesOut(fileName, ios::binary);
1033        if (!samplesOut.is_open())
1034                return false;
1035
1036        for (it = samples.begin(); it != it_end; ++ it)
1037        {       
1038                VssRay *ray = *it;
1039                Vector3 origin(ray->GetOrigin());
1040                Vector3 termination(ray->GetTermination());
1041               
1042                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
1043                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
1044
1045                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
1046                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
1047                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
1048                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
1049    }
1050#endif
1051        samplesOut.close();
1052
1053        return true;
1054}
1055
1056
1057int
1058Preprocessor::GenerateRays(const int number,
1059                                                   SamplingStrategy &strategy,
1060                                                   SimpleRayContainer &rays)
1061{
1062  return strategy.GenerateSamples(number, rays);
1063}
1064
1065
1066int
1067Preprocessor::GenerateRays(const int number,
1068                                                   const int sampleType,
1069                                                   SimpleRayContainer &rays)
1070{
1071        const int startSize = (int)rays.size();
1072        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
1073        int castRays = 0;
1074
1075        if (!strategy)
1076        {
1077                return 0;
1078        }
1079
1080#if 1
1081        castRays = strategy->GenerateSamples(number, rays);
1082#else
1083        GenerateRayBundle(rays, newRay, 16, 0);
1084        castRays += 16;
1085#endif
1086
1087        delete strategy;
1088        return castRays;
1089}
1090
1091
1092SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId)
1093{
1094        switch (strategyId)
1095        {
1096        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
1097                return new ObjectBasedDistribution(*this);
1098        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
1099                return new ObjectDirectionBasedDistribution(*this);
1100        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
1101                return new DirectionBasedDistribution(*this);
1102        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
1103                return new DirectionBoxBasedDistribution(*this);
1104        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
1105                return new SpatialBoxBasedDistribution(*this);
1106        case SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION:
1107                return new ReverseObjectBasedDistribution(*this);
1108        case SamplingStrategy::VIEWCELL_BORDER_BASED_DISTRIBUTION:
1109                return new ViewCellBorderBasedDistribution(*this);
1110        case SamplingStrategy::VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1111                return new ViewSpaceBorderBasedDistribution(*this);
1112        case SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1113                return new ReverseViewSpaceBorderBasedDistribution(*this);
1114        case SamplingStrategy::GLOBAL_LINES_DISTRIBUTION:
1115                return new GlobalLinesDistribution(*this);
1116               
1117                //case OBJECTS_INTERIOR_DISTRIBUTION:
1118                //      return new ObjectsInteriorDistribution(*this);
1119        default: // no valid strategy
1120                Debug << "warning: no valid sampling strategy" << endl;
1121                return NULL;
1122        }
1123
1124        return NULL; // should never come here
1125}
1126
1127
1128bool Preprocessor::LoadInternKdTree( const string internKdTree)
1129{
1130  bool mUseKdTree = true;
1131 
1132  if (!mUseKdTree) {
1133        // create just a dummy KdTree
1134        mKdTree = new KdTree;
1135        return true;
1136  }
1137 
1138  // always try to load the kd tree
1139  cout << "loading kd tree file " << internKdTree << " ... " << endl;
1140 
1141  if (!LoadKdTree(internKdTree)) {
1142        cout << "error loading kd tree with filename "
1143                 << internKdTree << ", rebuilding it instead ... " << endl;
1144        // build new kd tree from scene geometry
1145        BuildKdTree();
1146       
1147        // export kd tree?
1148        const long startTime = GetTime();
1149        cout << "exporting kd tree ... ";
1150       
1151        if (!ExportKdTree(internKdTree))
1152          {
1153                cout << " error exporting kd tree with filename "
1154                         << internKdTree << endl;
1155          }
1156        else
1157          {
1158                cout << "finished in "
1159                         << TimeDiff(startTime, GetTime()) * 1e-3
1160                         << " secs" << endl;
1161          }
1162  }
1163 
1164  KdTreeStatistics(cout);
1165  cout << mKdTree->GetBox() << endl;
1166 
1167  return true;
1168}
1169
1170
1171bool Preprocessor::InitRayCast(const string externKdTree,
1172                                                           const string internKdTree)
1173{
1174        // always try to load the kd tree
1175/*      cout << "loading kd tree file " << internKdTree << " ... " << endl;
1176
1177        if (!LoadKdTree(internKdTree))
1178        {
1179                cout << "error loading kd tree with filename "
1180                         << internKdTree << ", rebuilding it instead ... " << endl;
1181                // build new kd tree from scene geometry
1182                BuildKdTree();
1183
1184                // export kd tree?
1185                const long startTime = GetTime();
1186                cout << "exporting kd tree ... ";
1187
1188                if (!ExportKdTree(internKdTree))
1189                {
1190                        cout << " error exporting kd tree with filename "
1191                                 << internKdTree << endl;
1192                }
1193                else
1194                {
1195                        cout << "finished in "
1196                                 << TimeDiff(startTime, GetTime()) * 1e-3
1197                                 << " secs" << endl;
1198                }
1199        }
1200       
1201        KdTreeStatistics(cout);
1202        cout << mKdTree->GetBox() << endl;
1203*/
1204        int rayCastMethod;
1205        Environment::GetSingleton()->
1206                GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
1207
1208        if (rayCastMethod == 0)
1209        {
1210                cout << "ray cast method: internal" << endl;
1211                mRayCaster = new InternalRayCaster(*this);
1212        }
1213        else
1214        {
1215#ifdef GTP_INTERNAL
1216          cout << "ray cast method: intel" << endl;
1217          mRayCaster = new IntelRayCaster(*this, externKdTree);
1218#endif
1219        }
1220       
1221        /////
1222        //-- reserve constant block of rays
1223       
1224        // hack: If we dont't use view cells loading, there must be at least as much rays
1225        // as are needed for the view cells construction
1226        bool loadViewCells;
1227        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", loadViewCells);
1228
1229        int reserveRays;
1230
1231        if (!loadViewCells)
1232        {
1233                cout << "setting ray pool size to view cell construction ize" << endl;
1234
1235                char buf[100];
1236                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);     
1237               
1238                if (strcmp(buf, "vspBspTree") == 0)
1239                {
1240                        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", reserveRays);
1241                        reserveRays *= 2;
1242                }
1243                else if (strcmp(buf, "vspOspTree") == 0)
1244                {
1245                        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", reserveRays);
1246                        reserveRays *= 2;                       
1247                }
1248        }
1249        else
1250        {
1251                cout << "setting ray pool size to samples per pass" << endl;
1252       
1253                reserveRays = mSamplesPerPass * 2;
1254        }
1255
1256        cout << "======================" << endl;
1257        cout << "reserving " << reserveRays << " rays " << endl;
1258        mRayCaster->ReserveVssRayPool(reserveRays);
1259       
1260        return true;
1261}
1262
1263
1264void
1265Preprocessor::CastRays(
1266                                           SimpleRayContainer &rays,
1267                                           VssRayContainer &vssRays,
1268                                           const bool castDoubleRays,
1269                                           const bool pruneInvalidRays
1270                                           )
1271{
1272
1273        const long t1 = GetTime();
1274       
1275        if ((int)rays.size() > 10000) {
1276       
1277                mRayCaster->SortRays(rays);
1278                cout<<"Rays sorted in "<<TimeDiff(t1, GetTime())<<" ms."<<endl;
1279
1280                if (0) {
1281                        VssRayContainer tmpRays;
1282                        int m = 890000;
1283
1284                        for (int i=m; i < m+20; i++) {
1285                                tmpRays.push_back(new VssRay(rays[i].mOrigin,
1286                                        rays[i].mOrigin + 100.0f*rays[i].mDirection,
1287                                        NULL,
1288                                        NULL
1289                                        )
1290                                        );
1291
1292                        }
1293                        ExportRays("sorted_rays.x3d", tmpRays, 200);
1294                }
1295        }
1296
1297
1298        if (mUseHwGlobalLines)
1299          CastRaysWithHwGlobalLines(
1300                                                                rays,
1301                                                                vssRays,
1302                                                                castDoubleRays,
1303                                                                pruneInvalidRays
1304                                                                );
1305        else
1306          mRayCaster->CastRays(
1307                                                 rays,                         
1308                                                 vssRays,
1309                                                 mViewCellsManager->GetViewSpaceBox(),
1310                                                 castDoubleRays,
1311                                                 pruneInvalidRays);
1312 
1313        if ((int)rays.size() > 10000)
1314        {
1315                cout << endl;
1316        long t2 = GetTime();
1317
1318#if SHOW_RAYCAST_TIMING
1319                if (castDoubleRays)
1320                        cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1321                else
1322                        cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1323#endif
1324        }
1325
1326        DeterminePvsObjects(vssRays);
1327}
1328
1329
1330 
1331void
1332Preprocessor::CastRaysWithHwGlobalLines(
1333                                                                                SimpleRayContainer &rays,
1334                                                                          VssRayContainer &vssRays,
1335                                                                          const bool castDoubleRays,
1336                                                                          const bool pruneInvalidRays
1337                                                                          )
1338{
1339  SimpleRayContainer::const_iterator rit, rit_end = rays.end();
1340  SimpleRayContainer rayBucket;
1341  int i = 0;
1342  for (rit = rays.begin(); rit != rit_end; ++ rit, ++ i)
1343        {
1344          SimpleRay ray = *rit;
1345#ifdef USE_CG
1346                // HACK: global lines must be treated special
1347          if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
1348                {
1349                  mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1350                  continue;
1351                }
1352#endif
1353          rayBucket.push_back(ray);
1354         
1355          // 16 rays gathered => do ray casting
1356          if ((int)rayBucket.size() >= 16)
1357                {
1358                  mRayCaster->CastRays16(
1359                                                                 rayBucket,                             
1360                                                                 vssRays,
1361                                                                 mViewCellsManager->GetViewSpaceBox(),
1362                                                                 castDoubleRays,
1363                                                                 pruneInvalidRays);
1364                 
1365                  rayBucket.clear();
1366                }
1367       
1368                if ((int)rays.size() > 100000 && i % 100000 == 0)
1369                        cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
1370        }
1371   
1372        // cast rest of rays
1373        SimpleRayContainer::const_iterator sit, sit_end = rayBucket.end();
1374
1375        for (sit = rayBucket.begin(); sit != sit_end; ++ sit)
1376        {
1377                SimpleRay ray = *sit;
1378
1379#ifdef USE_CG
1380                // HACK: global lines must be treated special
1381                if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
1382                {
1383                        mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1384                        continue;
1385                }
1386#endif
1387                mRayCaster->CastRay(
1388                                                        ray,
1389                                                        vssRays,
1390                                                        mViewCellsManager->GetViewSpaceBox(),
1391                                                        castDoubleRays,
1392                                                        pruneInvalidRays);
1393               
1394        }
1395
1396}
1397
1398
1399bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
1400                                                                         const SimpleRay &mainRay,
1401                                                                         const int number,
1402                                                                         const int pertubType) const
1403{
1404        rayBundle.push_back(mainRay);
1405
1406        const float pertubOrigin = 0.0f;
1407        const float pertubDir = 0.2f;
1408
1409        for (int i = 0; i < number - 1; ++ i)
1410        {
1411                Vector3 pertub;
1412
1413                pertub.x = RandomValue(0.0f, pertubDir);
1414                pertub.y = RandomValue(0.0f, pertubDir);
1415                pertub.z = RandomValue(0.0f, pertubDir);
1416
1417                const Vector3 newDir = mainRay.mDirection + pertub;
1418                //const Vector3 newDir = mainRay.mDirection;
1419
1420                pertub.x = RandomValue(0.0f, pertubOrigin);
1421                pertub.y = RandomValue(0.0f, pertubOrigin);
1422                pertub.z = RandomValue(0.0f, pertubOrigin);
1423
1424                const Vector3 newOrigin = mainRay.mOrigin + pertub;
1425                //const Vector3 newOrigin = mainRay.mOrigin;
1426
1427                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0, 1.0f));
1428        }
1429
1430        return true;
1431}
1432
1433
1434void Preprocessor::SetupRay(Ray &ray,
1435                                                        const Vector3 &point,
1436                                                        const Vector3 &direction) const
1437{
1438        ray.Clear();
1439        // do not store anything else then intersections at the ray
1440        ray.Init(point, direction, Ray::LOCAL_RAY);     
1441}
1442
1443
1444void Preprocessor::EvalViewCellHistogram()
1445{
1446        char filename[256];
1447        Environment::GetSingleton()->GetStringValue("Preprocessor.histogram.file", filename);
1448 
1449        // mViewCellsManager->EvalViewCellHistogram(filename, 1000000);
1450        mViewCellsManager->EvalViewCellHistogramForPvsSize(filename, 1000000);
1451}
1452
1453
1454bool
1455Preprocessor::ExportRays(const char *filename,
1456                                                 const VssRayContainer &vssRays,
1457                                                 const int number,
1458                                                 const bool exportScene
1459                                                 )
1460{
1461  cout<<"Exporting vss rays..."<<endl<<flush;
1462 
1463  Exporter *exporter = NULL;
1464  exporter = Exporter::GetExporter(filename);
1465
1466  if (0) {
1467        exporter->SetWireframe();
1468        exporter->ExportKdTree(*mKdTree);
1469  }
1470 
1471  exporter->SetFilled();
1472  // $$JB temporarily do not export the scene
1473  if (exportScene)
1474        exporter->ExportScene(mSceneGraph->GetRoot());
1475
1476  exporter->SetWireframe();
1477
1478  if (1) {
1479        exporter->SetForcedMaterial(RgbColor(1,0,1));
1480        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1481        exporter->ResetForcedMaterial();
1482  }
1483 
1484  VssRayContainer rays;
1485  vssRays.SelectRays(number, rays);
1486  exporter->ExportRays(rays, RgbColor(1, 0, 0));
1487  delete exporter;
1488  cout<<"done."<<endl<<flush;
1489
1490  return true;
1491}
1492
1493bool
1494Preprocessor::ExportRayAnimation(const char *filename,
1495                                                                 const vector<VssRayContainer> &vssRays
1496                                                                 )
1497{
1498  cout<<"Exporting vss rays..."<<endl<<flush;
1499       
1500  Exporter *exporter = NULL;
1501  exporter = Exporter::GetExporter(filename);
1502  if (0) {
1503        exporter->SetWireframe();
1504        exporter->ExportKdTree(*mKdTree);
1505  }
1506  exporter->SetFilled();
1507  // $$JB temporarily do not export the scene
1508  if (0)
1509        exporter->ExportScene(mSceneGraph->GetRoot());
1510  exporter->SetWireframe();
1511
1512  if (1) {
1513        exporter->SetForcedMaterial(RgbColor(1,0,1));
1514        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1515        exporter->ResetForcedMaterial();
1516  }
1517 
1518  exporter->ExportRaySets(vssRays, RgbColor(1, 0, 0));
1519       
1520  delete exporter;
1521
1522  cout<<"done."<<endl<<flush;
1523
1524  return true;
1525}
1526
1527void
1528Preprocessor::ComputeRenderError()
1529{
1530  // compute rendering error
1531       
1532  if (renderer && renderer->mPvsStatFrames) {
1533        //      emit EvalPvsStat();
1534        //      QMutex mutex;
1535        //      mutex.lock();
1536        //      renderer->mRenderingFinished.wait(&mutex);
1537        //      mutex.unlock();
1538
1539        if (mViewCellsManager->GetViewCellPoints()->size()) {
1540         
1541          vector<ViewCellPoints *> *vcPoints = mViewCellsManager->GetViewCellPoints();
1542         
1543          vector<ViewCellPoints *>::const_iterator
1544                vit = vcPoints->begin(),
1545                vit_end = vcPoints->end();
1546
1547          SimpleRayContainer viewPoints;
1548         
1549          for (; vit != vit_end; ++ vit) {
1550                ViewCellPoints *vp = *vit;
1551
1552                SimpleRayContainer::const_iterator rit = vp->second.begin(), rit_end = vp->second.end();
1553                for (; rit!=rit_end; ++rit)
1554                  viewPoints.push_back(*rit);
1555          }
1556
1557          if (viewPoints.size() != renderer->mPvsErrorBuffer.size()) {
1558                renderer->mPvsErrorBuffer.resize(viewPoints.size());
1559                renderer->ClearErrorBuffer();
1560          }
1561
1562          renderer->EvalPvsStat(viewPoints);
1563        } else
1564          renderer->EvalPvsStat();
1565
1566        mStats <<
1567          "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
1568          "#AvgPixelError\n" <<renderer->GetAvgPixelError()<<endl<<
1569          "#MaxPixelError\n" <<renderer->GetMaxPixelError()<<endl<<
1570          "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
1571          "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
1572          "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
1573  }
1574}
1575
1576
1577Intersectable *Preprocessor::GetObjectById(const int id)
1578{
1579#if 1
1580        // create a dummy mesh instance to be able to use stl
1581        MeshInstance object(NULL);
1582        object.SetId(id);
1583
1584        ObjectContainer::const_iterator oit =
1585                lower_bound(mObjects.begin(), mObjects.end(), &object, ilt);
1586                               
1587        // objects sorted by id
1588        if ((oit != mObjects.end()) && ((*oit)->GetId() == object.GetId()))
1589        {
1590                return (*oit);
1591        }
1592        else
1593        {
1594                return NULL;
1595        }
1596#else
1597        return mObjects[id - 1];
1598#endif
1599}
1600
1601
1602void Preprocessor::PrepareHwGlobalLines()
1603{
1604        int texHeight, texWidth;
1605        float eps;
1606        int maxDepth;
1607        bool sampleReverse;
1608
1609        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texHeight", texHeight);
1610        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texWidth", texWidth);
1611        Environment::GetSingleton()->GetFloatValue("Preprocessor.HwGlobalLines.stepSize", eps);
1612        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.maxDepth", maxDepth);
1613        Environment::GetSingleton()->GetBoolValue("Preprocessor.HwGlobalLines.sampleReverse", sampleReverse);
1614
1615        Debug << "****** hw global line options *******" << endl;
1616        Debug << "texWidth: " << texWidth << endl;
1617        Debug << "texHeight: " << texHeight << endl;
1618        Debug << "sampleReverse: " << sampleReverse << endl;
1619        Debug << "max depth: " << maxDepth << endl;
1620        Debug << "step size: " << eps << endl;
1621        Debug << endl;
1622
1623#ifdef USE_CG
1624        globalLinesRenderer = mGlobalLinesRenderer =
1625                new GlobalLinesRenderer(this,
1626                                                                texHeight,
1627                                                                texWidth,
1628                                                                eps,
1629                                                                maxDepth,
1630                                                                sampleReverse);
1631
1632        mGlobalLinesRenderer->InitGl();
1633
1634#endif
1635}
1636
1637
1638void Preprocessor::DeterminePvsObjects(VssRayContainer &rays)
1639{
1640        mViewCellsManager->DeterminePvsObjects(rays, false);
1641}
1642
1643
1644bool Preprocessor::LoadObjects(const string &filename,
1645                                                           ObjectContainer &pvsObjects,
1646                                                           const ObjectContainer &preprocessorObjects)
1647{
1648        ObjectsParser parser;
1649
1650        const bool success = parser.ParseObjects(filename,
1651                                                                                         pvsObjects,
1652                                                                                         preprocessorObjects);
1653
1654        if (!success)
1655        {
1656                Debug << "Error: loading objects failed!" << endl;
1657        }
1658
1659        // hack: no bvh object could be found => take preprocessor objects
1660        if (pvsObjects.empty())
1661        {
1662                Debug << "here81 no objects" << endl;
1663                pvsObjects = preprocessorObjects;
1664        }
1665
1666        return success;
1667}
1668
1669
1670}
Note: See TracBrowser for help on using the repository browser.