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

Revision 2709, 44.6 KB checked in by mattausch, 16 years ago (diff)

sheduling dynamic object only when necessary

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