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

Revision 2708, 43.8 KB checked in by bittner, 16 years ago (diff)

Updates functional for verbose pvs - sprintf_s changed to sprintf due to compiling problem on vs2003

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