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

Revision 1112, 24.6 KB checked in by bittner, 18 years ago (diff)

Merge with Olivers code

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