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

Revision 1293, 34.6 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
22
23#ifdef GTP_INTERNAL
24#include "ArchModeler2MLRT.hxx"
25#endif
26
27#define DEBUG_RAYCAST 0
28
29
30namespace GtpVisibilityPreprocessor {
31
32const static bool ADDITIONAL_GEOMETRY_HACK = false;
33
34//Preprocessor *preprocessor;
35
36
37// HACK: Artificially modify scene to watch rendercost changes
38static void AddGeometry(SceneGraph *scene)
39{
40        scene->mRoot->UpdateBox();
41
42        AxisAlignedBox3 sceneBox = scene->GetBox();
43
44        int n = 200;
45
46        if (0)
47        {
48                // form grid of boxes
49                for (int i = 0; i < n; ++ i)
50                {
51                        for (int j = 0; j < n; ++ j)
52                        {
53                                const Vector3 scale2((float)j * 0.8f / n + 0.1f,  0.05f, (float)i * 0.8f  / (float)n + 0.1f);
54
55                                const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
56
57                                const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
58                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
59                                Mesh *mesh = CreateMeshFromBox(box);
60
61                                mesh->Preprocess();
62
63                                MeshInstance *mi = new MeshInstance(mesh);
64                                scene->mRoot->mGeometry.push_back(mi);
65                        }
66                }
67
68                for (int i = 0; i < n; ++ i)
69                {
70                        for (int j = 0; j < n; ++ j)
71                        {
72                                const Vector3 scale2(0.15f, (float)j * 0.8f / n + 0.1f, (float)i * 0.8f  / (float)n + 0.1f);
73
74                                Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
75
76                                Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
77                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
78                                Mesh *mesh = CreateMeshFromBox(box);
79
80                                mesh->Preprocess();
81
82                                MeshInstance *mi = new MeshInstance(mesh);
83                                scene->mRoot->mGeometry.push_back(mi);
84                        }
85                }
86
87                for (int i = 0; i < n; ++ i)
88                {
89                        const Vector3 scale2(2, 0.2f, (float)i * 0.8f  / (float)n + 0.1f);
90
91                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
92
93                        //Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
94                        Vector3 boxSize = sceneBox.Size() * Vector3(0.005f, 0.02f, 0.005f);
95
96                        AxisAlignedBox3 box(pt2 + 0.1f, pt2 + boxSize);
97                        Mesh *mesh = CreateMeshFromBox(box);
98
99                        mesh->Preprocess();
100
101                        MeshInstance *mi = new MeshInstance(mesh);
102                        scene->mRoot->mGeometry.push_back(mi);
103                }
104
105                scene->mRoot->UpdateBox();
106        }
107
108        if (1)
109        {
110                // plane separating view space regions
111                const Vector3 scale(1.0f, 0.0, 0);
112
113                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
114
115                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
116                Mesh *planeMesh = new Mesh();
117
118                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
119                IncludePolyInMesh(*poly, *planeMesh);
120
121                planeMesh->Preprocess();
122
123                MeshInstance *planeMi = new MeshInstance(planeMesh);
124                scene->mRoot->mGeometry.push_back(planeMi);
125        }       
126}
127
128
129Preprocessor::Preprocessor():
130mKdTree(NULL),
131mBspTree(NULL),
132mVspBspTree(NULL),
133mVspTree(NULL),
134mHierarchyManager(NULL),
135mViewCellsManager(NULL),
136mRenderSimulator(NULL),
137mPass(0),
138mRayCastMethod(0)
139{
140        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
141 
142        // renderer will be constructed when the scene graph and viewcell manager will be known
143        renderer = NULL;
144 
145        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
146        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadPolygonsAsMeshes", mLoadPolygonsAsMeshes);
147        Environment::GetSingleton()->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
148        Environment::GetSingleton()->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
149        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
150        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
151        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", mRayCastMethod);
152
153        char buffer[256];
154        Environment::GetSingleton()->GetStringValue("Preprocessor.visibilityFile",  buffer);
155        mVisibilityFileName = buffer;
156        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter );
157        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
158                                                          mApplyVisibilitySpatialFilter );
159        Environment::GetSingleton()->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
160
161        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
162        Debug << "load polygons as meshes: " << mLoadPolygonsAsMeshes << endl;
163}
164
165
166Preprocessor::~Preprocessor()
167{
168        cout << "cleaning up" << endl;
169
170        cout << "Deleting view cells manager ... \n";
171        DEL_PTR(mViewCellsManager);
172        cout << "done.\n";
173
174        cout << "Deleting bsp tree ... \n";
175        DEL_PTR(mBspTree);
176        cout << "done.\n";
177
178        cout << "Deleting kd tree...\n";
179        DEL_PTR(mKdTree);
180        cout << "done.\n";
181
182        cout << "Deleting vsp tree...\n";
183        DEL_PTR(mVspTree);
184        cout << "done.\n";
185
186        cout << "Deleting hierarchy manager...\n";
187        DEL_PTR(mHierarchyManager);
188        cout << "done.\n";
189
190        cout << "Deleting vspbsp tree...\n";
191        DEL_PTR(mVspBspTree);
192        cout << "done.\n";
193
194        cout << "Deleting scene graph...\n";
195        DEL_PTR(mSceneGraph);
196        cout << "done.\n";
197
198        DEL_PTR(mRenderSimulator);
199        DEL_PTR(renderer);
200}
201
202int
203SplitFilenames(const string str, vector<string> &filenames)
204{
205        int pos = 0;
206
207        while(1) {
208                int npos = (int)str.find(';', pos);
209               
210                if (npos < 0 || npos - pos < 1)
211                        break;
212                filenames.push_back(string(str, pos, npos - pos));
213                pos = npos + 1;
214        }
215       
216        filenames.push_back(string(str, pos, str.size() - pos));
217        return (int)filenames.size();
218}
219
220
221bool
222Preprocessor::LoadScene(const string filename)
223{
224        // use leaf nodes of the original spatial hierarchy as occludees
225        mSceneGraph = new SceneGraph;
226 
227        Parser *parser;
228        vector<string> filenames;
229        int files = SplitFilenames(filename, filenames);
230        cout << "number of input files: " << files << endl;
231        bool result = false;
232        if (files == 1) {
233               
234                if (strstr(filename.c_str(), ".x3d"))
235                  parser = new X3dParser;
236                else
237                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
238                        parser = new PlyParser;
239                  else if (strstr(filename.c_str(), ".obj"))
240                          parser = new ObjParser;
241                  else
242                          parser = new UnigraphicsParser;
243
244                cout<<filename<<endl;
245
246                if (mRayCastMethod == Preprocessor::INTEL_RAYCASTER)
247                  result = parser->ParseFile(filename, &mSceneGraph->mRoot,
248                                                                         mLoadPolygonsAsMeshes,
249                                                                         &mFaceParents);
250                else
251                  result = parser->ParseFile(filename, &mSceneGraph->mRoot, mLoadPolygonsAsMeshes);
252               
253                delete parser;
254
255        } else {
256                // root for different files
257                mSceneGraph->mRoot = new SceneGraphNode;
258                for (int i= 0; i < filenames.size(); i++) {
259                  if (strstr(filenames[i].c_str(), ".x3d"))
260                        parser = new X3dParser;
261                  else
262                        parser = new UnigraphicsParser;
263                 
264                  SceneGraphNode *node;
265                  bool success;
266                 
267                  if (mRayCastMethod == Preprocessor::INTEL_RAYCASTER)
268                        success = parser->ParseFile(filename, &node,
269                                                                                mLoadPolygonsAsMeshes,
270                                                                                &mFaceParents);
271                  else
272                        success = parser->ParseFile(filename, &node, mLoadPolygonsAsMeshes);
273                 
274                  if (success) {
275                        mSceneGraph->mRoot->mChildren.push_back(node);
276                        // at least one file parsed
277                        result = true;
278                  }
279                 
280                  delete parser;
281                }
282        }
283       
284       
285        if (result)
286          {
287                // HACK
288                if (ADDITIONAL_GEOMETRY_HACK)
289                        AddGeometry(mSceneGraph);
290               
291                mSceneGraph->AssignObjectIds();
292       
293                int intersectables, faces;
294                mSceneGraph->GetStatistics(intersectables, faces);
295       
296                cout<<filename<<" parsed successfully."<<endl;
297                cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
298                cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
299                mSceneGraph->CollectObjects(&mObjects);
300                mSceneGraph->mRoot->UpdateBox();
301
302                if (0)
303                {
304                        Exporter *exporter = Exporter::GetExporter("testload.x3d");
305
306                        if (exporter)
307                        {
308                                exporter->ExportGeometry(mObjects);
309                                delete exporter;
310                        }
311                }
312        }
313       
314       
315        return result;
316}
317
318bool
319Preprocessor::ExportPreprocessedData(const string filename)
320{
321 
322  mViewCellsManager->ExportViewCells(filename, true, mObjects);
323 
324  return true;
325}
326
327bool
328Preprocessor::PostProcessVisibility()
329{
330 
331  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
332        cout<<"Applying visibility filter ...";
333        cout<<"filter width = " << mVisibilityFilterWidth << endl;
334       
335        if (!mViewCellsManager)
336          return false;
337       
338        mViewCellsManager->ApplyFilter(mKdTree,
339                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
340                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
341        cout << "done." << endl;
342  }
343 
344  // export the preprocessed information to a file
345  if (mExportVisibility)
346        ExportPreprocessedData(mVisibilityFileName);
347 
348  return true;
349}
350
351
352bool
353Preprocessor::BuildKdTree()
354{
355  mKdTree = new KdTree;
356  // add mesh instances of the scene graph to the root of the tree
357  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
358  mSceneGraph->CollectObjects(&root->mObjects);
359 
360  long startTime = GetTime();
361
362  cout << "building kd tree ... " << endl;
363  mKdTree->Construct();
364  cout << "construction finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs " << endl;
365  return true;
366}
367
368void
369Preprocessor::KdTreeStatistics(ostream &s)
370{
371  s<<mKdTree->GetStatistics();
372}
373
374void
375Preprocessor::BspTreeStatistics(ostream &s)
376{
377        s << mBspTree->GetStatistics();
378}
379
380bool
381Preprocessor::Export( const string filename,
382                                          const bool scene,
383                                          const bool kdtree,
384                                          const bool bsptree
385                                          )
386{
387  Exporter *exporter = Exporter::GetExporter(filename);
388       
389  if (exporter) {
390    if (scene)
391      exporter->ExportScene(mSceneGraph->mRoot);
392
393    if (kdtree) {
394      exporter->SetWireframe();
395      exporter->ExportKdTree(*mKdTree);
396    }
397
398        if (bsptree) {
399                //exporter->SetWireframe();
400                exporter->ExportBspTree(*mBspTree);
401        }
402
403    delete exporter;
404    return true;
405  }
406
407  return false;
408}
409
410
411bool Preprocessor::PrepareViewCells()
412{
413        //-- parse view cells construction method
414        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
415        char buf[100];
416       
417        if (mLoadViewCells)
418        {       
419                Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
420                cout << "loading view cells from " << buf << endl;
421                mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, true);
422        }
423        else
424        {
425                // parse type of view cell container
426                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
427            mViewCellsManager = CreateViewCellsManager(buf);
428
429                // default view space is the extent of the scene
430                mViewCellsManager->SetViewSpaceBox(mSceneGraph->GetBox());
431        }
432       
433        //-- parameters for render heuristics evaluation
434        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
435
436        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
437        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
438        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
439       
440        mRenderSimulator =
441                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
442
443        mViewCellsManager->SetRenderer(mRenderSimulator);
444
445
446        if (mUseGlRenderer || mUseGlDebugger)
447        {
448                // NOTE: render texture should be power of 2 and square
449                // renderer must be initialised
450                // $$matt
451//              renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
452                //              renderer->makeCurrent();
453               
454        }
455       
456        return true;
457}
458
459 
460bool
461Preprocessor::ConstructViewCells()
462{
463  // if not already loaded, construct view cells from file
464  if (!mLoadViewCells) {
465        mViewCellsManager->SetViewSpaceBox(mKdTree->GetBox());
466       
467        // construct view cells using it's own set of samples
468        mViewCellsManager->Construct(this);
469       
470        //-- several visualizations and statistics
471        Debug << "view cells construction finished: " << endl;
472        mViewCellsManager->PrintStatistics(Debug);
473  }
474  return true;
475}
476
477HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
478{
479        HierarchyManager *hierarchyManager;
480
481        if (strcmp(name, "osp") == 0)
482        {
483                Debug << "hierarchy manager: osp" << endl;
484                // HACK for testing if per kd evaluation works!!
485                const bool ishack = false;
486                if (ishack)
487                        hierarchyManager = new HierarchyManager(mVspTree, mKdTree);
488                else
489                        hierarchyManager = new HierarchyManager(mVspTree, HierarchyManager::KD_BASED_OBJ_SUBDIV);
490        }
491        else if (strcmp(name, "bvh") == 0)
492        {
493                Debug << "hierarchy manager: bvh" << endl;
494                hierarchyManager = new HierarchyManager(mVspTree, HierarchyManager::BV_BASED_OBJ_SUBDIV);
495        }
496        else // only view space partition
497        {
498                Debug << "hierarchy manager: obj" << endl;
499                hierarchyManager = new HierarchyManager(mVspTree, HierarchyManager::NO_OBJ_SUBDIV);
500        }
501
502        return hierarchyManager;
503}
504
505
506ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
507{
508        ViewCellsTree *vcTree = new ViewCellsTree;
509
510        if (strcmp(name, "kdTree") == 0)
511        {
512                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
513        }
514        else if (strcmp(name, "bspTree") == 0)
515        {
516                Debug << "view cell type: Bsp" << endl;
517
518                mBspTree = new BspTree();
519                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
520        }
521        else if (strcmp(name, "vspBspTree") == 0)
522        {
523                Debug << "view cell type: VspBsp" << endl;
524
525                mVspBspTree = new VspBspTree();
526                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
527        }
528        else if (strcmp(name, "vspOspTree") == 0)
529        {
530                mVspTree = new VspTree();
531                char buf[100];         
532                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
533
534                HierarchyManager *mHierarchyManager = CreateHierarchyManager(buf);
535                mViewCellsManager = new VspOspViewCellsManager(vcTree, mHierarchyManager);
536        }
537        else if (strcmp(name, "sceneDependent") == 0)
538        {
539                Debug << "view cell type: Bsp" << endl;
540
541                //TODO
542                mBspTree = new BspTree();
543                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
544        }
545        else
546        {
547                cerr << "Wrong view cells type " << name << "!!!" << endl;
548                exit(1);
549        }
550
551        return mViewCellsManager;
552}
553
554
555// use ascii format to store rays
556#define USE_ASCII 0
557
558
559static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
560{
561        return obj1->mId < obj2->mId;
562}
563
564
565bool Preprocessor::LoadKdTree()
566{
567        return true;
568}
569
570bool Preprocessor::ExportKdTree()
571{
572        return true;
573}
574
575
576bool Preprocessor::LoadSamples(VssRayContainer &samples,
577                                                           ObjectContainer &objects) const
578{
579        std::stable_sort(objects.begin(), objects.end(), ilt);
580        char fileName[100];
581        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
582       
583    Vector3 origin, termination;
584        // HACK: needed only for lower_bound algorithm to find the
585        // intersected objects
586        MeshInstance sObj(NULL);
587        MeshInstance tObj(NULL);
588
589#if USE_ASCII
590        ifstream samplesIn(fileName);
591        if (!samplesIn.is_open())
592                return false;
593
594        string buf;
595        while (!(getline(samplesIn, buf)).eof())
596        {
597                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
598                           &origin.x, &origin.y, &origin.z,
599                           &termination.x, &termination.y, &termination.z,
600                           &(sObj.mId), &(tObj.mId));
601               
602                Intersectable *sourceObj = NULL;
603                Intersectable *termObj = NULL;
604               
605                if (sObj.mId >= 0)
606                {
607                        ObjectContainer::iterator oit =
608                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
609                        sourceObj = *oit;
610                }
611               
612                if (tObj.mId >= 0)
613                {
614                        ObjectContainer::iterator oit =
615                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
616                        termObj = *oit;
617                }
618
619                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
620        }
621#else
622        ifstream samplesIn(fileName, ios::binary);
623        if (!samplesIn.is_open())
624                return false;
625
626        while (1)
627        {
628                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
629                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
630                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
631                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
632               
633                 if (samplesIn.eof())
634                        break;
635
636                Intersectable *sourceObj = NULL;
637                Intersectable *termObj = NULL;
638               
639                if (sObj.mId >= 0)
640                {
641                        ObjectContainer::iterator oit =
642                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
643                        sourceObj = *oit;
644                }
645               
646                if (tObj.mId >= 0)
647                {
648                        ObjectContainer::iterator oit =
649                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
650                        termObj = *oit;
651                }
652
653                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
654        }
655
656#endif
657        samplesIn.close();
658
659        return true;
660}
661
662
663bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
664{
665        char fileName[100];
666        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
667       
668
669        VssRayContainer::const_iterator it, it_end = samples.end();
670       
671#if USE_ASCII
672        ofstream samplesOut(fileName);
673        if (!samplesOut.is_open())
674                return false;
675
676        for (it = samples.begin(); it != it_end; ++ it)
677        {
678                VssRay *ray = *it;
679                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
680                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
681
682                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
683                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
684                                   << sourceid << " " << termid << "\n";
685        }
686#else
687        ofstream samplesOut(fileName, ios::binary);
688        if (!samplesOut.is_open())
689                return false;
690
691        for (it = samples.begin(); it != it_end; ++ it)
692        {       
693                VssRay *ray = *it;
694                Vector3 origin(ray->GetOrigin());
695                Vector3 termination(ray->GetTermination());
696               
697                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
698                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
699
700                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
701                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
702                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
703                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
704    }
705#endif
706        samplesOut.close();
707
708        return true;
709}
710
711#if 0 // matt: implemented interface samplestrategy
712bool
713Preprocessor::GenerateRays(
714                                                   const int number,
715                                                   const int sampleType,
716                                                   SimpleRayContainer &rays
717                                                   )
718{
719  Vector3 origin, direction;
720  int startSize = (int)rays.size();
721  for (int i=0; (int)rays.size() - startSize  < number; i ++) {
722        // now get the direction
723        switch (sampleType) {
724        case OBJECT_BASED_DISTRIBUTION: {
725          mViewCellsManager->GetViewPoint(origin);
726          Vector3 point;
727          Vector3 normal;
728          int i = RandomValue(0, mObjects.size() - 1);
729          Intersectable *object = mObjects[i];
730          object->GetRandomSurfacePoint(point, normal);
731          direction = point - origin;
732        }
733          break;
734        case OBJECT_DIRECTION_BASED_DISTRIBUTION: {
735          int i = RandomValue(0, mObjects.size() - 1);
736          Intersectable *object = mObjects[i];
737          Vector3 normal;
738          object->GetRandomSurfacePoint(origin, normal);
739          direction = UniformRandomVector(normal);
740          origin += 0.1f*direction;
741        }
742          break;
743        case DIRECTION_BASED_DISTRIBUTION:
744          mViewCellsManager->GetViewPoint(origin);
745          direction = UniformRandomVector();
746          break;
747        case DIRECTION_BOX_BASED_DISTRIBUTION: {
748          mViewCellsManager->GetViewPoint(origin);
749          float alpha = RandomValue(0.0f, 2*M_PI);
750          float beta = RandomValue(-M_PI/2, M_PI/2);
751          direction = VssRay::GetDirection(alpha, beta);
752          break;
753        }
754        case SPATIAL_BOX_BASED_DISTRIBUTION:
755          mViewCellsManager->GetViewPoint(origin);
756          direction = mKdTree->GetBox().GetRandomPoint() - origin;
757          break;
758        default:
759          // unsuported distribution type
760          return false;
761        }
762        // $$ jb the pdf is yet not correct for all sampling methods!
763        float pdf = 1.0f;
764        float c = Magnitude(direction);
765        if (c > Limits::Small) {
766          direction*=1.0f/c;
767          rays.AddRay(SimpleRay(origin, direction, pdf));
768        }
769  }
770  return true;
771}
772#endif
773bool Preprocessor::GenerateRays(const int number,
774                                                                const int sampleType,
775                                                                SimpleRayContainer &rays)
776{
777        Vector3 origin, direction;
778       
779        const int startSize = (int)rays.size();
780        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
781
782        if (!strategy)
783                return false;
784
785        for (int i=0; (int)rays.size() - startSize < number; ++ i)
786        {
787                SimpleRay newRay;
788                bool success = strategy->GenerateSample(newRay);
789
790                if (success)
791                        rays.AddRay(newRay);
792        }
793
794        delete strategy;
795
796    return true;
797}
798
799
800SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
801{
802        switch (strategyId)
803        {
804        case OBJECT_BASED_DISTRIBUTION:
805                return new ObjectBasedDistribution(*this);
806        case OBJECT_DIRECTION_BASED_DISTRIBUTION:
807                return new ObjectDirectionBasedDistribution(*this);
808        case DIRECTION_BASED_DISTRIBUTION:
809                return new DirectionBasedDistribution(*this);
810        case DIRECTION_BOX_BASED_DISTRIBUTION:
811                return new DirectionBoxBasedDistribution(*this);
812        case SPATIAL_BOX_BASED_DISTRIBUTION:
813                return new SpatialBoxBasedDistribution(*this);
814        //case OBJECTS_INTERIOR_DISTRIBUTION:
815        //      return new ObjectsInteriorDistribution(*this);
816        default: // no valid strategy
817                Debug << "warning: no valid sampling strategy" << endl;
818                return NULL;
819        }
820
821        // should never come here
822        return NULL;
823}
824
825
826bool Preprocessor::InitRayCast(const string externKdTree)
827{
828        switch (mRayCastMethod) // use intel ray tracing
829        {
830        case INTEL_RAYCASTER:
831#ifdef GTP_INTERNAL
832          cout<<"Ray Cast file: "<<externKdTree<<endl;
833          return mlrtaLoadAS(externKdTree.c_str());
834#endif
835        case INTERNAL_RAYCASTER:
836        default:
837                break;
838        }
839
840        return true;
841}
842
843
844int Preprocessor::CastIntelDoubleRay(
845                                                                         const Vector3 &viewPoint,
846                                                                         const Vector3 &direction,
847                                                                         const float probability,
848                                                                         VssRayContainer &vssRays,
849                                                                         const AxisAlignedBox3 &box
850                                                                         )
851{
852        VssRay *vssRay  = NULL;
853        int hits = 0;
854        int hittriangle;
855        Vector3 pointA, pointB;
856        Vector3 normalA, normalB;
857        Intersectable *objectA = NULL, *objectB = NULL;
858        float dist;
859       
860        double normal[3];
861#ifdef GTP_INTERNAL
862        hittriangle = mlrtaIntersectAS(&viewPoint.x,
863                                                                   &direction.x,
864                                                                   normal,
865                                                                   dist);
866#else
867        hittriangle = -1;
868#endif
869        if (hittriangle !=-1 ) {
870          if (hittriangle >= mFaceParents.size())
871                cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
872          else {
873                objectA = mFaceParents[hittriangle].mObject;
874                normalA = Vector3(normal[0], normal[1], normal[2]);
875                // Get the normal of that face
876                //              Mesh *mesh = ((MeshInstance *)objectA)->GetMesh();
877                //              normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
878                //-rays[index+i].mDirection; // $$ temporary
879                pointA = viewPoint + direction*dist;
880          }
881        }
882
883        Vector3 dir = -direction;
884#ifdef GTP_INTERNAL
885        hittriangle = mlrtaIntersectAS(&viewPoint.x,
886                                                                   &dir.x,
887                                                                   normal,
888                                                                   dist);
889#else
890        hittriangle = -1;
891#endif
892
893        if (hittriangle !=-1 ) {
894          if (hittriangle >= mFaceParents.size())
895                cerr<<"Warning: traingle index out of range! "<<hittriangle<<endl;
896          else {
897                objectB = mFaceParents[hittriangle].mObject;
898                normalB = Vector3(normal[0], normal[1], normal[2]);
899                // Get the normal of that face
900                //              Mesh *mesh = ((MeshInstance *)objectB)->GetMesh();
901                //              normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
902                //-rays[index+i].mDirection; // $$ temporary
903                pointB = viewPoint + dir*dist;
904        }
905        }
906
907        return ProcessRay(viewPoint,
908                                          direction,
909                                          objectA, pointA, normalA,
910                                          objectB, pointB, normalB,
911                                          probability,
912                                          vssRays,
913                                          box
914                                          );
915}
916
917
918Intersectable *Preprocessor::CastIntelSingleRay(const Vector3 &viewPoint,
919                                                                                                const Vector3 &direction,
920                                                                                                //const float probability,
921                                                                                                Vector3 &tPoint,
922                                                                                                const AxisAlignedBox3 &box
923                                                                                                )
924{
925        AxisAlignedBox3 sbox = box;
926        sbox.Enlarge(Vector3(-Limits::Small));
927
928        if (!sbox.IsInside(viewPoint))
929                return 0;
930       
931        float pforg[3];
932        float pfdir[3];
933        double pfnorm[3];
934
935        pforg[0] = viewPoint[0]; pforg[1] = viewPoint[1]; pforg[2] = viewPoint[2];
936        pfdir[0] = direction[0]; pfdir[1] = direction[1]; pfdir[2] = direction[2];
937
938        float dist = 0;
939#ifdef GTP_INTERNAL
940        const int hittriangle = mlrtaIntersectAS(pforg, pfdir, pfnorm, dist);
941#else
942        const int hittriangle = -1;
943#endif
944
945        if (hittriangle == -1)
946          {
947                static Ray ray;
948                SetupRay(ray, viewPoint, direction);
949               
950                float tmin = 0, tmax;
951                if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
952                  {
953                        tPoint = ray.Extrap(tmax);
954                  }
955               
956                return NULL;
957          }
958        else {
959          if (hittriangle >= mFaceParents.size()) {
960                cerr<<"Warning: traingle index out of range! "<<hittriangle<<endl;
961                return NULL;
962          }
963          else {
964               
965                tPoint[0] = pforg[0] + pfdir[0] * dist;
966                tPoint[1] = pforg[1] + pfdir[1] * dist;
967                tPoint[2] = pforg[2] + pfdir[2] * dist;
968               
969                return mFaceParents[hittriangle].mObject;
970          }
971        }
972       
973}
974
975
976int Preprocessor::CastInternalRay(
977                                                                  const Vector3 &viewPoint,
978                                                                  const Vector3 &direction,
979                                                                  const float probability,
980                                                                  VssRayContainer &vssRays,
981                                                                  const AxisAlignedBox3 &box
982                                                                  )
983{
984
985  int hits = 0;
986  static Ray ray;
987  Intersectable *objectA, *objectB;
988  Vector3 pointA, pointB;
989
990  //  AxisAlignedBox3 box = Union(mKdTree->GetBox(), mViewCellsManager->GetViewSpaceBox());
991 
992
993  AxisAlignedBox3 sbox = box;
994  sbox.Enlarge(Vector3(-Limits::Small));
995  if (!sbox.IsInside(viewPoint))
996        return 0;
997       
998  SetupRay(ray, viewPoint, direction);
999  ray.mFlags &= ~Ray::CULL_BACKFACES;
1000
1001  // cast ray to KD tree to find intersection with other objects
1002  float bsize = Magnitude(box.Size());
1003 
1004 
1005  if (mKdTree->CastRay(ray)) {
1006        objectA = ray.intersections[0].mObject;
1007        pointA = ray.Extrap(ray.intersections[0].mT);
1008        if (mDetectEmptyViewSpace)
1009          if (DotProd(ray.intersections[0].mNormal, direction) >= 0) {
1010                // discard the sample
1011                return 0;
1012          }
1013       
1014  } else {
1015        objectA = NULL;
1016        // compute intersection with the scene bounding box
1017        float tmin, tmax;
1018        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
1019          pointA = ray.Extrap(tmax);
1020        else
1021          return 0;
1022  }
1023
1024 
1025  SetupRay(ray, viewPoint, -direction);
1026  ray.mFlags &= ~Ray::CULL_BACKFACES;
1027 
1028  if (mKdTree->CastRay(ray)) {
1029        objectB = ray.intersections[0].mObject;
1030        pointB = ray.Extrap(ray.intersections[0].mT);
1031        if (mDetectEmptyViewSpace)
1032          if (DotProd(ray.intersections[0].mNormal, direction) <= 0) {
1033                // discard the sample
1034                return 0;
1035          }
1036  } else {
1037        objectB = NULL;
1038        float tmin, tmax;
1039        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
1040          pointB = ray.Extrap(tmax);
1041        else
1042          return 0;
1043  }
1044 
1045 
1046  VssRay *vssRay  = NULL;
1047  bool validSample = (objectA != objectB);
1048  if (validSample) {
1049        if (objectA) {
1050          vssRay = new VssRay(pointB,
1051                                                  pointA,
1052                                                  objectB,
1053                                                  objectA,
1054                                                  mPass,
1055                                                  probability
1056                                                  );
1057          vssRays.push_back(vssRay);
1058          hits ++;
1059        }
1060       
1061        if (objectB) {
1062          vssRay = new VssRay(pointA,
1063                                                  pointB,
1064                                                  objectA,
1065                                                  objectB,
1066                                                  mPass,
1067                                                  probability
1068                                                  );
1069          vssRays.push_back(vssRay);
1070          hits ++;
1071        }
1072  }
1073 
1074  return hits;
1075}
1076
1077
1078int
1079Preprocessor::ProcessRay(
1080                                                 const Vector3 &viewPoint,
1081                                                 const Vector3 &direction,
1082                                                 Intersectable *objectA,
1083                                                 Vector3 &pointA,
1084                                                 const Vector3 &normalA,
1085                                                 Intersectable *objectB,
1086                                                 Vector3 &pointB,
1087                                                 const Vector3 &normalB,
1088                                                 const float probability,
1089                                                 VssRayContainer &vssRays,
1090                                                 const AxisAlignedBox3 &box
1091                                                 )
1092{
1093  int hits=0;
1094#if DEBUG_RAYCAST
1095  Debug<<"PR ";
1096#endif
1097  if (objectA == NULL && objectB == NULL)
1098        return 0;
1099 
1100  AxisAlignedBox3 sbox = box;
1101  sbox.Enlarge(Vector3(-Limits::Small));
1102
1103  if (!sbox.IsInside(viewPoint))
1104        return 0;
1105
1106  if (objectA == NULL) {
1107        // compute intersection with the scene bounding box
1108        static Ray ray;
1109        SetupRay(ray, viewPoint, direction);
1110       
1111        float tmin, tmax;
1112        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
1113          pointA = ray.Extrap(tmax);
1114        else
1115          return 0;
1116  } else {
1117        if (mDetectEmptyViewSpace)
1118          if (DotProd(normalA, direction) >= 0) {
1119                // discard the sample
1120                return 0;
1121          }
1122  }
1123
1124  if (objectB == NULL) {
1125        // compute intersection with the scene bounding box
1126        static Ray ray;
1127        SetupRay(ray, viewPoint, -direction);
1128
1129        float tmin, tmax;
1130        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
1131          pointB = ray.Extrap(tmax);
1132        else
1133          return 0;
1134  } else {
1135        if (mDetectEmptyViewSpace)
1136          if (DotProd(normalB, direction) <= 0) {
1137                // discard the sample
1138                return 0;
1139          }
1140  }
1141 
1142  VssRay *vssRay  = NULL;
1143  bool validSample = (objectA != objectB);
1144  if (validSample) {
1145        if (objectA) {
1146          vssRay = new VssRay(pointB,
1147                                                  pointA,
1148                                                  objectB,
1149                                                  objectA,
1150                                                  mPass,
1151                                                  probability
1152                                                  );
1153          vssRays.push_back(vssRay);
1154          hits ++;
1155        }
1156       
1157        if (objectB) {
1158          vssRay = new VssRay(pointA,
1159                                                  pointB,
1160                                                  objectA,
1161                                                  objectB,
1162                                                  mPass,
1163                                                  probability
1164                                                  );
1165          vssRays.push_back(vssRay);
1166          hits ++;
1167        }
1168  }
1169
1170
1171  return hits;
1172}
1173
1174void
1175Preprocessor::CastRays16(const int index,
1176                                                 SimpleRayContainer &rays,
1177                                                 VssRayContainer &vssRays,
1178                                                 const AxisAlignedBox3 &sbox)
1179{
1180  int i;
1181  int num = 16;
1182
1183#if DEBUG_RAYCAST
1184  Debug<<"C16 "<<flush;
1185#endif
1186  if (mRayCastMethod == INTEL_RAYCASTER) {
1187#ifdef GTP_INTERNAL
1188
1189  int forward_hit_triangles[16];
1190  float forward_dist[16];
1191
1192  int backward_hit_triangles[16];
1193  float backward_dist[16];
1194
1195
1196  Vector3 min = sbox.Min();
1197  Vector3 max = sbox.Max();
1198  for (i=0; i < num; i++) {
1199        mlrtaStoreRayAS16(&rays[index + i].mOrigin.x,
1200                                          &rays[index + i].mDirection.x,
1201                                          i);
1202  }
1203 
1204 
1205  mlrtaTraverseGroupAS16(&min.x,
1206                                                 &max.x,
1207                                                 forward_hit_triangles,
1208                                                 forward_dist);
1209
1210  for (i=0; i < num; i++) {
1211        Vector3 dir = -rays[index + i].mDirection;
1212        mlrtaStoreRayAS16(&rays[index+i].mOrigin.x,
1213                                          &dir.x,
1214                                          i);
1215  }
1216 
1217 
1218  mlrtaTraverseGroupAS16(&min.x,
1219                                                 &max.x,
1220                                                 backward_hit_triangles,
1221                                                 backward_dist);
1222 
1223
1224
1225  for (i=0; i < num; i++) {
1226        Intersectable *objectA = NULL, *objectB = NULL;
1227        Vector3 pointA, pointB;
1228        Vector3 normalA, normalB;
1229
1230
1231 
1232        if (forward_hit_triangles[i] !=-1 ) {
1233          if (forward_hit_triangles[i] >= mFaceParents.size())
1234                cerr<<"Warning: traingle index out of range! "<<forward_hit_triangles[i]<<endl;
1235          else {
1236                objectA = mFaceParents[forward_hit_triangles[i]].mObject;
1237                // Get the normal of that face
1238                Mesh *mesh = ((MeshInstance *)objectA)->GetMesh();
1239                normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
1240                //-rays[index+i].mDirection; // $$ temporary
1241                pointA = rays[index+i].Extrap(forward_dist[i]);
1242          }
1243        }
1244       
1245        if (backward_hit_triangles[i]!=-1) {
1246          if (backward_hit_triangles[i] >= mFaceParents.size())
1247                cerr<<"Warning: traingle index out of range! "<<backward_hit_triangles[i]<<endl;
1248          else {
1249                objectB = mFaceParents[backward_hit_triangles[i]].mObject;
1250                Mesh *mesh = ((MeshInstance *)objectB)->GetMesh();
1251               
1252                normalB = mesh->GetFacePlane(mFaceParents[backward_hit_triangles[i]].mFaceIndex).mNormal;
1253               
1254                //        normalB = rays[index+i].mDirection; // $$ temporary
1255                pointB = rays[index+i].Extrap(-backward_dist[i]);
1256          }
1257        }
1258
1259        ProcessRay(rays[index+i].mOrigin,
1260                           rays[index+i].mDirection,
1261                           objectA, pointA, normalA,
1262                           objectB, pointB, normalB,
1263                           rays[index+i].mPdf,
1264                           vssRays,
1265                           sbox
1266                           );
1267  }
1268#endif
1269 
1270  } else {
1271
1272        for (i=index; i < index + num; i++) {
1273          CastRay(rays[i].mOrigin,
1274                          rays[i].mDirection,
1275                          rays[i].mPdf,
1276                          vssRays,
1277                          sbox);
1278        }
1279  }
1280#if DEBUG_RAYCAST
1281  Debug<<"C16F\n"<<flush;
1282#endif
1283}
1284
1285void
1286Preprocessor::CastRays(
1287                                           SimpleRayContainer &rays,
1288                                           VssRayContainer &vssRays
1289                                           )
1290{
1291  long t1 = GetTime();
1292  for (int i=0; i < rays.size(); ) {
1293        if (i + 16 < rays.size()) {
1294          CastRays16(
1295                                 i,
1296                                 rays,
1297                                 vssRays,
1298                                 mViewCellsManager->GetViewSpaceBox());
1299          i += 16;
1300        } else {
1301
1302          CastRay(rays[i].mOrigin,
1303                          rays[i].mDirection,
1304                          rays[i].mPdf,
1305                          vssRays,
1306                          mViewCellsManager->GetViewSpaceBox());
1307
1308          i++;
1309        }
1310        if (i % 10000 == 0)
1311          cout<<".";
1312  }
1313
1314  long t2 = GetTime();
1315 
1316  cout<<2*rays.size()/(1e3*TimeDiff(t1, t2))<<"M rays/s"<<endl;
1317}
1318
1319Intersectable *
1320Preprocessor::CastSimpleRay(
1321                                                        const Vector3 &viewPoint,
1322                                                        const Vector3 &direction,
1323                                                        const AxisAlignedBox3 &box,
1324                                                        Vector3 &point,
1325                                                        Vector3 &normal
1326                                                        )
1327{
1328  Intersectable *result = NULL;
1329  switch (mRayCastMethod)
1330        {
1331        case INTEL_RAYCASTER: {
1332          float dist;
1333          int hittriangle;
1334          double n[3];
1335
1336#ifdef GTP_INTERNAL
1337          hittriangle = mlrtaIntersectAS(&viewPoint.x,
1338                                                                         &direction.x,
1339                                                                         n,
1340                                                                         dist);
1341
1342#else
1343        hittriangle = -1;
1344#endif
1345
1346          if (hittriangle !=-1 ) {
1347                if (hittriangle >= mFaceParents.size())
1348                  cerr<<"Warning: traingle index out of range! "<<hittriangle<<endl;
1349                else {
1350                  result = mFaceParents[hittriangle].mObject;
1351                  normal = Vector3(n[0], n[1], n[2]);
1352                  point = viewPoint + direction*dist;
1353                }
1354          }
1355          break;
1356        }
1357        case INTERNAL_RAYCASTER:
1358        default: {
1359          static Ray ray;
1360         
1361          ray.intersections.clear();
1362          // do not store anything else then intersections at the ray
1363          ray.Init(viewPoint, direction, Ray::LOCAL_RAY);
1364         
1365          ray.mFlags &= ~Ray::CULL_BACKFACES;
1366         
1367          if (mKdTree->CastRay(ray)) {
1368                result = ray.intersections[0].mObject;
1369                point = ray.Extrap(ray.intersections[0].mT);
1370                normal = ray.intersections[0].mNormal;
1371          }
1372          break;
1373        }
1374        }
1375  return result;
1376}
1377
1378int
1379Preprocessor::CastRay(
1380                                          const Vector3 &viewPoint,
1381                                          const Vector3 &direction,
1382                                          const float probability,
1383                                          VssRayContainer &vssRays,
1384                                          const AxisAlignedBox3 &box
1385                                          )
1386{
1387#if DEBUG_RAYCAST
1388  Debug<<"CR "<<flush;
1389#endif
1390  switch (mRayCastMethod)
1391        {
1392        case INTEL_RAYCASTER:
1393                return CastIntelDoubleRay(viewPoint, direction, probability, vssRays, box);
1394        case INTERNAL_RAYCASTER:
1395        default:
1396                return CastInternalRay(viewPoint, direction, probability, vssRays, box);
1397        }
1398#if DEBUG_RAYCAST
1399  Debug<<"CRF "<<flush;
1400#endif 
1401}
1402
1403
1404void Preprocessor::SetupRay(Ray &ray,
1405                                                        const Vector3 &point,
1406                                                        const Vector3 &direction
1407                                                        )
1408{
1409        ray.Clear();
1410        // do not store anything else then intersections at the ray
1411        ray.Init(point, direction, Ray::LOCAL_RAY);
1412}
1413
1414}
Note: See TracBrowser for help on using the repository browser.