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

Revision 1613, 24.4 KB checked in by bittner, 18 years ago (diff)

kd-tree hack active

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 (mViewCellsManager->GetType() == ViewCellsManager::BSP)
473                {
474                        if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
475                        {
476                                cerr << "loading view cells geometry failed" << endl;
477                        }
478                }
479                else
480                {
481                        cerr << "loading view cells geometry is not implemented for this manager" << endl;
482                }
483        }
484       
485        ////////
486        //-- evaluation of render cost heuristics
487        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
488
489        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
490        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
491        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
492       
493        mRenderSimulator =
494                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
495
496        mViewCellsManager->SetRenderer(mRenderSimulator);
497       
498        if (mUseGlRenderer || mUseGlDebugger)
499          {
500                // NOTE: render texture should be power of 2 and square
501                // renderer must be initialised
502                // $$matt
503                //              renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
504                //              renderer->makeCurrent();
505               
506          }
507
508        mViewCellsManager->SetPreprocessor(this);
509        return true;
510}
511
512 
513bool Preprocessor::ConstructViewCells()
514{
515  // construct view cells using it's own set of samples
516  mViewCellsManager->Construct(this);
517 
518  // visualizations and statistics
519  Debug << "finished view cells:" << endl;
520  mViewCellsManager->PrintStatistics(Debug);
521 
522  return true;
523}
524
525
526HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
527{
528        HierarchyManager *hierarchyManager;
529
530        if (strcmp(name, "osp") == 0)
531        {
532                Debug << "hierarchy manager: osp" << endl;
533                // HACK for testing if per kd evaluation works!!
534                const bool ishack = false;
535                if (ishack)
536                        hierarchyManager = new HierarchyManager(mKdTree);
537                else
538                        hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
539        }
540        else if (strcmp(name, "bvh") == 0)
541        {
542                Debug << "hierarchy manager: bvh" << endl;
543                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
544        }
545        else // only view space partition
546        {
547                Debug << "hierarchy manager: obj" << endl;
548                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
549        }
550
551        return hierarchyManager;
552}
553
554
555ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
556{
557        ViewCellsTree *vcTree = new ViewCellsTree;
558
559        if (strcmp(name, "kdTree") == 0)
560        {
561                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
562        }
563        else if (strcmp(name, "bspTree") == 0)
564        {
565                Debug << "view cell type: Bsp" << endl;
566
567                mBspTree = new BspTree();
568                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
569        }
570        else if (strcmp(name, "vspBspTree") == 0)
571        {
572                Debug << "view cell type: VspBsp" << endl;
573
574                mVspBspTree = new VspBspTree();
575                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
576        }
577        else if (strcmp(name, "vspOspTree") == 0)
578        {
579                Debug << "view cell type: VspOsp" << endl;
580                char buf[100];         
581                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
582
583                HierarchyManager *mHierarchyManager = CreateHierarchyManager(buf);
584                mViewCellsManager = new VspOspViewCellsManager(vcTree, mHierarchyManager);
585        }
586        else if (strcmp(name, "sceneDependent") == 0) //TODO
587        {
588                Debug << "view cell type: Bsp" << endl;
589               
590                mBspTree = new BspTree();
591                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
592        }
593        else
594        {
595                cerr << "Wrong view cells type " << name << "!!!" << endl;
596                exit(1);
597        }
598
599        return mViewCellsManager;
600}
601
602
603// use ascii format to store rays
604#define USE_ASCII 0
605
606
607static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
608{
609        return obj1->mId < obj2->mId;
610}
611
612
613bool Preprocessor::LoadKdTree(const string filename)
614{
615        mKdTree = new KdTree();
616        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
617}
618
619
620bool Preprocessor::ExportKdTree(const string filename)
621{
622        return mKdTree->ExportBinTree(filename.c_str());
623}
624
625
626bool Preprocessor::LoadSamples(VssRayContainer &samples,
627                                                           ObjectContainer &objects) const
628{
629        std::stable_sort(objects.begin(), objects.end(), ilt);
630        char fileName[100];
631        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
632       
633    Vector3 origin, termination;
634        // HACK: needed only for lower_bound algorithm to find the
635        // intersected objects
636        MeshInstance sObj(NULL);
637        MeshInstance tObj(NULL);
638
639#if USE_ASCII
640        ifstream samplesIn(fileName);
641        if (!samplesIn.is_open())
642                return false;
643
644        string buf;
645        while (!(getline(samplesIn, buf)).eof())
646        {
647                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
648                           &origin.x, &origin.y, &origin.z,
649                           &termination.x, &termination.y, &termination.z,
650                           &(sObj.mId), &(tObj.mId));
651               
652                Intersectable *sourceObj = NULL;
653                Intersectable *termObj = NULL;
654               
655                if (sObj.mId >= 0)
656                {
657                        ObjectContainer::iterator oit =
658                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
659                        sourceObj = *oit;
660                }
661               
662                if (tObj.mId >= 0)
663                {
664                        ObjectContainer::iterator oit =
665                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
666                        termObj = *oit;
667                }
668
669                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
670        }
671#else
672        ifstream samplesIn(fileName, ios::binary);
673        if (!samplesIn.is_open())
674                return false;
675
676        while (1)
677        {
678                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
679                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
680                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
681                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
682               
683                 if (samplesIn.eof())
684                        break;
685
686                Intersectable *sourceObj = NULL;
687                Intersectable *termObj = NULL;
688               
689                if (sObj.mId >= 0)
690                {
691                        ObjectContainer::iterator oit =
692                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
693                        sourceObj = *oit;
694                }
695               
696                if (tObj.mId >= 0)
697                {
698                        ObjectContainer::iterator oit =
699                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
700                        termObj = *oit;
701                }
702
703                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
704        }
705
706#endif
707        samplesIn.close();
708
709        return true;
710}
711
712
713bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
714{
715        char fileName[100];
716        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
717       
718
719        VssRayContainer::const_iterator it, it_end = samples.end();
720       
721#if USE_ASCII
722        ofstream samplesOut(fileName);
723        if (!samplesOut.is_open())
724                return false;
725
726        for (it = samples.begin(); it != it_end; ++ it)
727        {
728                VssRay *ray = *it;
729                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
730                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
731
732                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
733                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
734                                   << sourceid << " " << termid << "\n";
735        }
736#else
737        ofstream samplesOut(fileName, ios::binary);
738        if (!samplesOut.is_open())
739                return false;
740
741        for (it = samples.begin(); it != it_end; ++ it)
742        {       
743                VssRay *ray = *it;
744                Vector3 origin(ray->GetOrigin());
745                Vector3 termination(ray->GetTermination());
746               
747                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
748                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
749
750                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
751                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
752                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
753                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
754    }
755#endif
756        samplesOut.close();
757
758        return true;
759}
760
761bool Preprocessor::GenerateRays(const int number,
762                                                                const int sampleType,
763                                                                SimpleRayContainer &rays)
764{
765        const int startSize = (int)rays.size();
766        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
767
768        if (!strategy)
769        {
770                return false;
771        }
772
773        for (int i=0; (int)rays.size() - startSize < number; ++ i)
774        {
775                SimpleRay newRay;
776
777                if (strategy->GenerateSample(newRay))
778                {
779#if 1
780                        rays.AddRay(newRay);
781#else
782                        GenerateRayBundle(rays, newRay, 16, 0);
783#endif
784                }       
785        }
786
787        delete strategy;
788    return true;
789}
790
791
792SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
793{
794        switch (strategyId)
795        {
796        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
797                return new ObjectBasedDistribution(*this);
798        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
799                return new ObjectDirectionBasedDistribution(*this);
800        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
801                return new DirectionBasedDistribution(*this);
802        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
803                return new DirectionBoxBasedDistribution(*this);
804        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
805                return new SpatialBoxBasedDistribution(*this);
806        //case OBJECTS_INTERIOR_DISTRIBUTION:
807        //      return new ObjectsInteriorDistribution(*this);
808        default: // no valid strategy
809                Debug << "warning: no valid sampling strategy" << endl;
810                return NULL;
811        }
812
813        return NULL; // should never come here
814}
815
816
817bool Preprocessor::InitRayCast(const string externKdTree, const string internkdtree)
818{
819        bool loadKdTree;
820        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadKdTree", loadKdTree);
821       
822        if (!loadKdTree)
823        {       
824                //-- build new kd tree from scene geometry
825                BuildKdTree();
826                KdTreeStatistics(cout);
827        }
828        else
829        {
830                const long startTime = GetTime();
831                cout << "loading kd tree file " << internkdtree << " ... ";
832
833                if (!LoadKdTree(internkdtree))
834                {
835                        cout << "error loading kd tree with filename " << internkdtree << ", rebuilding it instead ..." << endl;
836
837                        BuildKdTree();
838                        KdTreeStatistics(cout);
839                }
840
841                cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
842
843                if (0)
844                {
845                        Exporter *exporter = Exporter::GetExporter("dummykd.x3d");
846                       
847                        if (exporter)
848                        {
849                                exporter->ExportKdTree(*mKdTree, true);
850                                delete exporter;
851                        }
852                }
853        }
854
855        int rayCastMethod;
856        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
857
858        if (rayCastMethod == 0)
859        {
860                mRayCaster = new InternalRayCaster(*this, mKdTree);
861                cout << "ray cast method: internal" << endl;
862        }
863        else
864        {
865#ifdef GTP_INTERNAL
866                mRayCaster = new IntelRayCaster(*this, externKdTree);
867                cout << "ray cast method: intel" << endl;
868#endif
869        }
870
871        return true;
872}
873
874
875void
876Preprocessor::CastRays(
877                                           SimpleRayContainer &rays,
878                                           VssRayContainer &vssRays,
879                                           const bool castDoubleRays,
880                                           const bool pruneInvalidRays
881                                           )
882{
883        const long t1 = GetTime();
884
885        for (int i = 0; i < (int)rays.size();)
886        {
887                if (i + 16 < (int)rays.size())
888                {
889                        mRayCaster->CastRays16(
890                                                                   i,
891                                                                   rays,                               
892                                                                   vssRays,
893                                                                   mViewCellsManager->GetViewSpaceBox(),
894                                                                   castDoubleRays,
895                                                                   pruneInvalidRays);
896                        i += 16;
897                }
898                else
899                  {
900                        mRayCaster->CastRay(
901                                                                rays[i],
902                                                                vssRays,
903                                                                mViewCellsManager->GetViewSpaceBox(),
904                                                                castDoubleRays,
905                                                                pruneInvalidRays);
906                        i ++;
907                  }
908                if (i % 10000 == 0)
909                  cout<<"\r"<<i<<"/"<<rays.size()<<"\r";
910        }
911        cout<<endl;
912       
913        long t2 = GetTime();
914
915#if SHOW_RAYCAST_TIMING
916        if (castDoubleRays)
917                cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
918        else
919                cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
920#endif 
921}
922
923
924bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
925                                                                         const SimpleRay &mainRay,
926                                                                         const int number,
927                                                                         const int pertubType) const
928{
929        rayBundle.push_back(mainRay);
930
931        const float pertubOrigin = 0.0f;
932        const float pertubDir = 0.2f;
933
934        for (int i = 0; i < number - 1; ++ i)
935        {
936                Vector3 pertub;
937
938                pertub.x = RandomValue(0.0f, pertubDir);
939                pertub.y = RandomValue(0.0f, pertubDir);
940                pertub.z = RandomValue(0.0f, pertubDir);
941                const Vector3 newDir = mainRay.mDirection + pertub;
942                //const Vector3 newDir = mainRay.mDirection;
943
944                pertub.x = RandomValue(0.0f, pertubOrigin);
945                pertub.y = RandomValue(0.0f, pertubOrigin);
946                pertub.z = RandomValue(0.0f, pertubOrigin);
947                const Vector3 newOrigin = mainRay.mOrigin + pertub;
948                //const Vector3 newOrigin = mainRay.mOrigin;
949
950                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0));
951        }
952
953        return true;
954}
955
956
957void Preprocessor::SetupRay(Ray &ray,
958                                                        const Vector3 &point,
959                                                        const Vector3 &direction
960                                                        ) const
961{
962        ray.Clear();
963        // do not store anything else then intersections at the ray
964        ray.Init(point, direction, Ray::LOCAL_RAY);
965       
966}
967
968
969}
Note: See TracBrowser for help on using the repository browser.