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

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