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

Revision 2539, 40.1 KB checked in by mattausch, 17 years ago (diff)

fixed obj loading error

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