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

Revision 2592, 41.2 KB checked in by bittner, 16 years ago (diff)

havran ray caster update

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