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

Revision 2714, 46.2 KB checked in by bittner, 16 years ago (diff)

dynamic object changes in preprocessor.cpp

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