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

Revision 2115, 42.5 KB checked in by mattausch, 17 years ago (diff)

changed pvs loading: loading objects in a first pass

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