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

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