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

Revision 436, 15.5 KB checked in by mattausch, 19 years ago (diff)

bsptree view cells working in VssPreprocessor?

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