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

Revision 1359, 34.9 KB checked in by mattausch, 18 years ago (diff)

worked on global object sorting

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