source: GTP/trunk/Lib/Vis/Preprocessing/src/RssPreprocessor.cpp @ 1876

Revision 1876, 23.8 KB checked in by bittner, 18 years ago (diff)

halton generator updates

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#include "RenderSimulator.h"
13#include "GlRenderer.h"
14#include "SamplingStrategy.h"
15#include "PreprocessorThread.h"
16
17
18namespace GtpVisibilityPreprocessor {
19
20
21  const bool pruneInvalidRays = false;
22 
23 
24#define ADD_RAYS_IN_PLACE 1
25 
26RssPreprocessor::RssPreprocessor():
27  mVssRays()
28{
29  // this should increase coherence of the samples
30  Environment::GetSingleton()->GetIntValue("RssPreprocessor.samplesPerPass", mSamplesPerPass);
31  Environment::GetSingleton()->GetIntValue("RssPreprocessor.initialSamples", mInitialSamples);
32  Environment::GetSingleton()->GetIntValue("RssPreprocessor.vssSamples", mRssSamples);
33  Environment::GetSingleton()->GetIntValue("RssPreprocessor.vssSamplesPerPass", mRssSamplesPerPass);
34  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.useImportanceSampling", mUseImportanceSampling);
35
36  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.useRssTree",
37                                                                                        mUseRssTree);
38
39  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.Export.pvs", mExportPvs);
40  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.Export.rssTree", mExportRssTree);
41  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.Export.rays", mExportRays);
42  Environment::GetSingleton()->GetIntValue("RssPreprocessor.Export.numRays", mExportNumRays);
43  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.useViewcells", mUseViewcells);
44  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.objectBasedSampling", mObjectBasedSampling);
45  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.directionalSampling", mDirectionalSampling);
46
47  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.loadInitialSamples", mLoadInitialSamples);
48
49  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.storeInitialSamples", mStoreInitialSamples);
50
51  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.updateSubdivision", mUpdateSubdivision);
52 
53  mRssTree = NULL;
54}
55
56
57int
58RssPreprocessor::GenerateRays(
59                                                          const int number,
60                                                          SamplingStrategy &strategy,
61                                                          SimpleRayContainer &rays)
62{
63  int result = 0;
64 
65  Debug<<"Generate rays...\n"<<flush;
66
67  switch (strategy.mType) {
68  case SamplingStrategy::RSS_BASED_DISTRIBUTION:
69  case SamplingStrategy::RSS_SILHOUETTE_BASED_DISTRIBUTION:
70                if (mRssTree) {
71                  result = GenerateImportanceRays(mRssTree, number, rays);
72                }
73                break;
74               
75  default:
76        result = Preprocessor::GenerateRays(number, strategy, rays);
77  }
78 
79  //  rays.NormalizePdf();
80  Debug<<"done.\n"<<flush;
81
82  return result;
83}
84
85
86
87
88RssPreprocessor::~RssPreprocessor()
89{
90  // mVssRays get deleted in the tree
91  //  CLEAR_CONTAINER(mVssRays);
92}
93
94
95
96void
97RssPreprocessor::ExportObjectRays(VssRayContainer &rays,
98                                                                  const int objectId)
99{
100  ObjectContainer::const_iterator oi;
101
102  Intersectable *object = NULL;
103  for (oi = mObjects.begin(); oi != mObjects.end(); ++oi)
104        if (objectId == (*oi)->GetId()) {
105          object = *oi;
106          break;
107        }
108
109  if (object == NULL)
110        return;
111 
112  VssRayContainer selectedRays;
113  VssRayContainer::const_iterator it= rays.begin(), it_end = rays.end();
114
115 
116  for (; it != it_end; ++it) {
117        if ((*it)->mTerminationObject == object)
118          selectedRays.push_back(*it);
119  }
120 
121
122  Exporter *exporter = Exporter::GetExporter("object-rays.x3d");
123  //    exporter->SetWireframe();
124  //    exporter->ExportKdTree(*mKdTree);
125  exporter->SetFilled();
126  exporter->ExportIntersectable(object);
127  exporter->ExportRays(selectedRays, RgbColor(1, 0, 0));
128 
129  delete exporter;
130 
131}
132
133
134int
135RssPreprocessor::GenerateImportanceRays(RssTree *rssTree,
136                                                                                const int desiredSamples,
137                                                                                SimpleRayContainer &rays
138                                                                                )
139{
140  int num;
141
142  rssTree->UpdateTreeStatistics();
143
144  cout<<
145        "#RSS_AVG_PVS_SIZE\n"<<rssTree->stat.avgPvsSize<<endl<<
146        "#RSS_AVG_RAYS\n"<<rssTree->stat.avgRays<<endl<<
147        "#RSS_AVG_RAY_CONTRIB\n"<<rssTree->stat.avgRayContribution<<endl<<
148        "#RSS_AVG_PVS_ENTROPY\n"<<rssTree->stat.avgPvsEntropy<<endl<<
149        "#RSS_AVG_RAY_LENGTH_ENTROPY\n"<<rssTree->stat.avgRayLengthEntropy<<endl<<
150        "#RSS_AVG_IMPORTANCE\n"<<rssTree->stat.avgImportance<<endl;
151 
152  if (0) {
153        float p = desiredSamples/(float)(rssTree->stat.avgRayContribution*rssTree->stat.Leaves());
154        num = rssTree->GenerateRays(p, rays);
155  } else {
156        int leaves = rssTree->stat.Leaves()/1;
157       
158        num = rssTree->GenerateRays(desiredSamples, leaves, rays);
159  }
160       
161       
162  return num;
163}
164
165
166bool
167RssPreprocessor::ExportRays(const char *filename,
168                                                        const VssRayContainer &vssRays,
169                                                        const int number
170                                                        )
171{
172  cout<<"Exporting vss rays..."<<endl<<flush;
173       
174  Exporter *exporter = NULL;
175  exporter = Exporter::GetExporter(filename);
176  if (0) {
177        exporter->SetWireframe();
178        exporter->ExportKdTree(*mKdTree);
179  }
180  exporter->SetFilled();
181  // $$JB temporarily do not export the scene
182  if (0)
183        exporter->ExportScene(mSceneGraph->GetRoot());
184  exporter->SetWireframe();
185
186  if (1) {
187        exporter->SetForcedMaterial(RgbColor(1,0,1));
188        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
189        exporter->ResetForcedMaterial();
190  }
191 
192  VssRayContainer rays;
193 
194  vssRays.SelectRays(number, rays);
195
196  exporter->ExportRays(rays, RgbColor(1, 0, 0));
197       
198  delete exporter;
199
200  cout<<"done."<<endl<<flush;
201
202  return true;
203}
204
205bool
206RssPreprocessor::ExportRayAnimation(const char *filename,
207                                                                        const vector<VssRayContainer> &vssRays
208                                                                        )
209{
210  cout<<"Exporting vss rays..."<<endl<<flush;
211       
212  Exporter *exporter = NULL;
213  exporter = Exporter::GetExporter(filename);
214  if (0) {
215        exporter->SetWireframe();
216        exporter->ExportKdTree(*mKdTree);
217  }
218  exporter->SetFilled();
219  // $$JB temporarily do not export the scene
220  if (1)
221        exporter->ExportScene(mSceneGraph->GetRoot());
222  exporter->SetWireframe();
223
224  if (1) {
225        exporter->SetForcedMaterial(RgbColor(1,0,1));
226        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
227        exporter->ResetForcedMaterial();
228  }
229 
230  exporter->ExportRaySets(vssRays, RgbColor(1, 0, 0));
231       
232  delete exporter;
233
234  cout<<"done."<<endl<<flush;
235
236  return true;
237}
238
239
240bool
241RssPreprocessor::ExportRssTree(char *filename,
242                                                           RssTree *tree,
243                                                           const Vector3 &dir
244                                                           )
245{
246  Exporter *exporter = Exporter::GetExporter(filename);
247  exporter->SetFilled();
248  exporter->ExportScene(mSceneGraph->GetRoot());
249  //  exporter->SetWireframe();
250  bool result = exporter->ExportRssTree2( *tree, dir );
251  delete exporter;
252  return result;
253}
254
255bool
256RssPreprocessor::ExportRssTreeLeaf(char *filename,
257                                                                   RssTree *tree,
258                                                                   RssTreeLeaf *leaf)
259{
260  Exporter *exporter = NULL;
261  exporter = Exporter::GetExporter(filename);
262  exporter->SetWireframe();
263  exporter->ExportKdTree(*mKdTree);
264       
265  exporter->SetForcedMaterial(RgbColor(0,0,1));
266  exporter->ExportBox(tree->GetBBox(leaf));
267  exporter->ResetForcedMaterial();
268       
269  VssRayContainer rays[4];
270  for (int i=0; i < leaf->rays.size(); i++) {
271        int k = leaf->rays[i].GetRayClass();
272        rays[k].push_back(leaf->rays[i].mRay);
273  }
274       
275  // SOURCE RAY
276  exporter->ExportRays(rays[0], RgbColor(1, 0, 0));
277  // TERMINATION RAY
278  exporter->ExportRays(rays[1], RgbColor(1, 1, 1));
279  // PASSING_RAY
280  exporter->ExportRays(rays[2], RgbColor(1, 1, 0));
281  // CONTAINED_RAY
282  exporter->ExportRays(rays[3], RgbColor(0, 0, 1));
283
284  delete exporter;
285  return true;
286}
287
288void
289RssPreprocessor::ExportRssTreeLeaves(RssTree *tree, const int number)
290{
291  vector<RssTreeLeaf *> leaves;
292  tree->CollectLeaves(leaves);
293
294  int num = 0;
295  int i;
296  float p = number / (float)leaves.size();
297  for (i=0; i < leaves.size(); i++) {
298        if (RandomValue(0,1) < p) {
299          char filename[64];
300          sprintf(filename, "rss-leaf-%04d.x3d", num);
301          ExportRssTreeLeaf(filename, tree, leaves[i]);
302          num++;
303        }
304        if (num >= number)
305          break;
306  }
307}
308
309
310float
311RssPreprocessor::GetAvgPvsSize(RssTree *tree,
312                                                           const vector<AxisAlignedBox3> &viewcells
313                                                           )
314{
315  vector<AxisAlignedBox3>::const_iterator it, it_end = viewcells.end();
316
317  int sum = 0;
318  for (it = viewcells.begin(); it != it_end; ++ it)
319        sum += tree->GetPvsSize(*it);
320       
321  return sum/(float)viewcells.size();
322}
323
324
325void
326RssPreprocessor::ExportPvs(char *filename,
327                                                   RssTree *rssTree
328                                                   )
329{
330  ObjectContainer pvs;
331  if (rssTree->CollectRootPvs(pvs)) {
332        Exporter *exporter = Exporter::GetExporter(filename);
333        exporter->SetFilled();
334        exporter->ExportGeometry(pvs);
335        exporter->SetWireframe();
336        exporter->ExportBox(rssTree->bbox);
337        exporter->ExportViewpoint(rssTree->bbox.Center(), Vector3(1,0,0));
338        delete exporter;
339  }
340}
341
342
343void
344RssPreprocessor::ComputeRenderError()
345{
346  // compute rendering error
347       
348  if (renderer && renderer->mPvsStatFrames) {
349        //      emit EvalPvsStat();
350        //      QMutex mutex;
351        //      mutex.lock();
352        //      renderer->mRenderingFinished.wait(&mutex);
353        //      mutex.unlock();
354       
355        renderer->EvalPvsStat();
356
357        mStats <<
358          "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
359          "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
360          "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
361          "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
362  }
363}
364
365void
366NormalizeRatios(vector<SamplingStrategy *> &distributions)
367{
368  int i;
369  float sumRatios = 0.0f;
370 
371  for (i=0; i < distributions.size(); i++)
372        sumRatios += distributions[i]->mRatio;
373
374 
375  if (sumRatios == 0.0f) {
376        for (i=0; i < distributions.size(); i++) {
377          distributions[i]->mRatio = 1.0f;
378          sumRatios += 1.0f;
379        }
380  }
381
382  for (i=0 ; i < distributions.size(); i++)
383        distributions[i]->mRatio/=sumRatios;
384
385#define MIN_RATIO 0.1f
386 
387  for (i = 0; i < distributions.size(); i++)
388        if (distributions[i]->mRatio < MIN_RATIO)
389          distributions[i]->mRatio = MIN_RATIO;
390
391
392  sumRatios = 0.0f;
393  for (i=0; i < distributions.size(); i++)
394        sumRatios += distributions[i]->mRatio;
395
396  for (i=0 ; i < distributions.size(); i++)
397        distributions[i]->mRatio/=sumRatios;
398 
399 
400  cout<<"New ratios: ";
401  for (i=0 ; i < distributions.size(); i++)
402        cout<<distributions[i]->mRatio<<" ";
403  cout<<endl;
404}
405
406void
407EvaluateRatios(vector<SamplingStrategy *> &distributions)
408{
409  // now evaluate the ratios for the next pass
410#define TIME_WEIGHT 0.0f
411  for (int i=0; i < distributions.size(); i++) {
412        distributions[i]->mRatio = distributions[i]->mContribution/
413          (TIME_WEIGHT*distributions[i]->mTime +
414           (1 - TIME_WEIGHT)*distributions[i]->mRays);
415
416#if 1
417        distributions[i]->mRatio = sqr(distributions[i]->mRatio);
418#endif
419  }
420}
421
422
423
424bool
425RssPreprocessor::ComputeVisibility()
426{
427
428  Debug << "type: rss" << endl;
429
430  cout<<"Rss Preprocessor started\n"<<flush;
431  //  cout<<"Memory/ray "<<sizeof(VssRay)+sizeof(RssTreeNode::RayInfo)<<endl;
432
433  Randomize(0);
434
435  if (1) {
436        Exporter *exporter = Exporter::GetExporter("samples.wrl");
437    exporter->SetFilled();
438        Halton<4> halton;
439
440//      for (int i=1; i < 7; i++)
441//        cout<<i<<" prime= "<<FindPrime(i)<<endl;
442       
443        Material mA, mB;
444        mA.mDiffuseColor = RgbColor(1, 0, 0);
445        mB.mDiffuseColor = RgbColor(0, 1, 0);
446       
447        for (int i=0; i < 10000; i++) {
448          float r[4];
449          halton.GetNext(r);
450          Vector3 v1 = UniformRandomVector(r[0], r[1]);
451          Vector3 v2 = UniformRandomVector(r[2], r[3]);
452
453          const float size =0.002f;
454          AxisAlignedBox3 box(v1-Vector3(size), v1+Vector3(size));
455          exporter->SetForcedMaterial(mA);
456          exporter->ExportBox(box);
457          AxisAlignedBox3 box2(v2-Vector3(size), v2+Vector3(size));
458
459          exporter->SetForcedMaterial(mB);
460          exporter->ExportBox(box2);
461        }
462        delete exporter;
463  }
464 
465 
466  cout<<"COMPUTATION THREAD="<<GetThread()->GetCurrentThreadId()<<endl<<flush;
467 
468  // use ray buffer to export ray animation
469  const bool useRayBuffer = true;
470 
471  vector<VssRayContainer> rayBuffer(50);
472 
473  long startTime = GetTime();
474  long lastTime;
475  float totalTime;
476 
477  int totalSamples = 0;
478
479  // if not already loaded, construct view cells from file
480  if (!mLoadViewCells)
481  {
482          // construct view cells using it's own set of samples
483          mViewCellsManager->Construct(this);
484
485          //-- several visualizations and statistics
486          Debug << "view cells construction finished: " << endl;
487          mViewCellsManager->PrintStatistics(Debug);
488  }
489
490 
491  int rssPass = 0;
492  int rssSamples = 0;
493
494  if (mUseRssTree)
495                mDistributions.push_back(new RssBasedDistribution(*this));
496
497 
498  if (1) {
499        // mDistributions.push_back(new SpatialBoxBasedDistribution(*this));
500        //  mDistributions.push_back(new DirectionBasedDistribution(*this));
501        mDistributions.push_back(new ObjectDirectionBasedDistribution(*this));
502        //  mDistributions.push_back(new ReverseObjectBasedDistribution(*this));
503        mDistributions.push_back(new ObjectBasedDistribution(*this));
504        mDistributions.push_back(new ReverseViewSpaceBorderBasedDistribution(*this));
505  } else {
506        mDistributions.push_back(new GlobalLinesDistribution(*this));
507        mDistributions.push_back(new SpatialBoxBasedDistribution(*this));
508  }
509 
510  if (mLoadInitialSamples) {
511        cout << "Loading samples from file ... ";
512        LoadSamples(mVssRays, mObjects);
513        cout << "finished\n" << endl;
514  } else {
515        SimpleRayContainer rays;
516       
517        cout<<"Generating initial rays..."<<endl<<flush;
518       
519        if (mUseImportanceSampling) {
520          int count = 0;
521          int i;
522
523          // Generate initial samples
524          for (i=0; i < mDistributions.size(); i++)
525                if (mDistributions[i]->mType != SamplingStrategy::RSS_BASED_DISTRIBUTION)
526                  count++;
527         
528          for (i=0; i < mDistributions.size(); i++)
529                if (mDistributions[i]->mType != SamplingStrategy::RSS_BASED_DISTRIBUTION)
530                  GenerateRays(mInitialSamples/count,
531                                           *mDistributions[i],
532                                           rays);
533         
534        } else {
535          int rayType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
536          if (mObjectBasedSampling)
537                rayType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
538          else
539                if (mDirectionalSampling)
540                  rayType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
541          cout<<"Generating rays..."<<endl;
542
543          Preprocessor::GenerateRays(mRssSamplesPerPass, rayType, rays);
544        }
545       
546       
547        cout<<"Casting initial rays..."<<endl<<flush;
548        CastRays(rays, mVssRays, true, pruneInvalidRays);
549
550        ExportObjectRays(mVssRays, 1546);
551  }
552 
553  cout << "#totalRayStackSize=" << (int)mVssRays.size() << endl <<flush;
554 
555  rssSamples += (int)mVssRays.size();
556  totalSamples += mInitialSamples;
557  mPass++;
558 
559  if (mExportRays) {
560       
561        char filename[64];
562        sprintf(filename, "rss-rays-initial.x3d");
563        ExportRays(filename, mVssRays, mExportNumRays);
564
565        if (useRayBuffer)
566          mVssRays.SelectRays(mExportNumRays, rayBuffer[0], true);
567       
568  }
569 
570  if (mStoreInitialSamples) {
571        cout << "Writing samples to file ... ";
572        ExportSamples(mVssRays);
573        cout << "finished\n" << endl;
574  }
575       
576  if (mUseViewcells) {
577
578        cout<<"Computing sample contributions..."<<endl<<flush;
579        // evaluate contributions of the intitial rays
580        mViewCellsManager->ComputeSampleContributions(mVssRays, true, false);
581        cout<<"done.\n"<<flush;
582
583        long time = GetTime();
584        totalTime = TimeDiff(startTime, time)*1e-3f;
585        lastTime = time;
586       
587        mStats <<
588          "#Pass\n" <<mPass<<endl<<
589          "#RssPass\n" <<rssPass<<endl<<
590          "#Time\n" << totalTime <<endl<<
591          "#TotalSamples\n" <<totalSamples<<endl<<
592          "#RssSamples\n" <<rssSamples<<endl;
593
594        {
595          VssRayContainer contributingRays;
596          mVssRays.GetContributingRays(contributingRays, 0);
597          mStats<<"#NUM_CONTRIBUTING_RAYS\n"<<(int)contributingRays.size()<<endl;
598          if (mExportRays) {
599                char filename[64];
600                sprintf(filename, "rss-crays-%04d.x3d", 0);
601                ExportRays(filename, contributingRays, mExportNumRays);
602          }
603        }
604       
605         
606        // viewcells->UpdatePVS(newVssRays);
607        Debug<<"Valid viewcells before set validity: "<<mViewCellsManager->CountValidViewcells()<<endl;
608        // cull viewcells with PVS > median (0.5f)
609        //mViewCellsManager->SetValidityPercentage(0, 0.5f);
610        //      mViewCellsManager->SetValidityPercentage(0, 1.0f);
611        Debug<<"Valid viewcells after set validity: "<<mViewCellsManager->CountValidViewcells()<<endl;
612
613        mVssRays.PrintStatistics(mStats);
614        mViewCellsManager->PrintPvsStatistics(mStats);
615
616
617        if (0) {
618          char str[64];
619          sprintf(str, "tmp/v-");
620         
621          // visualization
622          const bool exportRays = true;
623          const bool exportPvs = true;
624          ObjectContainer objects;
625          mViewCellsManager->ExportSingleViewCells(objects,
626                                                                                           1000,
627                                                                                           false,
628                                                                                           exportPvs,
629                                                                                           exportRays,
630                                                                                           10000,
631                                                                                           str);
632        }
633         
634        ComputeRenderError();
635  }
636
637  //  return 1;
638 
639  rssPass++;
640
641  //  mDistributions.resize(1);
642
643  mRssTree = new RssTree;
644  mRssTree->SetPass(mPass);
645 
646  /// compute view cell contribution of rays if view cells manager already constructed
647  //  mViewCellsManager->ComputeSampleContributions(mVssRays, true, false);
648
649  if (mUseImportanceSampling) {
650
651        if (mUseRssTree) {
652          mRssTree->Construct(mObjects, mVssRays);
653       
654          mRssTree->stat.Print(mStats);
655          cout<<"RssTree root PVS size = "<<mRssTree->GetRootPvsSize()<<endl;
656         
657          if (mExportRssTree) {
658                ExportRssTree("rss-tree-100.x3d", mRssTree, Vector3(1,0,0));
659                ExportRssTree("rss-tree-001.x3d", mRssTree, Vector3(0,0,1));
660                ExportRssTree("rss-tree-101.x3d", mRssTree, Vector3(1,0,1));
661                ExportRssTree("rss-tree-101m.x3d", mRssTree, Vector3(-1,0,-1));
662                ExportRssTreeLeaves(mRssTree, 10);
663          }
664        }
665
666        if (mExportPvs) {
667          ExportPvs("rss-pvs-initial.x3d", mRssTree);
668        }
669  }
670
671  // keep only rss
672  //  mDistributions.resize(1);
673
674  while (1) {
675
676        static SimpleRayContainer rays;
677        static VssRayContainer vssRays;
678        static VssRayContainer tmpVssRays;
679
680        rays.reserve((int)(1.1f*mRssSamplesPerPass));
681
682        rays.clear();
683        vssRays.clear();
684        tmpVssRays.clear();
685
686        int castRays = 0;
687        if (mUseImportanceSampling) {
688
689          NormalizeRatios(mDistributions);
690         
691          long t1;
692
693          for (int i=0; i < mDistributions.size(); i++) {
694                t1 = GetTime();
695                rays.clear();
696                tmpVssRays.clear();
697                if (mDistributions[i]->mRatio != 0) {
698                  GenerateRays(int(mRssSamplesPerPass*mDistributions[i]->mRatio),
699                                           *mDistributions[i],
700                                           rays);
701                 
702                  rays.NormalizePdf((float)rays.size());
703                 
704                  CastRays(rays, tmpVssRays, true, pruneInvalidRays);
705                  castRays += (int)rays.size();
706
707                  cout<<"Computing sample contributions..."<<endl<<flush;
708
709#if ADD_RAYS_IN_PLACE
710                  mDistributions[i]->mContribution =
711                        mViewCellsManager->ComputeSampleContributions(tmpVssRays, true, false);
712#else
713                  mDistributions[i]->mContribution =
714                        mViewCellsManager->ComputeSampleContributions(tmpVssRays, false, true);
715#endif
716                  cout<<"done."<<endl;
717                }
718
719                mDistributions[i]->mTime = TimeDiff(t1, GetTime());
720                //              mDistributions[i]->mRays = (int)rays.size();
721                mDistributions[i]->mRays = (int)tmpVssRays.size() + 1;
722                //              mStats<<"#RssRelContrib"<<endl<<contributions[0]/nrays[0]<<endl;
723                vssRays.insert(vssRays.end(), tmpVssRays.begin(), tmpVssRays.end() );
724          }
725
726          EvaluateRatios(mDistributions);
727         
728          // add contributions of all rays at once...
729#if !ADD_RAYS_IN_PLACE
730          mViewCellsManager->AddSampleContributions(vssRays);
731#endif   
732        }
733        else {
734                int rayType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
735          if (mObjectBasedSampling)
736                  rayType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
737          else
738                if (mDirectionalSampling)
739                        rayType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
740
741          cout<<"Generating rays..."<<endl;
742
743          Preprocessor::GenerateRays(mRssSamplesPerPass, rayType, rays);
744          cout<<"done."<<endl;
745
746          cout<<"Casting rays..."<<endl;          CastRays(rays, vssRays, true);
747          cout<<"done."<<endl;
748          castRays += (int)rays.size();
749          if (mUseViewcells) {
750                /// compute view cell contribution of rays
751                cout<<"Computing sample contributions..."<<endl;
752                mViewCellsManager->ComputeSampleContributions(vssRays, true, false);
753                cout<<"done."<<endl;
754          }
755               
756         
757        }
758        totalSamples += castRays;
759        rssSamples += (int)vssRays.size();
760
761        cout<<"Generated "<<castRays<<" rays, progress "<<100.0f*totalSamples/((float) mRssSamples +
762                                                                                                                                                   mInitialSamples)<<"%\n";
763       
764
765        long time = GetTime();
766        totalTime += TimeDiff(lastTime, time);
767        lastTime = time;
768       
769        mStats <<
770          "#Pass\n" <<mPass<<endl<<
771          "#RssPass\n" <<rssPass<<endl<<
772          "#Time\n" << TimeDiff(startTime, GetTime())*1e-3<<endl<<
773          "#TotalSamples\n" <<totalSamples<<endl<<
774          "#RssSamples\n" <<rssSamples<<endl;
775
776
777        if (mUseViewcells) {
778          Debug<<"Print statistics...\n"<<flush;
779          vssRays.PrintStatistics(mStats);
780          mViewCellsManager->PrintPvsStatistics(mStats);
781          Debug<<"done.\n"<<flush;
782        }
783
784
785        if (renderer && mPass > 0) {
786          char buf[100];
787          if (mUseImportanceSampling)
788                {
789                  sprintf(buf, "snap/i-%02d-", mPass);
790                 
791                  renderer->SetSnapPrefix(buf);
792                }
793          else
794                {
795                  sprintf(buf, "snap/r-%02d-", mPass);
796                 
797                  renderer->SetSnapPrefix(buf);
798                }
799         
800          renderer->SetSnapErrorFrames(true);
801        }
802       
803        ComputeRenderError();
804       
805        // epxort rays before adding them to the tree -> some of them can be deleted
806
807        if (mExportRays) {
808          char filename[64];
809          if (mUseImportanceSampling)
810                sprintf(filename, "rss-rays-i%04d.x3d", rssPass);
811          else
812                sprintf(filename, "rss-rays-%04d.x3d", rssPass);
813         
814         
815
816          if (useRayBuffer)
817                vssRays.SelectRays(mExportNumRays, rayBuffer[mPass], true);
818         
819          ExportRays(filename, vssRays, mExportNumRays);
820         
821          // now export all contributing rays
822          VssRayContainer contributingRays;
823          vssRays.GetContributingRays(contributingRays, mPass);
824          mStats<<"#NUM_CONTRIBUTING_RAYS\n"<<(int)contributingRays.size()<<endl;
825          sprintf(filename, "rss-crays-%04d.x3d", rssPass);
826          ExportRays(filename, contributingRays, mExportNumRays);
827        }
828
829       
830        // add rays to the tree after the viewcells have been cast to have their contributions
831        // already when adding into the tree
832        // do not add those rays which have too low or no contribution....
833
834       
835        if (mUseRssTree && mUseImportanceSampling) {
836          Debug<<"Adding rays...\n"<<flush;
837          mRssTree->AddRays(vssRays);
838          Debug<<"done.\n"<<flush;
839          if (mUpdateSubdivision) {
840                int updatePasses = 1;
841                if (mPass % updatePasses == 0) {
842                  Debug<<"Updating rss tree...\n"<<flush;
843                  int subdivided = mRssTree->UpdateSubdivision();
844                  Debug<<"done.\n"<<flush;
845                  cout<<"subdivided leafs = "<<subdivided<<endl;
846                  cout<<"#total leaves = "<<mRssTree->stat.Leaves()<<endl;
847                }
848          }
849        }
850       
851        if (mExportPvs) {
852          char filename[64];
853          sprintf(filename, "rss-pvs-%04d.x3d", rssPass);
854          ExportPvs(filename, mRssTree);
855        }
856       
857       
858        if (!mUseImportanceSampling || !mUseRssTree)
859          CLEAR_CONTAINER(vssRays);
860        // otherwise the rays get deleted by the rss tree update according to RssTree.maxRays ....
861       
862        if (totalSamples >= mRssSamples + mInitialSamples)
863          break;
864       
865       
866        rssPass++;
867        mPass++;
868        mRssTree->SetPass(mPass);
869  }
870 
871  if (mUseViewcells) {
872
873        if(0) {
874          VssRayContainer selectedRays;
875          int desired = mViewCellsManager->GetVisualizationSamples();
876         
877          mVssRays.SelectRays(desired, selectedRays);
878         
879          mViewCellsManager->Visualize(mObjects, selectedRays);
880          }
881       
882        // view cells after sampling
883        mViewCellsManager->PrintStatistics(Debug);
884       
885        EvalViewCellHistogram();
886       
887        //-- render simulation after merge
888        cout << "\nevaluating bsp view cells render time after sampling ... ";
889       
890        mRenderSimulator->RenderScene();
891        SimulationStatistics ss;
892        mRenderSimulator->GetStatistics(ss);
893       
894        cout << " finished" << endl;
895        cout << ss << endl;
896        Debug << ss << endl;
897  }
898
899
900  if (useRayBuffer && mExportRays && mUseImportanceSampling) {
901        char filename[64];
902        sprintf(filename, "rss-rays-i.x3d");
903       
904        rayBuffer.resize(mPass);
905        ExportRayAnimation(filename, rayBuffer);
906  }
907         
908
909  // do not delete rss tree now - can be used for visualization..
910#if 0
911  Debug<<"Deleting RSS tree...\n";
912  delete mRssTree;
913  Debug<<"Done.\n";
914#endif
915
916  //mViewCellsManager->ExportViewCells("visibility.xml",
917  //                                                                     true);
918 
919 
920  return true;
921}
922
923}
Note: See TracBrowser for help on using the repository browser.