source: trunk/VUT/GtpVisibilityPreprocessor/src/RssPreprocessor.cpp @ 451

Revision 451, 15.2 KB checked in by mattausch, 19 years ago (diff)

added viewcellsmanager to rsspreprocessor

Line 
1#include "SceneGraph.h"
2#include "KdTree.h"
3#include "RssPreprocessor.h"
4#include "X3dExporter.h"
5#include "Environment.h"
6#include "MutualVisibility.h"
7#include "Polygon3.h"
8#include "ViewCell.h"
9#include "VssRay.h"
10#include "RssTree.h"
11#include "ViewCellsManager.h"
12
13static bool useViewSpaceBox = true;//true;
14static bool use2dSampling = false;
15static bool fromBoxVisibility = true;
16
17static bool exportPvs = false;
18
19RssPreprocessor::RssPreprocessor():
20  mPass(0),
21  mVssRays()
22{
23  // this should increase coherence of the samples
24  environment->GetIntValue("RssPreprocessor.samplesPerPass", mSamplesPerPass);
25  environment->GetIntValue("RssPreprocessor.initialSamples", mInitialSamples);
26  environment->GetIntValue("RssPreprocessor.vssSamples", mRssSamples);
27  environment->GetIntValue("RssPreprocessor.vssSamplesPerPass", mRssSamplesPerPass);
28  environment->GetBoolValue("RssPreprocessor.useImportanceSampling", mUseImportanceSampling);
29  environment->GetIntValue("BspTree.Construction.samples", mBspConstructionSamples);
30       
31  mStats.open("stats.log");
32}
33
34RssPreprocessor::~RssPreprocessor()
35{
36  CLEAR_CONTAINER(mVssRays);
37}
38
39void
40RssPreprocessor::SetupRay(Ray &ray,
41                                                  const Vector3 &point,
42                                                  const Vector3 &direction
43                                                  )
44{
45  ray.intersections.clear();
46  // do not store anything else then intersections at the ray
47  ray.Init(point, direction, Ray::LOCAL_RAY);
48}
49
50int
51RssPreprocessor::CastRay(
52                                                 Vector3 &viewPoint,
53                                                 Vector3 &direction,
54                                                 VssRayContainer &vssRays
55                                                 )
56{
57  int hits = 0;
58  static Ray ray;
59  AxisAlignedBox3 box = mKdTree->GetBox();
60
61  AxisAlignedBox3 sbox = box;
62  sbox.Enlarge(Vector3(-Limits::Small));
63  if (!sbox.IsInside(viewPoint))
64        return 0;
65       
66  SetupRay(ray, viewPoint, direction);
67  // cast ray to KD tree to find intersection with other objects
68  Intersectable *objectA, *objectB;
69  Vector3 pointA, pointB;
70  float bsize = Magnitude(box.Size());
71 
72  if (mKdTree->CastRay(ray)) {
73        objectA = ray.intersections[0].mObject;
74        pointA = ray.Extrap(ray.intersections[0].mT);
75  } else {
76        objectA = NULL;
77        // compute intersection with the scene bounding box
78        float tmin, tmax;
79        box.ComputeMinMaxT(ray, &tmin, &tmax);
80        if (tmax > bsize) {
81          //cerr<<"Warning: tmax > box size tmax="<<tmax<<" tmin="<<tmin<<" size="<<bsize<<endl;
82          //cerr<<"ray"<<ray<<endl;
83        }
84        pointA = ray.Extrap(tmax);
85  }
86
87  bool detectEmptyViewSpace = true;
88       
89  if (detectEmptyViewSpace) {
90        SetupRay(ray, pointA, -direction);
91  } else
92        SetupRay(ray, viewPoint, -direction);
93       
94       
95  if (mKdTree->CastRay(ray)) {
96        objectB = ray.intersections[0].mObject;
97        pointB = ray.Extrap(ray.intersections[0].mT);
98  } else {
99        objectB = NULL;
100        float tmin, tmax;
101        box.ComputeMinMaxT(ray, &tmin, &tmax);
102        if (tmax > bsize) {
103          //cerr<<"Warning: tmax > box size tmax="<<tmax<<" tmin="<<tmin<<" size="<<bsize<<endl;
104          //cerr<<"ray"<<ray<<endl;
105        }
106        pointB = ray.Extrap(tmax);
107  }
108
109  VssRay *vssRay  = NULL;
110
111  bool validSample = true;
112  if (detectEmptyViewSpace) {
113        // check if the viewpoint lies on the line segment AB
114        if (Distance(pointA, pointB) <
115                Distance(viewPoint, pointA) + Distance(viewPoint, pointB) - Limits::Small) {
116          validSample = false;
117        }
118  }
119       
120  if (validSample) {
121        if (objectA) {
122          vssRay = new VssRay(pointB,
123                                                  pointA,
124                                                  objectB,
125                                                  objectA);
126          vssRays.push_back(vssRay);
127          hits ++;
128        }
129       
130        if (objectB) {
131          vssRay = new VssRay(pointA,
132                                                  pointB,
133                                                  objectA,
134                                                  objectB);
135          vssRays.push_back(vssRay);
136          hits ++;
137        }
138  }
139       
140  return hits;
141}
142
143
144Vector3
145RssPreprocessor::GetViewpoint(AxisAlignedBox3 *viewSpaceBox)
146{
147  AxisAlignedBox3 box;
148       
149  if (viewSpaceBox)
150        box =*viewSpaceBox;
151  else
152        box = mKdTree->GetBox();
153       
154  // shrink the box in the y direction
155  return box.GetRandomPoint();
156}
157
158Vector3
159RssPreprocessor::GetDirection(const Vector3 &viewpoint,
160                                                          AxisAlignedBox3 *viewSpaceBox
161                                                          )
162{
163  Vector3 point;
164  if (!use2dSampling) {
165        Vector3 normal;
166        int i = RandomValue(0, mObjects.size()-1);
167        Intersectable *object = mObjects[i];
168        object->GetRandomSurfacePoint(point, normal);
169  } else {
170        AxisAlignedBox3 box;
171               
172        if (viewSpaceBox)
173          box =*viewSpaceBox;
174        else
175          box = mKdTree->GetBox();
176               
177        point = box.GetRandomPoint();
178        point.y = viewpoint.y;
179  }
180       
181  return point - viewpoint;
182}
183
184int
185RssPreprocessor::GenerateImportanceRays(RssTree *rssTree,
186                                                                                const int desiredSamples,
187                                                                                SimpleRayContainer &rays
188                                                                                )
189{
190  int num;
191 
192  float avgPvsSize;
193  float avgRayContribution;
194  float avgPvsEntropy;
195  float avgRayLengthEntropy;
196  float avgImportance;
197 
198  rssTree->GetTreeStatistics(
199                                                         avgPvsSize,
200                                                         avgRayContribution,
201                                                         avgPvsEntropy,
202                                                         avgRayLengthEntropy,
203                                                         avgImportance);
204 
205  cout<<
206        "#AVG_PVS_SIZE\n"<<avgPvsSize<<endl<<
207        "#AVG_RAY_CONTRIB\n"<<avgRayContribution<<endl<<
208        "#AVG_PVS_ENTROPY\n"<<avgPvsEntropy<<endl<<
209        "#AVG_RAY_LENGTH_ENTROPY\n"<<avgRayLengthEntropy<<endl<<
210        "#AVG_IMPORTANCE\n"<<avgImportance<<endl;
211 
212  if (0) {
213        float p = desiredSamples/(float)(avgRayContribution*rssTree->stat.Leaves());
214        num = rssTree->GenerateRays(p, rays);
215  } else {
216        int leaves = rssTree->stat.Leaves()/2;
217        num = rssTree->GenerateRays(desiredSamples, leaves, rays);
218  }
219       
220  cout<<"Generated "<<num<<" rays."<<endl;
221       
222  return num;
223}
224
225
226bool
227RssPreprocessor::ExportRays(const char *filename,
228                                                        const VssRayContainer &vssRays,
229                                                        const int number
230                                                        )
231{
232  cout<<"Exporting vss rays..."<<endl<<flush;
233       
234  float prob = number/(float)vssRays.size();
235
236
237  Exporter *exporter = NULL;
238  exporter = Exporter::GetExporter(filename);
239  //    exporter->SetWireframe();
240  //    exporter->ExportKdTree(*mKdTree);
241  exporter->SetFilled();
242  exporter->ExportScene(mSceneGraph->mRoot);
243  exporter->SetWireframe();
244
245  if (mViewSpaceBox) {
246        exporter->SetForcedMaterial(RgbColor(1,0,1));
247        exporter->ExportBox(*mViewSpaceBox);
248        exporter->ResetForcedMaterial();
249  }
250       
251  VssRayContainer rays; for (int i=0; i < vssRays.size(); i++)
252        if (RandomValue(0,1) < prob)
253          rays.push_back(vssRays[i]);
254
255  exporter->ExportRays(rays, RgbColor(1, 0, 0));
256       
257  delete exporter;
258
259  cout<<"done."<<endl<<flush;
260
261  return true;
262}
263
264
265bool
266RssPreprocessor::ExportRssTree(char *filename,
267                                                           RssTree *tree,
268                                                           const Vector3 &dir
269                                                           )
270{
271  Exporter *exporter = Exporter::GetExporter(filename);
272  exporter->SetFilled();
273  exporter->ExportScene(mSceneGraph->mRoot);
274  //  exporter->SetWireframe();
275  bool result = exporter->ExportRssTree2( *tree, dir );
276  delete exporter;
277  return result;
278}
279
280bool
281RssPreprocessor::ExportRssTreeLeaf(char *filename,
282                                                                   RssTree *tree,
283                                                                   RssTreeLeaf *leaf)
284{
285  Exporter *exporter = NULL;
286  exporter = Exporter::GetExporter(filename);
287  exporter->SetWireframe();
288  exporter->ExportKdTree(*mKdTree);
289       
290  if (mViewSpaceBox) {
291        exporter->SetForcedMaterial(RgbColor(1,0,0));
292        exporter->ExportBox(*mViewSpaceBox);
293        exporter->ResetForcedMaterial();
294  }
295       
296  exporter->SetForcedMaterial(RgbColor(0,0,1));
297  exporter->ExportBox(tree->GetBBox(leaf));
298  exporter->ResetForcedMaterial();
299       
300  VssRayContainer rays[4];
301  for (int i=0; i < leaf->rays.size(); i++) {
302        int k = leaf->rays[i].GetRayClass();
303        rays[k].push_back(leaf->rays[i].mRay);
304  }
305       
306  // SOURCE RAY
307  exporter->ExportRays(rays[0], RgbColor(1, 0, 0));
308  // TERMINATION RAY
309  exporter->ExportRays(rays[1], RgbColor(1, 1, 1));
310  // PASSING_RAY
311  exporter->ExportRays(rays[2], RgbColor(1, 1, 0));
312  // CONTAINED_RAY
313  exporter->ExportRays(rays[3], RgbColor(0, 0, 1));
314
315  delete exporter;
316  return true;
317}
318
319void
320RssPreprocessor::ExportRssTreeLeaves(RssTree *tree, const int number)
321{
322  vector<RssTreeLeaf *> leaves;
323  tree->CollectLeaves(leaves);
324
325  int num = 0;
326  int i;
327  float p = number / (float)leaves.size();
328  for (i=0; i < leaves.size(); i++) {
329        if (RandomValue(0,1) < p) {
330          char filename[64];
331          sprintf(filename, "rss-leaf-%04d.x3d", num);
332          ExportRssTreeLeaf(filename, tree, leaves[i]);
333          num++;
334        }
335        if (num >= number)
336          break;
337  }
338}
339
340
341float
342RssPreprocessor::GetAvgPvsSize(RssTree *tree,
343                                                           const vector<AxisAlignedBox3> &viewcells
344                                                           )
345{
346  vector<AxisAlignedBox3>::const_iterator it, it_end = viewcells.end();
347
348  int sum = 0;
349  for (it = viewcells.begin(); it != it_end; ++ it)
350        sum += tree->GetPvsSize(*it);
351       
352  return sum/(float)viewcells.size();
353}
354
355
356void
357RssPreprocessor::ExportPvs(char *filename,
358                                                   RssTree *rssTree
359                                                   )
360{
361  ObjectContainer pvs;
362  if (rssTree->CollectRootPvs(pvs)) {
363        Exporter *exporter = Exporter::GetExporter(filename);
364        exporter->SetFilled();
365        exporter->ExportGeometry(pvs);
366        delete exporter;
367  }
368}
369
370bool
371RssPreprocessor::ComputeVisibility()
372{
373 
374  mSceneGraph->CollectObjects(&mObjects);
375       
376  long startTime = GetTime();
377 
378  int totalSamples = 0;
379
380  /// Rays used for post processing and visualizations.
381  RayContainer storedRays;
382
383  AxisAlignedBox3 *box = new AxisAlignedBox3(mKdTree->GetBox());
384
385  if (fromBoxVisibility) {
386        float size = 0.05f;
387        float s = 0.5f - size;
388        float olds = Magnitude(box->Size());
389        box->Enlarge(box->Size()*Vector3(-s));
390        Vector3 translation = Vector3(-olds*0.1f, 0, 0);
391        box->SetMin(box->Min() + translation);
392        box->SetMax(box->Max() + translation);
393  } else {
394               
395        // sample city like heights
396        box->SetMin(1, box->Min(1) + box->Size(1)*0.2);
397        box->SetMax(1, box->Min(1) + box->Size(1)*0.3);
398  }
399
400  if (use2dSampling)
401        box->SetMax(1, box->Min(1));
402       
403  if (useViewSpaceBox)
404        mViewSpaceBox = box;
405  else
406        mViewSpaceBox = NULL;
407               
408
409  RssTree *rssTree = NULL;
410
411  while (totalSamples < mInitialSamples) {
412        int passContributingSamples = 0;
413        int passSampleContributions = 0;
414        int passSamples = 0;
415        int index = 0;
416               
417        int sampleContributions;
418               
419        int s = Min(mSamplesPerPass, mInitialSamples);
420        for (int k=0; k < s; k++) {
421                       
422          Vector3 viewpoint = GetViewpoint(mViewSpaceBox);
423          Vector3 direction = GetDirection(viewpoint, mViewSpaceBox);
424                       
425          CastRay(viewpoint, direction, mVssRays);
426                       
427                       
428          //-- CORR matt: put block inside loop
429          if (sampleContributions) {
430                passContributingSamples ++;
431                passSampleContributions += sampleContributions;
432          }
433          passSamples++;
434          totalSamples++;
435        }
436   
437        mPass++;
438               
439        int pvsSize = 0;
440        float avgRayContrib = (passContributingSamples > 0) ?
441          passSampleContributions/(float)passContributingSamples : 0;
442               
443        cout << "#Pass " << mPass << " : t = " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
444        cout << "#TotalSamples=" << totalSamples/1000
445                 << "k   #SampleContributions=" << passSampleContributions << " ("
446                 << 100*passContributingSamples/(float)passSamples<<"%)" << " avgPVS="
447                 << pvsSize/(float)mObjects.size() << endl
448                 << "avg ray contrib=" << avgRayContrib << endl;
449               
450        mStats <<
451          "#Pass\n" <<mPass<<endl<<
452          "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl<<
453          "#TotalSamples\n" << totalSamples<< endl<<
454          "#SampleContributions\n" << passSampleContributions << endl <<
455          "#PContributingSamples\n"<<100*passContributingSamples/(float)passSamples<<endl <<
456          "#AvgPVS\n"<< pvsSize/(float)mObjects.size() << endl <<
457          "#AvgRayContrib\n" << avgRayContrib << endl;
458  }
459 
460  cout << "#totalPvsSize=" << mKdTree->CollectLeafPvs() << endl;
461  cout << "#totalRayStackSize=" << mVssRays.size() << endl <<flush;
462 
463  int numExportRays = 10000;
464  //  int numExportRays = 0;
465
466  if (numExportRays) {
467        char filename[64];
468        sprintf(filename, "rss-rays-initial.x3d");
469        ExportRays(filename, mVssRays, numExportRays);
470  }
471 
472  if (exportPvs) {
473        ExportPvs("rss-pvs-initial.x3d", rssTree);
474  }
475
476  // construct view cells
477  mViewCellsManager->Construct(mObjects, mVssRays, mViewSpaceBox);
478
479  rssTree = new RssTree;
480  // viewcells = Construct(mVssRays);
481       
482  if (fromBoxVisibility)
483        rssTree->Construct(mVssRays, mViewSpaceBox);
484  else
485        rssTree->Construct(mVssRays, NULL);
486
487  cout<<"RssTree root PVS size = "<<rssTree->GetRootPvsSize()<<endl;
488 
489  ExportRssTree("rss-tree-100.x3d", rssTree, Vector3(1,0,0));
490  ExportRssTree("rss-tree-001.x3d", rssTree, Vector3(0,0,1));
491  ExportRssTree("rss-tree-101.x3d", rssTree, Vector3(1,0,1));
492  ExportRssTree("rss-tree-101m.x3d", rssTree, Vector3(-1,0,-1));
493
494  ExportRssTreeLeaves(rssTree, 10);
495
496  // viewcells->UpdatePVS(newVssRays);
497  // get viewcells as kd tree boxes
498  vector<AxisAlignedBox3> kdViewcells;
499  if (0) {
500        vector<KdLeaf *> leaves;
501        mKdTree->CollectLeaves(leaves);
502        vector<KdLeaf *>::const_iterator it;
503        int targetLeaves = 50;
504        float prob = targetLeaves/(float)leaves.size();
505        for (it = leaves.begin(); it != leaves.end(); ++it)
506          if (RandomValue(0.0f,1.0f) < prob)
507                kdViewcells.push_back(mKdTree->GetBox(*it));
508               
509        float avgPvs = GetAvgPvsSize(rssTree, kdViewcells);
510        cout<<"Initial average PVS size = "<<avgPvs<<endl;
511  }
512
513       
514  int samples = 0;
515  int pass = 0;
516  while (1) {
517        int num = mRssSamplesPerPass;
518        SimpleRayContainer rays;
519        VssRayContainer vssRays;
520               
521        if (!mUseImportanceSampling) {
522          for (int j=0; j < num; j++) {
523                Vector3 viewpoint = GetViewpoint(mViewSpaceBox);
524                Vector3 direction = GetDirection(viewpoint, mViewSpaceBox);
525                rays.push_back(SimpleRay(viewpoint, direction));
526          }
527        } else {
528          num = GenerateImportanceRays(rssTree, num, rays);
529        }
530               
531               
532        for (int i=0; i < rays.size(); i++)
533          CastRay(rays[i].mOrigin, rays[i].mDirection, vssRays);
534               
535        rssTree->AddRays(vssRays);
536               
537        if (1) {
538          int subdivided = rssTree->UpdateSubdivision();
539          cout<<"subdivided leafs = "<<subdivided<<endl;
540        }
541
542        float avgPvs = GetAvgPvsSize(rssTree, kdViewcells);
543        cout<<"Average PVS size = "<<avgPvs<<endl;
544
545        if (numExportRays) {
546          char filename[64];
547          if (mUseImportanceSampling)
548                sprintf(filename, "rss-rays-i%04d.x3d", pass);
549          else
550                sprintf(filename, "rss-rays-%04d.x3d", pass);
551         
552          ExportRays(filename, vssRays, numExportRays);
553        }
554
555        //-- prepare traversal rays for view cell intersections
556        RayContainer passRays;
557
558        VssRayContainer::const_iterator it, it_end = vssRays.end();
559       
560        for (it = vssRays.begin(); it != it_end; ++ it)
561                passRays.push_back(new Ray(*(*it)));
562       
563        int sampleContributions = 0;
564        int contributingSamples = 0;
565
566        /// compute view cell contribution of rays
567        mViewCellsManager->ComputeSampleContributions(passRays,
568                                                                                                  sampleContributions,
569                                                                                                  contributingSamples);
570       
571        //-- save rays for post processing
572        if (((int)storedRays.size() < mViewCellsManager->GetPostProcessSamples()) ||
573                ((int)storedRays.size() < mViewCellsManager->GetVisualizationSamples()))
574        {
575                RayContainer::const_iterator it, it_end = passRays.end();
576
577                for (it = passRays.begin(); it != it_end; ++ it)
578                        storedRays.push_back(new Ray(*(*it)));
579        }
580        else
581        {
582                CLEAR_CONTAINER(passRays);
583        }
584
585        samples+=num;
586        float pvs = rssTree->GetAvgPvsSize();
587        cout<<"*****************************\n";
588        cout<<samples<<" avgPVS ="<<pvs<<endl;
589        cout<<"RssTree root PVS size = "<<rssTree->GetRootPvsSize()<<endl;
590        cout<<"*****************************\n";
591
592        if (exportPvs) {
593          char filename[64];
594          sprintf(filename, "rss-pvs-%04d.x3d", pass);
595          ExportPvs(filename, rssTree);
596        }
597
598        if (samples >= mRssSamples)
599          break;
600
601       
602        pass++;
603  }
604 
605  delete rssTree;
606 
607  return true;
608}
609
Note: See TracBrowser for help on using the repository browser.