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

Revision 2065, 40.3 KB checked in by mattausch, 17 years ago (diff)

debug version: something wrong with the pvs!

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