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

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