source: trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp @ 489

Revision 489, 14.8 KB checked in by mattausch, 19 years ago (diff)

valid view point regions working now for bsp view cells (crit: maxpvs)

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