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

Revision 1627, 24.8 KB checked in by mattausch, 18 years ago (diff)
Line 
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"
8#include "ViewCellsManager.h"
9#include "ViewCellBsp.h"
10#include "VspBspTree.h"
11#include "RenderSimulator.h"
12#include "GlRenderer.h"
13#include "PlyParser.h"
14#include "SamplingStrategy.h"
15#include "VspTree.h"
16#include "OspTree.h"
17#include "ObjParser.h"
18#include "BvHierarchy.h"
19#include "HierarchyManager.h"
20#include "VssRay.h"
21#include "IntelRayCaster.h"
22#include "InternalRayCaster.h"
23
24
25
26#define DEBUG_RAYCAST 0
27#define SHOW_RAYCAST_TIMING 1
28
29
30namespace GtpVisibilityPreprocessor {
31
32const static bool ADDITIONAL_GEOMETRY_HACK = false;
33
34
35// HACK: Artificially modify scene to watch rendercost changes
36static void AddGeometry(SceneGraph *scene)
37{
38        scene->GetRoot()->UpdateBox();
39
40        AxisAlignedBox3 sceneBox = scene->GetBox();
41
42        int n = 200;
43
44        if (0)
45        {
46                // form grid of boxes
47                for (int i = 0; i < n; ++ i)
48                {
49                        for (int j = 0; j < n; ++ j)
50                        {
51                                const Vector3 scale2((float)j * 0.8f / n + 0.1f,  0.05f, (float)i * 0.8f  / (float)n + 0.1f);
52
53                                const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
54
55                                const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
56                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
57                                Mesh *mesh = CreateMeshFromBox(box);
58
59                                mesh->Preprocess();
60
61                                MeshInstance *mi = new MeshInstance(mesh);
62                                scene->GetRoot()->mGeometry.push_back(mi);
63                        }
64                }
65
66                for (int i = 0; i < n; ++ i)
67                {
68                        for (int j = 0; j < n; ++ j)
69                        {
70                                const Vector3 scale2(0.15f, (float)j * 0.8f / n + 0.1f, (float)i * 0.8f  / (float)n + 0.1f);
71
72                                Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
73
74                                Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
75                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
76                                Mesh *mesh = CreateMeshFromBox(box);
77
78                                mesh->Preprocess();
79
80                                MeshInstance *mi = new MeshInstance(mesh);
81                                scene->GetRoot()->mGeometry.push_back(mi);
82                        }
83                }
84
85                for (int i = 0; i < n; ++ i)
86                {
87                        const Vector3 scale2(2, 0.2f, (float)i * 0.8f  / (float)n + 0.1f);
88
89                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
90
91                        //Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
92                        Vector3 boxSize = sceneBox.Size() * Vector3(0.005f, 0.02f, 0.005f);
93
94                        AxisAlignedBox3 box(pt2 + 0.1f, pt2 + boxSize);
95                        Mesh *mesh = CreateMeshFromBox(box);
96
97                        mesh->Preprocess();
98
99                        MeshInstance *mi = new MeshInstance(mesh);
100                        scene->GetRoot()->mGeometry.push_back(mi);
101                }
102
103                scene->GetRoot()->UpdateBox();
104        }
105
106        if (1)
107        {
108                // plane separating view space regions
109                const Vector3 scale(1.0f, 0.0, 0);
110
111                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
112
113                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
114                Mesh *planeMesh = new Mesh();
115
116                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
117                IncludePolyInMesh(*poly, *planeMesh);
118
119                planeMesh->Preprocess();
120
121                MeshInstance *planeMi = new MeshInstance(planeMesh);
122                scene->GetRoot()->mGeometry.push_back(planeMi);
123        }       
124}
125
126
127Preprocessor::Preprocessor():
128mKdTree(NULL),
129mBspTree(NULL),
130mVspBspTree(NULL),
131mHierarchyManager(NULL),
132mViewCellsManager(NULL),
133mRenderSimulator(NULL),
134mPass(0),
135mSceneGraph(NULL),
136mRayCaster(NULL),
137mStopComputation(false)
138{
139        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
140 
141        // renderer will be constructed when the scene graph and viewcell manager will be known
142        renderer = NULL;
143 
144        Environment::GetSingleton()->GetBoolValue("Preprocessor.delayVisibilityComputation",
145                                                                                          mDelayVisibilityComputation);
146       
147        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
148        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadMeshes", mLoadMeshes);
149        Environment::GetSingleton()->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
150        Environment::GetSingleton()->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
151        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
152        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
153       
154        char buffer[256];
155        Environment::GetSingleton()->GetStringValue("Preprocessor.visibilityFile",  buffer);
156   
157        mVisibilityFileName = buffer;
158        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter );
159        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
160                                                          mApplyVisibilitySpatialFilter );
161        Environment::GetSingleton()->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
162
163        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
164        Debug << "load meshes: " << mLoadMeshes << endl;
165}
166
167
168Preprocessor::~Preprocessor()
169{
170        cout << "cleaning up" << endl;
171
172        cout << "Deleting view cells manager ... \n";
173        DEL_PTR(mViewCellsManager);
174        cout << "done.\n";
175
176        cout << "Deleting bsp tree ... \n";
177        DEL_PTR(mBspTree);
178        cout << "done.\n";
179
180        cout << "Deleting kd tree...\n";
181        DEL_PTR(mKdTree);
182        cout << "done.\n";
183
184        cout << "Deleting hierarchy manager...\n";
185        DEL_PTR(mHierarchyManager);
186        cout << "done.\n";
187
188        cout << "Deleting vspbsp tree...\n";
189        DEL_PTR(mVspBspTree);
190        cout << "done.\n";
191
192        cout << "Deleting scene graph...\n";
193        DEL_PTR(mSceneGraph);
194        cout << "done.\n";
195
196        DEL_PTR(mRenderSimulator);
197        DEL_PTR(renderer);
198        DEL_PTR(mRayCaster);
199}
200
201
202GlRendererBuffer *Preprocessor::GetRenderer()
203{
204        return renderer;
205}
206
207
208static int SplitFilenames(const string str, vector<string> &filenames)
209{
210        int pos = 0;
211
212        while(1) {
213                int npos = (int)str.find(';', pos);
214               
215                if (npos < 0 || npos - pos < 1)
216                        break;
217                filenames.push_back(string(str, pos, npos - pos));
218                pos = npos + 1;
219        }
220       
221        filenames.push_back(string(str, pos, str.size() - pos));
222        return (int)filenames.size();
223}
224
225
226bool
227Preprocessor::LoadScene(const string filename)
228{
229        // use leaf nodes of the original spatial hierarchy as occludees
230        mSceneGraph = new SceneGraph;
231 
232        Parser *parser;
233        vector<string> filenames;
234        const int files = SplitFilenames(filename, filenames);
235        cout << "number of input files: " << files << endl;
236        bool result = false;
237
238        // root for different files
239        mSceneGraph->SetRoot(new SceneGraphNode());
240
241        // intel ray caster can only trace triangles
242        int rayCastMethod;
243        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
244        vector<FaceParentInfo> *fi = (rayCastMethod == RayCaster::INTEL_RAYCASTER) ?
245                &mFaceParents : NULL;
246
247        if (files == 1) {
248               
249                if (strstr(filename.c_str(), ".x3d"))
250                  parser = new X3dParser;
251                else
252                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
253                        parser = new PlyParser;
254                  else if (strstr(filename.c_str(), ".obj"))
255                          parser = new ObjParser;
256                  else
257                          parser = new UnigraphicsParser;
258
259                cout << filename << endl;
260               
261                result = parser->ParseFile(
262                                filename,
263                                mSceneGraph->GetRoot(),
264                                mLoadMeshes,
265                                fi);
266                       
267                delete parser;
268
269        }
270        else {
271                vector<string>::const_iterator fit, fit_end = filenames.end();
272               
273                for (fit = filenames.begin(); fit != fit_end; ++ fit)
274                {
275                        const string filename = *fit;
276
277                        cout << "parsing file " << filename.c_str() << endl;
278                        if (strstr(filename.c_str(), ".x3d"))
279                                parser = new X3dParser;
280                        else
281                                parser = new UnigraphicsParser;
282
283                        SceneGraphNode *node = new SceneGraphNode();
284                        const bool success = parser->ParseFile(
285                                filename,
286                                node,
287                                mLoadMeshes,
288                                fi);
289
290                        if (success)
291                        {
292                                mSceneGraph->GetRoot()->mChildren.push_back(node);
293                                result = true; // at least one file parsed
294                        }
295
296                        delete parser;
297                }
298        }
299       
300        if (result)
301        {
302                // HACK
303                if (ADDITIONAL_GEOMETRY_HACK)
304                        AddGeometry(mSceneGraph);
305
306                mSceneGraph->AssignObjectIds();
307 
308                int intersectables, faces;
309                mSceneGraph->GetStatistics(intersectables, faces);
310 
311                cout<<filename<<" parsed successfully."<<endl;
312                cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
313                cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
314                mSceneGraph->CollectObjects(&mObjects);
315                mSceneGraph->GetRoot()->UpdateBox();
316 
317                if (0)
318                {
319                        Exporter *exporter = Exporter::GetExporter("testload.x3d");
320                        if (exporter)
321                        {
322                                exporter->ExportGeometry(mObjects);
323                                delete exporter;
324                        }
325                }
326        }
327
328        return result;
329}
330
331bool
332Preprocessor::ExportPreprocessedData(const string filename)
333{
334        mViewCellsManager->ExportViewCells(filename, true, mObjects);
335        return true;
336}
337
338
339bool
340Preprocessor::PostProcessVisibility()
341{
342 
343  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
344        cout<<"Applying visibility filter ...";
345        cout<<"filter width = " << mVisibilityFilterWidth << endl;
346       
347        if (!mViewCellsManager)
348          return false;
349       
350        mViewCellsManager->ApplyFilter(mKdTree,
351                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
352                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
353        cout << "done." << endl;
354  }
355 
356  // export the preprocessed information to a file
357  if (mExportVisibility)
358  {
359          ExportPreprocessedData(mVisibilityFileName);
360  }
361
362  return true;
363}
364
365
366bool
367Preprocessor::BuildKdTree()
368{
369  mKdTree = new KdTree;
370
371  // add mesh instances of the scene graph to the root of the tree
372  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
373       
374  mSceneGraph->CollectObjects(&root->mObjects);
375 
376  const long startTime = GetTime();
377  cout << "building kd tree ... " << endl;
378
379  mKdTree->Construct();
380
381  cout << "finished kd tree construction in " << TimeDiff(startTime, GetTime()) * 1e-3
382           << " secs " << endl;
383
384  return true;
385}
386
387
388void
389Preprocessor::KdTreeStatistics(ostream &s)
390{
391  s<<mKdTree->GetStatistics();
392}
393
394void
395Preprocessor::BspTreeStatistics(ostream &s)
396{
397        s << mBspTree->GetStatistics();
398}
399
400bool
401Preprocessor::Export( const string filename,
402                                          const bool scene,
403                                          const bool kdtree
404                                          )
405{
406  Exporter *exporter = Exporter::GetExporter(filename);
407       
408  if (exporter) {
409    if (2 && scene)
410      exporter->ExportScene(mSceneGraph->GetRoot());
411
412    if (1 && kdtree) {
413      exporter->SetWireframe();
414      exporter->ExportKdTree(*mKdTree);
415    }
416
417    delete exporter;
418    return true;
419  }
420
421  return false;
422}
423
424
425bool Preprocessor::PrepareViewCells()
426{
427        ///////
428        //-- parse view cells construction method
429
430        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
431        char buf[100];
432
433        if (mLoadViewCells)
434        {       
435          Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
436          cout << "loading view cells from " << buf << endl;
437         
438         mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, true, NULL);
439         
440          if (!mViewCellsManager)
441          {
442                  return false;
443          }
444        }
445        else
446        {
447                // parse type of view cell container
448                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
449            mViewCellsManager = CreateViewCellsManager(buf);
450
451                // default view space is the extent of the scene
452                AxisAlignedBox3 box = mSceneGraph->GetBox();
453                                       
454                if (0)
455                {
456                        // use a small box outside of the scene
457                        box.Scale(Vector3(0.1f,0.5f,0.5f));
458                        box.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size())*0.5f, 0, 0));
459                }
460
461                mViewCellsManager->SetViewSpaceBox(box);
462         
463                bool loadVcGeometry;
464                Environment::GetSingleton()->GetBoolValue("ViewCells.loadGeometry", loadVcGeometry);
465
466                bool extrudeBaseTriangles;
467                Environment::GetSingleton()->GetBoolValue("ViewCells.useBaseTrianglesAsGeometry", extrudeBaseTriangles);
468
469                char vcGeomFilename[100];
470                Environment::GetSingleton()->GetStringValue("ViewCells.geometryFilename", vcGeomFilename);
471               
472                if (loadVcGeometry)
473                {
474                        if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
475                        {
476                                if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
477                                {
478                                        cerr << "loading view cells geometry failed" << endl;
479                                }
480                        }
481                        else
482                        {
483                                cerr << "loading view cells geometry is not implemented for this manager" << endl;
484                        }
485                }
486        }
487       
488        ////////
489        //-- evaluation of render cost heuristics
490        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
491
492        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
493        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
494        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
495       
496        mRenderSimulator =
497                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
498
499        mViewCellsManager->SetRenderer(mRenderSimulator);
500       
501        if (mUseGlRenderer || mUseGlDebugger)
502          {
503                // NOTE: render texture should be power of 2 and square
504                // renderer must be initialised
505                // $$matt
506                //              renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
507                //              renderer->makeCurrent();
508               
509          }
510
511        mViewCellsManager->SetPreprocessor(this);
512        return true;
513}
514
515 
516bool Preprocessor::ConstructViewCells()
517{
518        // construct view cells using it's own set of samples
519        mViewCellsManager->Construct(this);
520
521        // visualizations and statistics
522        Debug << "finished view cells:" << endl;
523        mViewCellsManager->PrintStatistics(Debug);
524
525        return true;
526}
527
528
529HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
530{
531        HierarchyManager *hierarchyManager;
532
533        if (strcmp(name, "osp") == 0)
534        {
535                Debug << "hierarchy manager: osp" << endl;
536                // HACK for testing if per kd evaluation works!!
537                const bool ishack = false;
538                if (ishack)
539                        hierarchyManager = new HierarchyManager(mKdTree);
540                else
541                        hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
542        }
543        else if (strcmp(name, "bvh") == 0)
544        {
545                Debug << "hierarchy manager: bvh" << endl;
546                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
547        }
548        else // only view space partition
549        {
550                Debug << "hierarchy manager: obj" << endl;
551                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
552        }
553
554        return hierarchyManager;
555}
556
557
558ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
559{
560        ViewCellsTree *vcTree = new ViewCellsTree;
561
562        if (strcmp(name, "kdTree") == 0)
563        {
564                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
565        }
566        else if (strcmp(name, "bspTree") == 0)
567        {
568                Debug << "view cell type: Bsp" << endl;
569
570                mBspTree = new BspTree();
571                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
572        }
573        else if (strcmp(name, "vspBspTree") == 0)
574        {
575                Debug << "view cell type: VspBsp" << endl;
576
577                mVspBspTree = new VspBspTree();
578                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
579        }
580        else if (strcmp(name, "vspOspTree") == 0)
581        {
582                Debug << "view cell type: VspOsp" << endl;
583                char buf[100];         
584                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
585
586                HierarchyManager *mHierarchyManager = CreateHierarchyManager(buf);
587                mViewCellsManager = new VspOspViewCellsManager(vcTree, mHierarchyManager);
588        }
589        else if (strcmp(name, "sceneDependent") == 0) //TODO
590        {
591                Debug << "view cell type: Bsp" << endl;
592               
593                mBspTree = new BspTree();
594                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
595        }
596        else
597        {
598                cerr << "Wrong view cells type " << name << "!!!" << endl;
599                exit(1);
600        }
601
602        return mViewCellsManager;
603}
604
605
606// use ascii format to store rays
607#define USE_ASCII 0
608
609
610static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
611{
612        return obj1->mId < obj2->mId;
613}
614
615
616bool Preprocessor::LoadKdTree(const string filename)
617{
618        mKdTree = new KdTree();
619        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
620}
621
622
623bool Preprocessor::ExportKdTree(const string filename)
624{
625        return mKdTree->ExportBinTree(filename.c_str());
626}
627
628
629bool Preprocessor::LoadSamples(VssRayContainer &samples,
630                                                           ObjectContainer &objects) const
631{
632        std::stable_sort(objects.begin(), objects.end(), ilt);
633        char fileName[100];
634        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
635       
636    Vector3 origin, termination;
637        // HACK: needed only for lower_bound algorithm to find the
638        // intersected objects
639        MeshInstance sObj(NULL);
640        MeshInstance tObj(NULL);
641
642#if USE_ASCII
643        ifstream samplesIn(fileName);
644        if (!samplesIn.is_open())
645                return false;
646
647        string buf;
648        while (!(getline(samplesIn, buf)).eof())
649        {
650                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
651                           &origin.x, &origin.y, &origin.z,
652                           &termination.x, &termination.y, &termination.z,
653                           &(sObj.mId), &(tObj.mId));
654               
655                Intersectable *sourceObj = NULL;
656                Intersectable *termObj = NULL;
657               
658                if (sObj.mId >= 0)
659                {
660                        ObjectContainer::iterator oit =
661                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
662                        sourceObj = *oit;
663                }
664               
665                if (tObj.mId >= 0)
666                {
667                        ObjectContainer::iterator oit =
668                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
669                        termObj = *oit;
670                }
671
672                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
673        }
674#else
675        ifstream samplesIn(fileName, ios::binary);
676        if (!samplesIn.is_open())
677                return false;
678
679        while (1)
680        {
681                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
682                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
683                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
684                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
685               
686                 if (samplesIn.eof())
687                        break;
688
689                Intersectable *sourceObj = NULL;
690                Intersectable *termObj = NULL;
691               
692                if (sObj.mId >= 0)
693                {
694                        ObjectContainer::iterator oit =
695                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
696                        sourceObj = *oit;
697                }
698               
699                if (tObj.mId >= 0)
700                {
701                        ObjectContainer::iterator oit =
702                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
703                        termObj = *oit;
704                }
705
706                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
707        }
708
709#endif
710        samplesIn.close();
711
712        return true;
713}
714
715
716bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
717{
718        char fileName[100];
719        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
720       
721
722        VssRayContainer::const_iterator it, it_end = samples.end();
723       
724#if USE_ASCII
725        ofstream samplesOut(fileName);
726        if (!samplesOut.is_open())
727                return false;
728
729        for (it = samples.begin(); it != it_end; ++ it)
730        {
731                VssRay *ray = *it;
732                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
733                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
734
735                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
736                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
737                                   << sourceid << " " << termid << "\n";
738        }
739#else
740        ofstream samplesOut(fileName, ios::binary);
741        if (!samplesOut.is_open())
742                return false;
743
744        for (it = samples.begin(); it != it_end; ++ it)
745        {       
746                VssRay *ray = *it;
747                Vector3 origin(ray->GetOrigin());
748                Vector3 termination(ray->GetTermination());
749               
750                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
751                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
752
753                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
754                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
755                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
756                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
757    }
758#endif
759        samplesOut.close();
760
761        return true;
762}
763
764bool Preprocessor::GenerateRays(const int number,
765                                                                const int sampleType,
766                                                                SimpleRayContainer &rays)
767{
768        const int startSize = (int)rays.size();
769        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
770
771        if (!strategy)
772        {
773                return false;
774        }
775
776        for (int i=0; (int)rays.size() - startSize < number; ++ i)
777        {
778                SimpleRay newRay;
779
780                if (strategy->GenerateSample(newRay))
781                {
782#if 1
783                        rays.AddRay(newRay);
784#else
785                        GenerateRayBundle(rays, newRay, 16, 0);
786#endif
787                }       
788        }
789
790        delete strategy;
791    return true;
792}
793
794
795SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
796{
797        switch (strategyId)
798        {
799        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
800                return new ObjectBasedDistribution(*this);
801        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
802                return new ObjectDirectionBasedDistribution(*this);
803        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
804                return new DirectionBasedDistribution(*this);
805        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
806                return new DirectionBoxBasedDistribution(*this);
807        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
808                return new SpatialBoxBasedDistribution(*this);
809        //case OBJECTS_INTERIOR_DISTRIBUTION:
810        //      return new ObjectsInteriorDistribution(*this);
811        default: // no valid strategy
812                Debug << "warning: no valid sampling strategy" << endl;
813                return NULL;
814        }
815
816        return NULL; // should never come here
817}
818
819
820bool Preprocessor::InitRayCast(const string externKdTree, const string internKdTree)
821{
822        bool loadKdTree = true;
823        //Environment::GetSingleton()->GetBoolValue("Preprocessor.loadKdTree", loadKdTree);
824       
825       
826        if (!loadKdTree)
827        {       /////////
828                //-- build new kd tree from scene geometry
829
830                BuildKdTree();
831                KdTreeStatistics(cout);
832        }
833        else
834        {
835                long startTime = GetTime();
836                cout << "loading kd tree file " << internKdTree << " ... ";
837
838                if (!LoadKdTree(internKdTree))
839                {
840                        cout << "error loading kd tree with filename " << internKdTree << ", rebuilding it instead ..." << endl;
841
842                        BuildKdTree();
843                        KdTreeStatistics(cout);
844                }
845
846                cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
847
848                if (0)
849                {
850                        Exporter *exporter = Exporter::GetExporter("dummykd.x3d");
851                       
852                        if (exporter)
853                        {
854                                exporter->ExportKdTree(*mKdTree, true);
855                                delete exporter;
856                        }
857                }
858
859                // export kd tree?
860                startTime = GetTime();
861                cout << "exporting kd tree ... ";
862
863                if (!ExportKdTree(internKdTree))
864                {
865                        cout << " error exporting kd tree with filename " << internKdTree << endl;
866                }
867                else
868                {
869                        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
870                }
871        }
872
873        int rayCastMethod;
874        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
875
876        if (rayCastMethod == 0)
877        {
878                mRayCaster = new InternalRayCaster(*this, mKdTree);
879                cout << "ray cast method: internal" << endl;
880        }
881        else
882        {
883#ifdef GTP_INTERNAL
884                mRayCaster = new IntelRayCaster(*this, externKdTree);
885                cout << "ray cast method: intel" << endl;
886#endif
887        }
888
889        return true;
890}
891
892
893void
894Preprocessor::CastRays(
895                                           SimpleRayContainer &rays,
896                                           VssRayContainer &vssRays,
897                                           const bool castDoubleRays,
898                                           const bool pruneInvalidRays
899                                           )
900{
901        const long t1 = GetTime();
902
903        for (int i = 0; i < (int)rays.size();)
904        {
905                if (i + 16 < (int)rays.size())
906                {
907                        mRayCaster->CastRays16(
908                                                                   i,
909                                                                   rays,                               
910                                                                   vssRays,
911                                                                   mViewCellsManager->GetViewSpaceBox(),
912                                                                   castDoubleRays,
913                                                                   pruneInvalidRays);
914                        i += 16;
915                }
916                else
917                  {
918                        mRayCaster->CastRay(
919                                                                rays[i],
920                                                                vssRays,
921                                                                mViewCellsManager->GetViewSpaceBox(),
922                                                                castDoubleRays,
923                                                                pruneInvalidRays);
924                        i ++;
925                  }
926                if (i % 10000 == 0)
927                  cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
928        }
929        cout<<endl;
930       
931        long t2 = GetTime();
932
933#if SHOW_RAYCAST_TIMING
934        if (castDoubleRays)
935                cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
936        else
937                cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
938#endif 
939}
940
941
942bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
943                                                                         const SimpleRay &mainRay,
944                                                                         const int number,
945                                                                         const int pertubType) const
946{
947        rayBundle.push_back(mainRay);
948
949        const float pertubOrigin = 0.0f;
950        const float pertubDir = 0.2f;
951
952        for (int i = 0; i < number - 1; ++ i)
953        {
954                Vector3 pertub;
955
956                pertub.x = RandomValue(0.0f, pertubDir);
957                pertub.y = RandomValue(0.0f, pertubDir);
958                pertub.z = RandomValue(0.0f, pertubDir);
959                const Vector3 newDir = mainRay.mDirection + pertub;
960                //const Vector3 newDir = mainRay.mDirection;
961
962                pertub.x = RandomValue(0.0f, pertubOrigin);
963                pertub.y = RandomValue(0.0f, pertubOrigin);
964                pertub.z = RandomValue(0.0f, pertubOrigin);
965                const Vector3 newOrigin = mainRay.mOrigin + pertub;
966                //const Vector3 newOrigin = mainRay.mOrigin;
967
968                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0));
969        }
970
971        return true;
972}
973
974
975void Preprocessor::SetupRay(Ray &ray,
976                                                        const Vector3 &point,
977                                                        const Vector3 &direction
978                                                        ) const
979{
980        ray.Clear();
981        // do not store anything else then intersections at the ray
982        ray.Init(point, direction, Ray::LOCAL_RAY);
983       
984}
985
986
987}
Note: See TracBrowser for help on using the repository browser.