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

Revision 1414, 34.1 KB checked in by mattausch, 18 years ago (diff)

fixed kd tree loading / exporting

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.loadMeshes", mLoadMeshes);
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 meshes: " << mLoadMeshes << endl;
164
165        if (mRayCastMethod == 0)
166                cout << "ray cast method: internal" << endl;
167        else
168                cout << "ray cast method: intel" << endl;
169}
170
171
172Preprocessor::~Preprocessor()
173{
174        cout << "cleaning up" << endl;
175
176        cout << "Deleting view cells manager ... \n";
177        DEL_PTR(mViewCellsManager);
178        cout << "done.\n";
179
180        cout << "Deleting bsp tree ... \n";
181        DEL_PTR(mBspTree);
182        cout << "done.\n";
183
184        cout << "Deleting kd tree...\n";
185        DEL_PTR(mKdTree);
186        cout << "done.\n";
187
188        cout << "Deleting vsp tree...\n";
189        DEL_PTR(mVspTree);
190        cout << "done.\n";
191
192        cout << "Deleting hierarchy manager...\n";
193        DEL_PTR(mHierarchyManager);
194        cout << "done.\n";
195
196        cout << "Deleting vspbsp tree...\n";
197        DEL_PTR(mVspBspTree);
198        cout << "done.\n";
199
200        cout << "Deleting scene graph...\n";
201        DEL_PTR(mSceneGraph);
202        cout << "done.\n";
203
204        DEL_PTR(mRenderSimulator);
205        DEL_PTR(renderer);
206}
207
208int
209SplitFilenames(const string str, vector<string> &filenames)
210{
211        int pos = 0;
212
213        while(1) {
214                int npos = (int)str.find(';', pos);
215               
216                if (npos < 0 || npos - pos < 1)
217                        break;
218                filenames.push_back(string(str, pos, npos - pos));
219                pos = npos + 1;
220        }
221       
222        filenames.push_back(string(str, pos, str.size() - pos));
223        return (int)filenames.size();
224}
225
226
227bool
228Preprocessor::LoadScene(const string filename)
229{
230        // use leaf nodes of the original spatial hierarchy as occludees
231        mSceneGraph = new SceneGraph;
232 
233        Parser *parser;
234        vector<string> filenames;
235        const int files = SplitFilenames(filename, filenames);
236        cout << "number of input files: " << files << endl;
237        bool result = false;
238
239        // root for different files
240        mSceneGraph->SetRoot(new SceneGraphNode());
241
242        // intel ray caster can only trace triangles
243        vector<FaceParentInfo> *fi = (mRayCastMethod == Preprocessor::INTEL_RAYCASTER) ?
244                &mFaceParents : NULL;
245
246        if (files == 1) {
247               
248                if (strstr(filename.c_str(), ".x3d"))
249                  parser = new X3dParser;
250                else
251                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
252                        parser = new PlyParser;
253                  else if (strstr(filename.c_str(), ".obj"))
254                          parser = new ObjParser;
255                  else
256                          parser = new UnigraphicsParser;
257
258                cout << filename << endl;
259               
260                result = parser->ParseFile(
261                                filename,
262                                mSceneGraph->GetRoot(),
263                                mLoadMeshes,
264                                fi);
265                       
266                delete parser;
267
268        }
269        else {
270                vector<string>::const_iterator fit, fit_end = filenames.end();
271               
272                for (fit = filenames.begin(); fit != fit_end; ++ fit)
273                {
274                        const string filename = *fit;
275
276                        cout << "parsing file " << filename.c_str() << endl;
277                        if (strstr(filename.c_str(), ".x3d"))
278                                parser = new X3dParser;
279                        else
280                                parser = new UnigraphicsParser;
281
282                        SceneGraphNode *node = new SceneGraphNode();
283                        const bool success = parser->ParseFile(
284                                filename,
285                                node,
286                                mLoadMeshes,
287                                fi);
288
289                        if (success)
290                        {
291                                mSceneGraph->GetRoot()->mChildren.push_back(node);
292                                result = true; // at least one file parsed
293                        }
294
295                        delete parser;
296                }
297        }
298       
299        if (result)
300        {
301                // HACK
302                if (ADDITIONAL_GEOMETRY_HACK)
303                        AddGeometry(mSceneGraph);
304
305                mSceneGraph->AssignObjectIds();
306 
307                int intersectables, faces;
308                mSceneGraph->GetStatistics(intersectables, faces);
309 
310                cout<<filename<<" parsed successfully."<<endl;
311                cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
312                cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
313                mSceneGraph->CollectObjects(&mObjects);
314                mSceneGraph->GetRoot()->UpdateBox();
315 
316                if (0)
317                {
318                        Exporter *exporter = Exporter::GetExporter("testload.x3d");
319                        if (exporter)
320                        {
321                                exporter->ExportGeometry(mObjects);
322                                delete exporter;
323                        }
324                }
325        }
326
327        return result;
328}
329
330bool
331Preprocessor::ExportPreprocessedData(const string filename)
332{
333 
334  mViewCellsManager->ExportViewCells(filename, true, mObjects);
335 
336  return true;
337}
338
339bool
340Preprocessor::PostProcessVisibility()
341{
342 
343  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
344        cout<<"Applying visibility filter ...";
345        cout<<"filter width = " << mVisibilityFilterWidth << endl;
346       
347        if (!mViewCellsManager)
348          return false;
349       
350        mViewCellsManager->ApplyFilter(mKdTree,
351                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
352                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
353        cout << "done." << endl;
354  }
355 
356  // export the preprocessed information to a file
357  if (mExportVisibility)
358        ExportPreprocessedData(mVisibilityFileName);
359 
360  return true;
361}
362
363
364bool
365Preprocessor::BuildKdTree()
366{
367  mKdTree = new KdTree;
368
369  // add mesh instances of the scene graph to the root of the tree
370  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
371       
372  mSceneGraph->CollectObjects(&root->mObjects);
373 
374  long startTime = GetTime();
375  cout << "building kd tree ... " << endl;
376
377  mKdTree->Construct();
378
379  cout << "construction finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs " << endl;
380
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 (0 && scene)
407      exporter->ExportScene(mSceneGraph->GetRoot());
408
409    if (0 && kdtree) {
410      exporter->SetWireframe();
411      exporter->ExportKdTree(*mKdTree);
412    }
413
414        if (0 && 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(const string filename)
583{
584        mKdTree = new KdTree();
585        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
586}
587
588
589bool Preprocessor::ExportKdTree(const string filename)
590{
591        return mKdTree->ExportBinTree(filename.c_str());
592}
593
594
595bool Preprocessor::LoadSamples(VssRayContainer &samples,
596                                                           ObjectContainer &objects) const
597{
598        std::stable_sort(objects.begin(), objects.end(), ilt);
599        char fileName[100];
600        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
601       
602    Vector3 origin, termination;
603        // HACK: needed only for lower_bound algorithm to find the
604        // intersected objects
605        MeshInstance sObj(NULL);
606        MeshInstance tObj(NULL);
607
608#if USE_ASCII
609        ifstream samplesIn(fileName);
610        if (!samplesIn.is_open())
611                return false;
612
613        string buf;
614        while (!(getline(samplesIn, buf)).eof())
615        {
616                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
617                           &origin.x, &origin.y, &origin.z,
618                           &termination.x, &termination.y, &termination.z,
619                           &(sObj.mId), &(tObj.mId));
620               
621                Intersectable *sourceObj = NULL;
622                Intersectable *termObj = NULL;
623               
624                if (sObj.mId >= 0)
625                {
626                        ObjectContainer::iterator oit =
627                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
628                        sourceObj = *oit;
629                }
630               
631                if (tObj.mId >= 0)
632                {
633                        ObjectContainer::iterator oit =
634                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
635                        termObj = *oit;
636                }
637
638                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
639        }
640#else
641        ifstream samplesIn(fileName, ios::binary);
642        if (!samplesIn.is_open())
643                return false;
644
645        while (1)
646        {
647                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
648                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
649                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
650                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
651               
652                 if (samplesIn.eof())
653                        break;
654
655                Intersectable *sourceObj = NULL;
656                Intersectable *termObj = NULL;
657               
658                if (sObj.mId >= 0)
659                {
660                        ObjectContainer::iterator oit =
661                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
662                        sourceObj = *oit;
663                }
664               
665                if (tObj.mId >= 0)
666                {
667                        ObjectContainer::iterator oit =
668                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
669                        termObj = *oit;
670                }
671
672                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
673        }
674
675#endif
676        samplesIn.close();
677
678        return true;
679}
680
681
682bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
683{
684        char fileName[100];
685        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
686       
687
688        VssRayContainer::const_iterator it, it_end = samples.end();
689       
690#if USE_ASCII
691        ofstream samplesOut(fileName);
692        if (!samplesOut.is_open())
693                return false;
694
695        for (it = samples.begin(); it != it_end; ++ it)
696        {
697                VssRay *ray = *it;
698                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
699                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
700
701                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
702                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
703                                   << sourceid << " " << termid << "\n";
704        }
705#else
706        ofstream samplesOut(fileName, ios::binary);
707        if (!samplesOut.is_open())
708                return false;
709
710        for (it = samples.begin(); it != it_end; ++ it)
711        {       
712                VssRay *ray = *it;
713                Vector3 origin(ray->GetOrigin());
714                Vector3 termination(ray->GetTermination());
715               
716                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
717                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
718
719                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
720                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
721                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
722                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
723    }
724#endif
725        samplesOut.close();
726
727        return true;
728}
729
730bool Preprocessor::GenerateRays(const int number,
731                                                                const int sampleType,
732                                                                SimpleRayContainer &rays)
733{
734        const int startSize = (int)rays.size();
735        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
736
737        if (!strategy)
738        {
739                return false;
740        }
741
742        for (int i=0; (int)rays.size() - startSize < number; ++ i)
743        {
744                SimpleRay newRay;
745
746                if (strategy->GenerateSample(newRay))
747                {
748#if 1
749                        rays.AddRay(newRay);
750#else
751                        GenerateRayBundle(rays, newRay, 16, 0);
752#endif
753                }       
754        }
755
756        delete strategy;
757    return true;
758}
759
760
761SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
762{
763        switch (strategyId)
764        {
765        case OBJECT_BASED_DISTRIBUTION:
766                return new ObjectBasedDistribution(*this);
767        case OBJECT_DIRECTION_BASED_DISTRIBUTION:
768                return new ObjectDirectionBasedDistribution(*this);
769        case DIRECTION_BASED_DISTRIBUTION:
770                return new DirectionBasedDistribution(*this);
771        case DIRECTION_BOX_BASED_DISTRIBUTION:
772                return new DirectionBoxBasedDistribution(*this);
773        case SPATIAL_BOX_BASED_DISTRIBUTION:
774                return new SpatialBoxBasedDistribution(*this);
775        //case OBJECTS_INTERIOR_DISTRIBUTION:
776        //      return new ObjectsInteriorDistribution(*this);
777        default: // no valid strategy
778                Debug << "warning: no valid sampling strategy" << endl;
779                return NULL;
780        }
781
782        // should never come here
783        return NULL;
784}
785
786
787bool Preprocessor::InitRayCast(const string externKdTree)
788{
789        switch (mRayCastMethod) // use intel ray tracing
790        {
791        case INTEL_RAYCASTER:
792#ifdef GTP_INTERNAL
793          cout<<"Ray Cast file: " << externKdTree << endl;
794          return mlrtaLoadAS(externKdTree.c_str());
795#endif
796        case INTERNAL_RAYCASTER:
797        default:
798                break;
799        }
800
801        return true;
802}
803
804
805int Preprocessor::CastIntelDoubleRay(
806                                                                         const Vector3 &viewPoint,
807                                                                         const Vector3 &direction,
808                                                                         const float probability,
809                                                                         VssRayContainer &vssRays,
810                                                                         const AxisAlignedBox3 &box
811                                                                         )
812{
813#ifdef GTP_INTERNAL
814        //cout << "intel ray" << endl;
815        VssRay *vssRay  = NULL;
816        int hits = 0;
817        int hittriangle;
818        Vector3 pointA, pointB;
819        Vector3 normalA, normalB;
820        Intersectable *objectA = NULL, *objectB = NULL;
821        float dist;
822        double normal[3];
823
824        hittriangle = mlrtaIntersectAS(&viewPoint.x,
825                &direction.x,
826                normal,
827                dist);
828
829        if (hittriangle != -1 ) {
830                if (hittriangle >= mFaceParents.size())
831                        cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
832                else {
833                        objectA = mFaceParents[hittriangle].mObject;
834                        normalA = Vector3(normal[0], normal[1], normal[2]);
835                        // Get the normal of that face
836                        //              Mesh *mesh = ((MeshInstance *)objectA)->GetMesh();
837                        //              normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
838                        //-rays[index+i].mDirection; // $$ temporary
839                        pointA = viewPoint + direction*dist;
840                }
841        }
842
843
844        Vector3 dir = -direction;
845        hittriangle = mlrtaIntersectAS(&viewPoint.x,
846                &dir.x,
847                normal,
848                dist);
849
850        if (hittriangle != -1 ) {
851                if (hittriangle >= mFaceParents.size())
852                        cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
853                else {
854                        objectB = mFaceParents[hittriangle].mObject;
855                        normalB = Vector3(normal[0], normal[1], normal[2]);
856                        // Get the normal of that face
857                        //              Mesh *mesh = ((MeshInstance *)objectB)->GetMesh();
858                        //              normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
859                        //-rays[index+i].mDirection; // $$ temporary
860                        pointB = viewPoint + dir * dist;
861                }
862        }
863
864        return ProcessRay(viewPoint,
865                direction,
866                objectA, pointA, normalA,
867                objectB, pointB, normalB,
868                probability,
869                vssRays,
870                box
871                );
872#else
873        return -1;
874#endif
875}
876
877
878Intersectable *Preprocessor::CastIntelSingleRay(const Vector3 &viewPoint,
879                                                                                                const Vector3 &direction,
880                                                                                                //const float probability,
881                                                                                                Vector3 &tPoint,
882                                                                                                const AxisAlignedBox3 &box
883                                                                                                )
884{
885        AxisAlignedBox3 sbox = box;
886        sbox.Enlarge(Vector3(-Limits::Small));
887
888        if (!sbox.IsInside(viewPoint))
889                return 0;
890       
891#ifdef GTP_INTERNAL
892        float pforg[3];
893        float pfdir[3];
894        double pfnorm[3];
895
896        pforg[0] = viewPoint[0]; pforg[1] = viewPoint[1]; pforg[2] = viewPoint[2];
897        pfdir[0] = direction[0]; pfdir[1] = direction[1]; pfdir[2] = direction[2];
898
899        float dist;
900        const int hittriangle = mlrtaIntersectAS(pforg, pfdir, pfnorm, dist);
901
902        if (hittriangle == -1)
903          {
904                static Ray ray;
905                SetupRay(ray, viewPoint, direction);
906               
907                float tmin = 0, tmax;
908                if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
909                  {
910                        tPoint = ray.Extrap(tmax);
911                  }
912               
913                return NULL;
914          }
915        else {
916          if (hittriangle >= mFaceParents.size()) {
917                cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
918                return NULL;
919          }
920          else {
921               
922                tPoint[0] = pforg[0] + pfdir[0] * dist;
923                tPoint[1] = pforg[1] + pfdir[1] * dist;
924                tPoint[2] = pforg[2] + pfdir[2] * dist;
925               
926                return mFaceParents[hittriangle].mObject;
927          }
928        }
929
930#else
931        const int hittriangle = -1;
932        return NULL;
933#endif
934
935}
936
937
938int Preprocessor::CastInternalRay(
939                                                                  const Vector3 &viewPoint,
940                                                                  const Vector3 &direction,
941                                                                  const float probability,
942                                                                  VssRayContainer &vssRays,
943                                                                  const AxisAlignedBox3 &box
944                                                                  )
945{
946  //cout << "internal ray" << endl;
947  int hits = 0;
948  static Ray ray;
949  Intersectable *objectA, *objectB;
950  Vector3 pointA, pointB;
951
952  //  AxisAlignedBox3 box = Union(mKdTree->GetBox(), mViewCellsManager->GetViewSpaceBox());
953  AxisAlignedBox3 sbox = box;
954  sbox.Enlarge(Vector3(-Limits::Small));
955  if (!sbox.IsInside(viewPoint))
956        return 0;
957       
958  SetupRay(ray, viewPoint, direction);
959  ray.mFlags &= ~Ray::CULL_BACKFACES;
960
961  // cast ray to KD tree to find intersection with other objects
962  float bsize = Magnitude(box.Size());
963 
964 
965  if (mKdTree->CastRay(ray)) {
966        objectA = ray.intersections[0].mObject;
967        pointA = ray.Extrap(ray.intersections[0].mT);
968        if (mDetectEmptyViewSpace)
969          if (DotProd(ray.intersections[0].mNormal, direction) >= 0) {
970                // discard the sample
971                return 0;
972          }
973       
974  } else {
975        objectA = NULL;
976        // compute intersection with the scene bounding box
977        float tmin, tmax;
978        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
979          pointA = ray.Extrap(tmax);
980        else
981          return 0;
982  }
983
984  SetupRay(ray, viewPoint, -direction);
985  ray.mFlags &= ~Ray::CULL_BACKFACES;
986 
987  if (mKdTree->CastRay(ray)) {
988        objectB = ray.intersections[0].mObject;
989        pointB = ray.Extrap(ray.intersections[0].mT);
990        if (mDetectEmptyViewSpace)
991          if (DotProd(ray.intersections[0].mNormal, direction) <= 0) {
992                // discard the sample
993                return 0;
994          }
995  } else {
996        objectB = NULL;
997        float tmin, tmax;
998        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
999          pointB = ray.Extrap(tmax);
1000        else
1001          return 0;
1002  }
1003 
1004 
1005  VssRay *vssRay  = NULL;
1006  bool validSample = (objectA != objectB);
1007  if (validSample) {
1008        if (objectA) {
1009          vssRay = new VssRay(pointB,
1010                                                  pointA,
1011                                                  objectB,
1012                                                  objectA,
1013                                                  mPass,
1014                                                  probability
1015                                                  );
1016          vssRays.push_back(vssRay);
1017          //cout << "ray: " << *vssRay << endl;
1018          hits ++;
1019        }
1020       
1021        if (objectB) {
1022          vssRay = new VssRay(pointA,
1023                                                  pointB,
1024                                                  objectA,
1025                                                  objectB,
1026                                                  mPass,
1027                                                  probability
1028                                                  );
1029          vssRays.push_back(vssRay);
1030          //cout << "ray: " << *vssRay << endl;
1031          hits ++;
1032        }
1033  }
1034 
1035  return hits;
1036}
1037
1038
1039int
1040Preprocessor::ProcessRay(
1041                                                 const Vector3 &viewPoint,
1042                                                 const Vector3 &direction,
1043                                                 Intersectable *objectA,
1044                                                 Vector3 &pointA,
1045                                                 const Vector3 &normalA,
1046                                                 Intersectable *objectB,
1047                                                 Vector3 &pointB,
1048                                                 const Vector3 &normalB,
1049                                                 const float probability,
1050                                                 VssRayContainer &vssRays,
1051                                                 const AxisAlignedBox3 &box
1052                                                 )
1053{
1054  int hits=0;
1055#if DEBUG_RAYCAST
1056  Debug<<"PR ";
1057#endif
1058  if (objectA == NULL && objectB == NULL)
1059        return 0;
1060 
1061  AxisAlignedBox3 sbox = box;
1062  sbox.Enlarge(Vector3(-Limits::Small));
1063
1064  if (!sbox.IsInside(viewPoint))
1065        return 0;
1066
1067  if (objectA == NULL) {
1068        // compute intersection with the scene bounding box
1069        static Ray ray;
1070        SetupRay(ray, viewPoint, direction);
1071       
1072        float tmin, tmax;
1073        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
1074          pointA = ray.Extrap(tmax);
1075        else
1076          return 0;
1077  } else {
1078        if (mDetectEmptyViewSpace)
1079          if (DotProd(normalA, direction) >= 0) {
1080                // discard the sample
1081                return 0;
1082          }
1083  }
1084
1085  if (objectB == NULL) {
1086        // compute intersection with the scene bounding box
1087        static Ray ray;
1088        SetupRay(ray, viewPoint, -direction);
1089
1090        float tmin, tmax;
1091        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
1092          pointB = ray.Extrap(tmax);
1093        else
1094          return 0;
1095  } else {
1096        if (mDetectEmptyViewSpace)
1097          if (DotProd(normalB, direction) <= 0) {
1098                // discard the sample
1099                return 0;
1100          }
1101  }
1102 
1103  VssRay *vssRay  = NULL;
1104  bool validSample = (objectA != objectB);
1105  if (validSample) {
1106        if (objectA) {
1107          vssRay = new VssRay(pointB,
1108                                                  pointA,
1109                                                  objectB,
1110                                                  objectA,
1111                                                  mPass,
1112                                                  probability
1113                                                  );
1114          vssRays.push_back(vssRay);
1115          //cout << "ray: " << *vssRay << endl;
1116          hits ++;
1117        }
1118       
1119        if (objectB) {
1120          vssRay = new VssRay(pointA,
1121                                                  pointB,
1122                                                  objectA,
1123                                                  objectB,
1124                                                  mPass,
1125                                                  probability
1126                                                  );
1127          vssRays.push_back(vssRay);
1128          //cout << "ray: " << *vssRay << endl;
1129          hits ++;
1130        }
1131  }
1132
1133
1134  return hits;
1135}
1136
1137void
1138Preprocessor::CastRays16(const int index,
1139                                                 SimpleRayContainer &rays,
1140                                                 VssRayContainer &vssRays,
1141                                                 const AxisAlignedBox3 &sbox)
1142{
1143  int i;
1144  const int num = 16;
1145
1146#if DEBUG_RAYCAST
1147  Debug<<"C16 "<<flush;
1148#endif
1149  if (mRayCastMethod == INTEL_RAYCASTER) {
1150#ifdef GTP_INTERNAL
1151
1152  int forward_hit_triangles[16];
1153  float forward_dist[16];
1154
1155  int backward_hit_triangles[16];
1156  float backward_dist[16];
1157
1158
1159  Vector3 min = sbox.Min();
1160  Vector3 max = sbox.Max();
1161 
1162  for (i=0; i < num; i++) {
1163        mlrtaStoreRayAS16(&rays[index + i].mOrigin.x,
1164                                          &rays[index + i].mDirection.x,
1165                                          i);
1166  }
1167 
1168  mlrtaTraverseGroupAS16(&min.x,
1169                                                 &max.x,
1170                                                 forward_hit_triangles,
1171                                                 forward_dist);
1172
1173  for (i=0; i < num; i++) {
1174        Vector3 dir = -rays[index + i].mDirection;
1175        mlrtaStoreRayAS16(&rays[index+i].mOrigin.x,
1176                                          &dir.x,
1177                                          i);
1178  }
1179 
1180  mlrtaTraverseGroupAS16(&min.x,
1181                                                 &max.x,
1182                                                 backward_hit_triangles,
1183                                                 backward_dist);
1184 
1185
1186  for (i=0; i < num; i++) {
1187        Intersectable *objectA = NULL, *objectB = NULL;
1188        Vector3 pointA, pointB;
1189        Vector3 normalA, normalB;
1190
1191        if (forward_hit_triangles[i] != -1 ) {
1192          if (forward_hit_triangles[i] >= mFaceParents.size())
1193                cerr<<"Warning: triangle index out of range! "<<forward_hit_triangles[i]<<endl;
1194          else {
1195                objectA = mFaceParents[forward_hit_triangles[i]].mObject;
1196                // Get the normal of that face
1197                normalA = objectA->GetNormal(mFaceParents[forward_hit_triangles[i]].mFaceIndex);
1198                //-rays[index+i].mDirection; // $$ temporary
1199                pointA = rays[index+i].Extrap(forward_dist[i]);
1200          }
1201        }
1202         
1203        if (backward_hit_triangles[i]!=-1) {
1204          if (backward_hit_triangles[i] >= mFaceParents.size())
1205                cerr<<"Warning: triangle  index out of range! "<<backward_hit_triangles[i]<<endl;
1206          else {
1207                objectB = mFaceParents[backward_hit_triangles[i]].mObject;
1208                normalB = objectB->GetNormal(mFaceParents[forward_hit_triangles[i]].mFaceIndex);
1209               
1210                // normalB = rays[index+i].mDirection; // $$ temporary
1211                pointB = rays[index+i].Extrap(-backward_dist[i]);
1212          }
1213        }
1214 
1215        ProcessRay(rays[index+i].mOrigin,
1216                           rays[index+i].mDirection,
1217                           objectA, pointA, normalA,
1218                           objectB, pointB, normalB,
1219                           rays[index+i].mPdf,
1220                           vssRays,
1221                           sbox
1222                           );
1223  }
1224 
1225#endif
1226 
1227  } else {
1228
1229        for (i=index; i < index + num; i++) {
1230          CastRay(rays[i].mOrigin,
1231                          rays[i].mDirection,
1232                          rays[i].mPdf,
1233                          vssRays,
1234                          sbox);
1235        }
1236  }
1237#if DEBUG_RAYCAST
1238  Debug<<"C16F\n"<<flush;
1239#endif
1240}
1241
1242void
1243Preprocessor::CastRays(
1244                                           SimpleRayContainer &rays,
1245                                           VssRayContainer &vssRays
1246                                           )
1247{
1248  long t1 = GetTime();
1249 
1250  for (int i = 0; i < (int)rays.size(); ) {
1251          // method only available for intel raycaster yet
1252        if (i + 16 < (int)rays.size()) {
1253
1254          CastRays16(
1255                                 i,
1256                                 rays,
1257                                 vssRays,
1258                                 mViewCellsManager->GetViewSpaceBox());
1259          i += 16;
1260        } else {
1261          CastRay(rays[i].mOrigin,
1262                          rays[i].mDirection,
1263                          rays[i].mPdf,
1264                          vssRays,
1265                          mViewCellsManager->GetViewSpaceBox());
1266          i++;
1267        }
1268        if (i % 10000 == 0)
1269          cout<<".";
1270  }
1271
1272  long t2 = GetTime();
1273  cout<<2*rays.size()/(1e3*TimeDiff(t1, t2))<<"M rays/s"<<endl;
1274}
1275
1276Intersectable *
1277Preprocessor::CastSimpleRay(
1278                                                        const Vector3 &viewPoint,
1279                                                        const Vector3 &direction,
1280                                                        const AxisAlignedBox3 &box,
1281                                                        Vector3 &point,
1282                                                        Vector3 &normal
1283                                                        )
1284{
1285  Intersectable *result = NULL;
1286  switch (mRayCastMethod)
1287        {
1288        case INTEL_RAYCASTER: {
1289         
1290          int hittriangle;
1291
1292#ifdef GTP_INTERNAL
1293          float dist;
1294          double n[3];
1295
1296          hittriangle = mlrtaIntersectAS(&viewPoint.x,
1297                                                                         &direction.x,
1298                                                                         n,
1299                                                                         dist);
1300
1301           if (hittriangle !=-1 ) {
1302                if (hittriangle >= mFaceParents.size())
1303                  cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
1304                else {
1305                  result = mFaceParents[hittriangle].mObject;
1306                  normal = Vector3(n[0], n[1], n[2]);
1307                  point = viewPoint + direction*dist;
1308                }
1309          }
1310#else
1311          hittriangle = -1;
1312#endif
1313
1314          break;
1315        }
1316        case INTERNAL_RAYCASTER:
1317        default: {
1318          static Ray ray;
1319         
1320          ray.intersections.clear();
1321          // do not store anything else then intersections at the ray
1322          ray.Init(viewPoint, direction, Ray::LOCAL_RAY);
1323         
1324          ray.mFlags &= ~Ray::CULL_BACKFACES;
1325         
1326          if (mKdTree->CastRay(ray)) {
1327                result = ray.intersections[0].mObject;
1328                point = ray.Extrap(ray.intersections[0].mT);
1329                normal = ray.intersections[0].mNormal;
1330          }
1331          break;
1332        }
1333        }
1334  return result;
1335}
1336
1337int
1338Preprocessor::CastRay(
1339                                          const Vector3 &viewPoint,
1340                                          const Vector3 &direction,
1341                                          const float probability,
1342                                          VssRayContainer &vssRays,
1343                                          const AxisAlignedBox3 &box
1344                                          )
1345{
1346#if DEBUG_RAYCAST
1347  Debug<<"CR "<<flush;
1348#endif
1349  switch (mRayCastMethod)
1350        {
1351        case INTEL_RAYCASTER:
1352                return CastIntelDoubleRay(viewPoint, direction, probability, vssRays, box);
1353        case INTERNAL_RAYCASTER:
1354        default:
1355                return CastInternalRay(viewPoint, direction, probability, vssRays, box);
1356        }
1357#if DEBUG_RAYCAST       
1358  Debug<<"CRF "<<flush;
1359#endif 
1360}
1361
1362
1363bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
1364                                                                         const SimpleRay &mainRay,
1365                                                                         const int number,
1366                                                                         const int pertubType) const
1367{
1368        rayBundle.push_back(mainRay);
1369
1370        const float pertubOrigin = 10.0f;
1371        const float pertubDir = 0.0f;
1372
1373        for (int i = 0; i < number - 1; ++ i)
1374        {
1375                Vector3 pertub;
1376
1377                pertub.x = RandomValue(0.0f, pertubDir);
1378                pertub.y = RandomValue(0.0f, pertubDir);
1379                pertub.z = RandomValue(0.0f, pertubDir);
1380                const Vector3 newDir = mainRay.mDirection + pertub;
1381                //const Vector3 newDir = mainRay.mDirection;
1382
1383                pertub.x = RandomValue(0.0f, pertubOrigin);
1384                pertub.y = RandomValue(0.0f, pertubOrigin);
1385                pertub.z = RandomValue(0.0f, pertubOrigin);
1386                const Vector3 newOrigin = mainRay.mOrigin + pertub;
1387                //const Vector3 newOrigin = mainRay.mOrigin;
1388
1389                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0));
1390        }
1391
1392        return true;
1393}
1394
1395
1396void Preprocessor::SetupRay(Ray &ray,
1397                                                        const Vector3 &point,
1398                                                        const Vector3 &direction
1399                                                        )
1400{
1401        ray.Clear();
1402        // do not store anything else then intersections at the ray
1403        ray.Init(point, direction, Ray::LOCAL_RAY);
1404}
1405
1406}
Note: See TracBrowser for help on using the repository browser.