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

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