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

Revision 2610, 42.9 KB checked in by bittner, 17 years ago (diff)

pixel error computation revival

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