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

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