source: trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp @ 421

Revision 421, 29.3 KB checked in by mattausch, 19 years ago (diff)

fixed controls for terrain demo
fixed member names in vspkdtree

Line 
1#include "SceneGraph.h"
2#include "KdTree.h"
3#include "SamplingPreprocessor.h"
4#include "X3dExporter.h"
5#include "Environment.h"
6#include "MutualVisibility.h"
7#include "Polygon3.h"
8#include "ViewCell.h"
9#include "RenderSimulator.h"
10
11SamplingPreprocessor::SamplingPreprocessor(): mPass(0)
12{
13  // this should increase coherence of the samples
14  environment->GetIntValue("Sampling.samplesPerPass", mSamplesPerPass);
15  environment->GetIntValue("Sampling.totalSamples", mTotalSamples);
16  environment->GetIntValue("BspTree.Construction.samples", mBspConstructionSamples);
17  environment->GetIntValue("VspKdTree.Construction.samples", mVspConstructionSamples);
18  environment->GetIntValue("ViewCells.PostProcessing.samples", mPostProcessSamples);
19  environment->GetIntValue("BspTree.Visualization.samples", mVisualizationSamples);
20 
21  mKdPvsDepth = 100;
22  mStats.open("stats.log");
23}
24
25SamplingPreprocessor::~SamplingPreprocessor()
26{
27        CLEAR_CONTAINER(mSampleRays);
28        CLEAR_CONTAINER(mVspSampleRays);
29}
30
31void
32SamplingPreprocessor::SetupRay(Ray &ray,
33                                                                                                                         const Vector3 &point,
34                                                                                                                         const Vector3 &direction,
35                                                                                                                         const int type)
36{
37  ray.intersections.clear();
38  ray.kdLeaves.clear();
39  ray.testedObjects.clear();
40  ray.bspIntersections.clear();
41        ray.mFlags |= Ray::STORE_KDLEAVES | Ray::STORE_BSP_INTERSECTIONS;
42  //  cout<<point<<" "<<direction<<endl;
43  ray.Init(point, direction, type);
44}
45
46KdNode *
47SamplingPreprocessor::GetNodeForPvs(KdLeaf *leaf)
48{
49  KdNode *node = leaf;
50  while (node->mParent && node->mDepth > mKdPvsDepth)
51    node = node->mParent;
52  return node;
53}
54
55bool
56SamplingPreprocessor::BuildBspTree()
57{
58        // delete old tree
59        DEL_PTR(mBspTree);
60        mBspTree = new BspTree(&mUnbounded);
61        ObjectContainer objects;
62       
63        switch (BspTree::sConstructionMethod)
64        {
65        case BspTree::FROM_INPUT_VIEW_CELLS:
66                mBspTree->SetGenerateViewCells(false);
67                mBspTree->Construct(mViewCells);
68                break;
69        case BspTree::FROM_SCENE_GEOMETRY:
70                DeleteViewCells(); // we generate new view cells
71                mBspTree->SetGenerateViewCells(true);
72                mSceneGraph->CollectObjects(&objects);
73                mBspTree->Construct(objects);
74                break;
75        case BspTree::FROM_RAYS:
76                DeleteViewCells(); // we generate new view cells
77                mBspTree->SetGenerateViewCells(true);
78                mBspTree->Construct(mSampleRays);
79                break;
80        default:
81                Debug << "Error: Method not available\n";
82                break;
83        }
84       
85       
86        return true;
87}
88
89int
90SamplingPreprocessor::AddNodeSamples(const Ray &ray,
91                                                                                                                                                 Intersectable *sObject,
92                                                                                                                                                 Intersectable *tObject
93                                                                                                                                                 )
94{
95  int contributingSamples = 0;
96  int j;
97        int objects = 0;
98        if (sObject)
99                objects++;
100        if (tObject)
101                objects++;
102
103        if (objects) {
104                for (j=0; j < ray.kdLeaves.size(); j++) {
105                        KdNode *node = GetNodeForPvs( ray.kdLeaves[j] );
106                        if (sObject)
107                                contributingSamples += sObject->mKdPvs.AddSample(node);
108                        if (tObject)
109                                contributingSamples += tObject->mKdPvs.AddSample(node);
110                }
111        }
112       
113        for (j=1; j < ((int)ray.kdLeaves.size() - 1); j++) {
114                ray.kdLeaves[j]->AddPassingRay2(ray,
115                                                                                                                                                objects,
116                                                                                                                                                ray.kdLeaves.size()
117                                                                                                                                                );
118  }
119 
120  return contributingSamples;
121}
122
123
124int SamplingPreprocessor::AddObjectSamples(Intersectable *obj, const Ray &ray)
125{
126        int contributingSamples = 0;
127        int j;
128 
129        // object can be seen from the view cell => add to view cell pvs
130        for (j=0; j < ray.bspIntersections.size(); ++ j)
131        {       
132                BspLeaf *leaf = ray.bspIntersections[j].mLeaf;
133                // if ray not in unbounded space
134                if (leaf->GetViewCell() != &mUnbounded)
135                        contributingSamples +=
136                                leaf->GetViewCell()->GetPvs().AddSample(obj);
137        }
138 
139        // rays passing through this viewcell
140        if (mPass > 1)
141                for (j=1; j < ((int)ray.bspIntersections.size() - 1); ++ j)
142                {
143                        BspLeaf *leaf = ray.bspIntersections[j].mLeaf;
144
145                        if (leaf->GetViewCell() != &mUnbounded)
146                                leaf->GetViewCell()->
147                                        AddPassingRay(ray, contributingSamples ? 1 : 0);
148                }
149 
150        return contributingSamples;
151}
152
153
154void
155SamplingPreprocessor::HoleSamplingPass()
156{
157  vector<KdLeaf *> leaves;
158  mKdTree->CollectLeaves(leaves);
159 
160  // go through all the leaves and evaluate their passing contribution
161  for (int i=0 ; i < leaves.size(); i++) {
162    KdLeaf *leaf = leaves[i];
163    cout<<leaf->mPassingRays<<endl;
164  }
165}
166
167
168int
169SamplingPreprocessor::CastRay(Intersectable *object, Ray &ray)
170{
171        int sampleContributions = 0;
172
173        long t1 = GetRealTime();
174        // cast ray to KD tree to find intersection with other objects
175        mKdTree->CastRay(ray);
176        long t2 = GetRealTime();
177
178        if (0 && object && object->GetId() > 2197) {
179                object->Describe(cout)<<endl;
180                cout<<ray<<endl;
181        }
182
183        switch(ViewCell::sHierarchy)
184        {
185        case ViewCell::BSP:
186               
187                //-- cast ray to BSP tree to get intersection with view cells
188                if (!mBspTree)
189                        break;
190               
191                mBspTree->CastRay(ray);
192                       
193                if (object)
194                        sampleContributions += AddObjectSamples(object, ray);
195                       
196                if (!ray.intersections.empty()) // second intersection found
197                {
198                        sampleContributions +=
199                                AddObjectSamples(ray.intersections[0].mObject, ray);
200                }
201                break;
202        case ViewCell::KD:
203                if (ray.kdLeaves.size())
204                {
205                        Intersectable *terminator =
206                                ray.intersections.size() ? ray.intersections[0].mObject: NULL;
207
208                        sampleContributions += AddNodeSamples(ray,
209                                                                                                                                                                        object,
210                                                                                                                                                                        terminator);
211                }
212                break;
213        case ViewCell::VSP:
214                // TODO:
215                break;
216        default:
217                Debug << "Should never come here" << endl;
218                break;
219        }
220
221        return sampleContributions;
222}
223
224//  void
225//  SamplingPreprocessor::AvsGenerateRandomRay(Ray &ray)
226//  {
227//    int objId = RandomValue(0, mObjects.size());
228//    Intersectable *object = objects[objId];
229//    object->GetRandomSurfacePoint(point, normal);
230//    direction = UniformRandomVector(normal);
231//    SetupRay(ray, point, direction);
232//  }
233
234//  void
235//  SamplingPreprocessor::AvsHandleRay(Ray &ray)
236//  {
237//    int sampleContributions = 0;
238
239//    mKdTree->CastRay(ray);
240 
241//    if (ray.leaves.size()) {
242//      sampleContributions += AddNodeSamples(object, ray, pass);
243   
244//      if (ray.intersections.size()) {
245//        sampleContributions += AddNodeSamples(ray.intersections[0].mObject, ray, pass);
246//      }
247//    }
248//  }
249
250//  void
251//  SamplingPreprocessor::AvsBorderSampling(Ray &ray)
252//  {
253 
254
255//  }
256
257//  void
258//  SamplingPreprocessor::AvsPass()
259//  {
260//    Ray ray;
261//    while (1) {
262//      AvsGenerateRay(ray);
263//      HandleRay(ray);
264//      while ( !mRayQueue.empty() ) {
265//        Ray ray = mRayQueue.pop();
266//        mRayQueue.pop();
267//        AdaptiveBorderSampling(ray);
268//      }
269//    }
270 
271 
272
273//  }
274
275
276int
277SamplingPreprocessor::CastEdgeSamples(
278                                                                                                                                                        Intersectable *object,
279                                                                                                                                                        const Vector3 &point,
280                                                                                                                                                        MeshInstance *mi,
281                                                                                                                                                        const int samples
282                                                                                                                                                        )
283{
284        Ray ray;
285        int maxTries = samples*10;
286        int i;
287        int rays = 0;
288        int edgeSamplesContributions = 0;
289        for (i=0; i < maxTries && rays < samples; i++) {
290                // pickup a random face of each mesh
291                Mesh *mesh = mi->GetMesh();
292                int face = RandomValue(0, mesh->mFaces.size()-1);
293               
294                Polygon3 poly(mesh->mFaces[face], mesh);
295                poly.Scale(1.001);
296                // now extend a random edge of the face
297                int edge = RandomValue(0, poly.mVertices.size()-1);
298                float t = RandomValue(0.0f,1.0f);
299                Vector3 target = t*poly.mVertices[edge] + (1.0f-t)*poly.mVertices[(edge + 1)%
300                                                                                                                                                                                                                                                                                 poly.mVertices.size()];
301                SetupRay(ray, point, target - point, Ray::LOCAL_RAY);
302                if (!mesh->CastRay(ray, mi)) {
303                        // the rays which intersect the mesh have been discarded since they are not tangent
304                        // to the mesh
305                        rays++;
306                        edgeSamplesContributions += CastRay(object, ray);
307                }
308        }
309        return edgeSamplesContributions;
310}
311
312KdNode *
313SamplingPreprocessor::GetNodeToSample(Intersectable *object)
314{
315        int pvsSize = object->mKdPvs.GetSize();
316        KdNode *nodeToSample = NULL;
317       
318        bool samplePvsBoundary = false;
319        if (pvsSize && samplePvsBoundary) {
320                // this samples the nodes from the boundary of the current PVS
321                // mail all nodes from the pvs
322                Intersectable::NewMail();
323                KdPvsMap::iterator i = object->mKdPvs.mEntries.begin();
324               
325                for (; i != object->mKdPvs.mEntries.end(); i++) {
326                        KdNode *node = (*i).first;
327                        node->Mail();
328                }
329               
330                int maxTries = 2*pvsSize;
331                Debug << "Finding random neighbour" << endl;   
332                for (int tries = 0; tries < 10; tries++) {
333                        int index = RandomValue(0, pvsSize - 1);
334                        KdPvsData data;
335                        KdNode *node;
336                        object->mKdPvs.GetData(index, node, data);
337                        nodeToSample = mKdTree->FindRandomNeighbor(node, true);
338                        if (nodeToSample)
339                                break;
340                }
341        } else {
342                // just pickup a random node
343                //              nodeToSample = mKdTree->GetRandomLeaf(Plane3(normal, point));
344                nodeToSample = mKdTree->GetRandomLeaf();
345        }
346        return nodeToSample;
347}
348
349void
350SamplingPreprocessor::VerifyVisibility(Intersectable *object)
351{
352        // mail all nodes from the pvs
353        Intersectable::NewMail();
354        KdPvsMap::iterator i = object->mKdPvs.mEntries.begin();
355        for (; i != object->mKdPvs.mEntries.end(); i++) {
356                KdNode *node = (*i).first;
357                node->Mail();
358        }
359        Debug << "Get all neighbours from PVS" << endl;
360        vector<KdNode *> invisibleNeighbors;
361        // get all neighbors of all PVS nodes
362        i = object->mKdPvs.mEntries.begin();
363        for (; i != object->mKdPvs.mEntries.end(); i++) {
364                KdNode *node = (*i).first;
365                mKdTree->FindNeighbors(node, invisibleNeighbors, true);
366                AxisAlignedBox3 box = object->GetBox();
367                for (int j=0; j < invisibleNeighbors.size(); j++) {
368                        int visibility = ComputeBoxVisibility(mSceneGraph,
369                                                              mKdTree,
370                                                              box,
371                                                              mKdTree->GetBox(invisibleNeighbors[j]),
372                                                              1e-6f);
373                        //            exit(0);
374                }
375                // now rank all the neighbors according to probability that a new
376                // sample creates some contribution
377        }
378}
379
380bool
381SamplingPreprocessor::ComputeVisibility()
382{
383 
384  // pickup an object
385  ObjectContainer objects;
386 
387  mSceneGraph->CollectObjects(&objects);
388
389  Vector3 point, normal, direction;
390  Ray ray;
391
392  long startTime = GetTime();
393 
394  int i;
395  int totalSamples = 0;
396
397  int pvsOut = Min((int)objects.size(), 10);
398  int pvsSize = 0;
399
400  RayContainer rays[10];
401
402  while (totalSamples < mTotalSamples) {
403                int passContributingSamples = 0;
404                int passSampleContributions = 0;
405                int passSamples = 0;
406                int index = 0;
407               
408                int reverseSamples = 0;
409               
410                       
411                //cout << "totalSamples: "  << totalSamples << endl;
412
413                for (i = 0; i < objects.size(); i++) {
414                                               
415                        KdNode *nodeToSample = NULL;
416                        Intersectable *object = objects[i];
417               
418                        int pvsSize = 0;
419                        if (ViewCell::sHierarchy == ViewCell::KD)
420                                pvsSize = object->mKdPvs.GetSize();
421                                               
422                       
423                        if (0 && pvsSize && mPass == 1000 ) {
424                                VerifyVisibility(object);
425                        }
426                       
427                        int faceIndex = object->GetRandomSurfacePoint(point, normal);
428                       
429                        bool viewcellSample = true;
430                        int sampleContributions;
431                        bool debug = false; //(object->GetId() >= 2199);
432                        if (viewcellSample) {
433                                //mKdTree->GetRandomLeaf(Plane3(normal, point));
434
435                                nodeToSample = GetNodeToSample(object);
436
437                                for (int k=0; k < mSamplesPerPass; k++) {
438                                        bool reverseSample = false;
439                                       
440
441                                        if (nodeToSample) {
442                                                AxisAlignedBox3 box = mKdTree->GetBox(nodeToSample);
443                                                Vector3 pointToSample = box.GetRandomPoint();
444                                                //                                              pointToSample.y = 0.9*box.Min().y + 0.1*box.Max().y;
445                                                if (object->GetRandomVisibleSurfacePoint( point, normal, pointToSample, 3 )) {
446                                                        direction = pointToSample - point;
447                                                } else {
448                                                        reverseSamples++;
449                                                        reverseSample = true;
450                                                        direction = point - pointToSample;
451                                                        point = pointToSample;
452                                                }
453                                        }
454                                        else {
455                                                direction = UniformRandomVector(normal);
456                                        }
457                                       
458                                        // construct a ray
459                                        SetupRay(ray, point, direction, Ray::LOCAL_RAY);
460                                       
461                                        sampleContributions = CastRay(reverseSample ? NULL : object, ray);
462                                       
463                                        //-- CORR matt: put block inside loop
464                                        if (sampleContributions) {
465                                                passContributingSamples ++;
466                                                passSampleContributions += sampleContributions;
467                                        }
468
469                                        if ( i < pvsOut ) {
470                                                Ray *nray = new Ray(ray);
471                                                rays[i].push_back(nray);
472                                        }
473               
474                                        if (!ray.intersections.empty()) {
475                                                // check whether we can add this to the rays
476                                                for (int j = 0; j < pvsOut; j++) {
477                                                        if (objects[j] == ray.intersections[0].mObject) {
478                                                                Ray *nray = new Ray(ray);
479                                                                rays[j].push_back(nray);
480                                                        }
481                                                }
482                                        }
483                                        //-------------------
484                                        if (ViewCell::sHierarchy == ViewCell::BSP)
485                                        {
486                                                ProcessBspViewCells(ray,
487                                                                                        reverseSample ? NULL : object,
488                                                                                        faceIndex,
489                                                                                        passContributingSamples,
490                                                                                        passSampleContributions);
491
492                                                //mVspKdTree->Construct(mSampleRays, mBoundingBox);
493                                        }
494                                        else if (ViewCell::sHierarchy == ViewCell::VSP)
495                                        {
496                                                ProcessVspViewCells(ray,
497                                                                                        reverseSample ? NULL : object,
498                                                                                        faceIndex,
499                                                                                        passContributingSamples,
500                                                                                        passSampleContributions);
501                                        }
502                                }
503                        } else {
504                                // edge samples
505                                // get random visible mesh
506                                //                              object->GetRandomVisibleMesh(Plane3(normal, point));
507                        }
508       
509                        // CORR matt: must add all samples
510                        passSamples += mSamplesPerPass;
511                }
512       
513                totalSamples += passSamples;
514               
515                //    if (pass>10)
516                //      HoleSamplingPass();
517   
518                mPass++;
519       
520                if (ViewCell::sHierarchy == ViewCell::KD)
521                {
522                        pvsSize = 0;
523
524                        for (i=0; i < objects.size(); i++) {
525                                Intersectable *object = objects[i];
526                                pvsSize += object->mKdPvs.GetSize();
527                        }
528                }
529                else
530                        pvsSize += passSampleContributions;
531               
532                float avgRayContrib = (passContributingSamples > 0) ?
533                        passSampleContributions/(float)passContributingSamples : 0;
534
535                cout << "#Pass " << mPass << " : t = " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
536                cout << "#TotalSamples=" << totalSamples/1000
537                                 << "k   #SampleContributions=" << passSampleContributions << " ("
538                                 << 100*passContributingSamples/(float)passSamples<<"%)" << " avgPVS="
539                                 << (float)pvsSize /(float)objects.size() << endl
540                                 << "avg ray contrib=" << avgRayContrib << endl
541                                 << "reverse samples [%]" << reverseSamples/(float)passSamples*100.0f << endl;
542
543                mStats <<
544                        "#Pass\n" <<mPass<<endl<<
545                        "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl<<
546                        "#TotalSamples\n" << totalSamples<< endl<<
547                        "#SampleContributions\n" << passSampleContributions << endl <<
548                        "#PContributingSamples\n"<<100*passContributingSamples/(float)passSamples<<endl <<
549                        "#AvgPVS\n"<< pvsSize/(float)objects.size() << endl <<
550                        "#AvgRayContrib\n" << avgRayContrib << endl;
551        }
552       
553        if (ViewCell::sHierarchy == ViewCell::KD)       
554                cout << "#totalKdPvsSize=" << mKdTree->CollectLeafPvs() << endl;
555 
556        //-- render simulation
557        cout << "\nevaluating bsp view cells render time before merge ... ";
558        GetRenderSimulator()->SimulateRendering();
559       
560        cout << " finished" << endl;
561
562        cout << GetRenderSimulator()->mStat << endl;
563        Debug << GetRenderSimulator()->mStat << endl;
564
565
566        if (mBspTree)
567        {
568                //-- post processing of bsp view cells
569        int vcSize = 0;
570                int pvsSize = 0;
571
572                BspViewCellsStatistics stat;
573               
574                Debug << "overall scene size: " << (int)objects.size() << endl;
575                mBspTree->EvaluateViewCellsStats(stat);
576               
577                Debug << "original view cell partition:\n" << stat << endl;
578               
579                if (1) // export view cells
580                {
581                        cout << "exporting initial view cells (=leaves) ... ";
582                        Exporter *exporter = Exporter::GetExporter("view_cells.x3d");
583                        if (exporter)
584                        {
585                                exporter->SetWireframe();
586                                exporter->ExportBspLeaves(*mBspTree, stat.maxPvs);
587                                //exporter->ExportBspViewCellPartition(*mBspTree, 0);
588                               
589                                if (1) // export scene geometry
590                                {
591                                        Material m;//= RandomMaterial();
592                                        m.mDiffuseColor = RgbColor(0, 1, 0);
593                                        exporter->SetForcedMaterial(m);
594                                        exporter->SetWireframe();
595       
596                                        for (int j = 0; j < objects.size(); ++ j)
597                                                exporter->ExportIntersectable(objects[j]);
598                                }
599                                       
600                                delete exporter;
601                        }
602                        cout << "finished" << endl;
603                }
604
605                cout << "starting post processing using " << mPostProcessSamples << " samples ... ";
606               
607                long startTime = GetTime();
608                int merged = PostprocessViewCells(mSampleRays);
609               
610                cout << "finished" << endl;
611                cout << "merged " << merged << " view cells in "
612                         << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
613
614                //-- recount pvs
615                mBspTree->EvaluateViewCellsStats(stat);
616               
617                Debug << "after post processing:\n" << stat << endl;
618
619                //-- render simulation
620                cout << "\nevaluating render time after merge ... ";
621                       
622                GetRenderSimulator()->SimulateRendering();
623                cout << " finished" << endl;
624
625                cout << GetRenderSimulator()->mStat << endl;
626                Debug << GetRenderSimulator()->mStat << endl;
627
628                if (1) // export view cells
629                {
630                        cout << "exporting view cells after merge ... ";
631                        Exporter *exporter = Exporter::GetExporter("merged_view_cells.x3d");
632                        if (exporter)
633                        {
634                                exporter->ExportBspViewCellPartition(*mBspTree, stat.maxPvs);
635                                //exporter->ExportBspViewCellPartition(*mBspTree, 0);
636                                delete exporter;
637                        }
638
639                        cout << "finished" << endl;
640                }
641
642                //-- visualization of the BSP splits
643                bool exportSplits = false;
644                environment->GetBoolValue("BspTree.Visualization.exportSplits", exportSplits);
645               
646                cout << "exporting splits ... ";
647                if (exportSplits)
648                        ExportSplits(objects);
649                cout << "finished" << endl;
650
651                // export the PVS of sample view cells
652                if (1)
653                        ExportBspPvs(objects);
654        }
655       
656  //  HoleSamplingPass();
657        if (0) {
658                Exporter *exporter = Exporter::GetExporter("ray-density.x3d");
659                exporter->SetExportRayDensity(true);
660                exporter->ExportKdTree(*mKdTree);
661
662                if (mBspTree && (ViewCell::sHierarchy == ViewCell::VSP))
663                        exporter->ExportVspKdTree(*mVspKdTree);
664
665                delete exporter;
666        }
667 
668        bool exportRays = false;
669        if (exportRays) {
670                Exporter *exporter = NULL;
671                exporter = Exporter::GetExporter("sample-rays.x3d");
672                exporter->SetWireframe();
673                exporter->ExportKdTree(*mKdTree);
674                exporter->ExportBspTree(*mBspTree);
675
676                for (i=0; i < pvsOut; i++)
677                        exporter->ExportRays(rays[i], 1000, RgbColor(1, 0, 0));
678                exporter->SetFilled();
679               
680                delete exporter;
681        }
682
683        //-- several visualizations and statistics
684        if (1) {
685
686   for (int k=0; k < pvsOut; k++) {
687                 Intersectable *object = objects[k];
688                 char s[64];
689                 sprintf(s, "sample-pvs%04d.x3d", k);
690                 Exporter *exporter = Exporter::GetExporter(s);
691                 exporter->SetWireframe();
692                 
693                 
694                 KdPvsMap::iterator i = object->mKdPvs.mEntries.begin();
695                 Intersectable::NewMail();
696                 
697                 // avoid adding the object to the list
698                 object->Mail();
699                 ObjectContainer visibleObjects;
700                 
701                 for (; i != object->mKdPvs.mEntries.end(); i++)
702                         {
703                                 KdNode *node = (*i).first;
704                                 exporter->ExportBox(mKdTree->GetBox(node));
705                                 mKdTree->CollectObjects(node, visibleObjects);
706                         }
707                 
708                 exporter->ExportRays(rays[k], 1000, RgbColor(0, 1, 0));
709                 exporter->SetFilled();
710                 
711                 for (int j = 0; j < visibleObjects.size(); j++)
712                         exporter->ExportIntersectable(visibleObjects[j]);
713                 
714                 
715                 Material m;
716                 m.mDiffuseColor = RgbColor(1, 0, 0);
717                 exporter->SetForcedMaterial(m);
718                 exporter->ExportIntersectable(object);
719                 
720                 delete exporter;
721         }
722  }
723 
724  return true;
725}
726
727
728void SamplingPreprocessor::ProcessVspViewCells(const Ray &ray,
729                                               Intersectable *object,
730                                                                                           const int faceIndex,
731                                                                                           int &contributingSamples,
732                                                                                           int &sampleContributions)
733{
734        // save rays for bsp tree construction
735        if (!mVspKdTree)
736        {
737                if ((int)mVspSampleRays.size() < mVspConstructionSamples)
738                {
739                        MeshInstance *mi = dynamic_cast<MeshInstance *>(object);
740                       
741                        VssRay *sRay = new VssRay(ray);
742                        mVspSampleRays.push_back(sRay);
743               
744                        // also add origin to sample
745                        sRay->mOriginObject = object;
746                }
747                else
748                {
749                        // construct VSP tree using the collected samples
750                        cout << "building VSP tree from " << (int)mVspSampleRays.size() << " samples " << endl;
751                        mVspKdTree->Construct(mVspSampleRays);
752               
753                        // add contributions of saved samples to PVS
754                        //contributingSamples += mBspTree->GetStat().contributingSamples;
755                        //sampleContributions += mBspTree->GetStat().sampleContributions;
756
757                        Debug << mVspKdTree->GetStatistics();
758
759                        // throw away samples because BSP leaves not stored in order
760                        // Need ordered rays for post processing => collect new rays
761                        //CLEAR_CONTAINER(mVspSampleRays);
762                }
763        }
764        // save rays for post processing
765        /*else if (((int)mVspSampleRays.size() < mPostProcessSamples) ||
766                         ((int)mVspSampleRays.size() < mVisualizationSamples))
767        {
768                mVspSampleRays.push_back(new Ray(ray));
769        }*/
770}
771
772void SamplingPreprocessor::ProcessBspViewCells(const Ray &ray,
773                                               Intersectable *object,
774                                                                                           const int faceIndex,
775                                                                                           int &contributingSamples,
776                                                                                           int &sampleContributions)
777{
778        // save rays for bsp tree construction
779        if (!mBspTree)
780        {
781                if ((BspTree::sConstructionMethod == BspTree::FROM_RAYS) &&
782                        ((int)mSampleRays.size() < mBspConstructionSamples))
783                {
784                        MeshInstance *mi = dynamic_cast<MeshInstance *>(object);
785                       
786                        Ray *sRay = new Ray(ray);
787                        mSampleRays.push_back(sRay);
788               
789                        // also add origin to sample
790                        sRay->sourceObject = Ray::Intersection(0.0, object, faceIndex);
791                }
792                else
793                {
794                        // construct BSP tree using the collected samples
795                        cout << "building bsp tree from " << (int)mSampleRays.size() << " samples " << endl;
796                        BuildBspTree();
797               
798                        // add contributions of saved samples to PVS
799                        contributingSamples += mBspTree->GetStat().contributingSamples;
800                        sampleContributions += mBspTree->GetStat().sampleContributions;
801
802                        BspTreeStatistics(Debug);
803
804                        if (0) Export("vc_bsptree.x3d", false, false, true);
805
806                        // throw away samples because BSP leaves not stored in order
807                        // Need ordered rays for post processing => collect new rays
808                        CLEAR_CONTAINER(mSampleRays);
809                }
810        }
811        // save rays for post processing
812        else if (((int)mSampleRays.size() < mPostProcessSamples) ||
813                         ((int)mSampleRays.size() < mVisualizationSamples))
814        {
815                mSampleRays.push_back(new Ray(ray));
816        }
817}
818
819// merge or subdivide view cells
820int SamplingPreprocessor::PostprocessViewCells(const RayContainer &rays)
821{
822        int merged = 0;
823
824        RayContainer::const_iterator rit, rit_end = rays.end();
825        vector<Ray::BspIntersection>::const_iterator iit;
826
827        int limit = min((int)mSampleRays.size(), mPostProcessSamples);
828
829        for (int i = 0; i < limit; ++ i)
830        { 
831                Ray *ray = mSampleRays[i];
832
833                // traverse leaves stored in the rays and compare and merge consecutive
834                // leaves (i.e., the neighbors in the tree)
835                if (ray->bspIntersections.size() < 2)
836                        continue;
837
838                iit = ray->bspIntersections.begin();
839
840                BspLeaf *previousLeaf = (*iit).mLeaf;
841                ++ iit;
842               
843                for (; iit != ray->bspIntersections.end(); ++ iit)
844                {
845                        BspLeaf *leaf = (*iit).mLeaf;
846
847                        if (mBspTree->ShouldMerge(leaf, previousLeaf))
848                        {                       
849                                mBspTree->MergeViewCells(leaf, previousLeaf);
850
851                                ++ merged;
852                        }
853               
854                        previousLeaf = leaf;
855                }
856        }
857
858        return merged;
859}
860
861void SamplingPreprocessor::ExportSplits(const ObjectContainer &objects)
862{
863        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
864
865        if (exporter)
866        {       
867                Material m;
868                m.mDiffuseColor = RgbColor(1, 0, 0);
869                exporter->SetForcedMaterial(m);
870                exporter->SetWireframe();
871                exporter->ExportBspSplits(*mBspTree, true);
872
873                // take forced material, else big scenes cannot be viewed
874                m.mDiffuseColor = RgbColor(0, 1, 0);
875                exporter->SetForcedMaterial(m);
876                exporter->SetFilled();
877
878                exporter->ResetForcedMaterial();
879               
880                // export rays
881                if (0)
882                {
883                        RayContainer outRays;
884               
885                        for (int i = 0; i < mSampleRays.size(); ++ i)
886                        {
887                                // only rays piercing geometry
888                                if (!mSampleRays[i]->intersections.empty())
889                                        outRays.push_back(mSampleRays[i]);
890                        }
891                        if (BspTree::sConstructionMethod == BspTree::FROM_RAYS)
892                        {
893                                // export rays
894                                exporter->ExportRays(outRays, 1000, RgbColor(1, 1, 0));
895                        }
896                }
897
898                // export scene geometry
899                if (1)
900                {
901                        Material m;//= RandomMaterial();
902                        m.mDiffuseColor = RgbColor(0, 1, 0);
903                        exporter->SetForcedMaterial(m);
904            exporter->SetWireframe();
905
906                        for (int j = 0; j < objects.size(); ++ j)
907                                exporter->ExportIntersectable(objects[j]);
908                }
909
910                delete exporter;
911        }
912}
913
914inline bool vc_gt(ViewCell *a, ViewCell *b)
915{
916        return a->GetPvs().GetSize() > b->GetPvs().GetSize();
917}
918
919void SamplingPreprocessor::ExportBspPvs(const ObjectContainer &objects)
920{
921        const int leafOut = 10;
922       
923        ViewCell::NewMail();
924
925        //-- some rays for output
926        const int raysOut = min((int)mSampleRays.size(), mVisualizationSamples);
927        cout << "visualization using " << mVisualizationSamples << " samples" << endl;
928        vector<Ray *> vcRays[leafOut];
929
930        if (0){
931                //-- some random view cells and rays for output
932                vector<BspLeaf *> bspLeaves;
933
934                for (int i = 0; i < leafOut; ++ i)
935                        bspLeaves.push_back(mBspTree->GetRandomLeaf());
936               
937                for (int i = 0; i < bspLeaves.size(); ++ i)
938                {
939                        cout << "creating output for view cell " << i << " ... ";
940                        // check whether we can add the current ray to the output rays
941                        for (int k = 0; k < raysOut; ++ k)
942                        {
943                                Ray *ray = mSampleRays[k];
944
945                                for     (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
946                                {
947                                        BspLeaf *leaf = ray->bspIntersections[j].mLeaf;
948
949                                        if (bspLeaves[i]->GetViewCell() == leaf->GetViewCell())
950                                        {
951                                                vcRays[i].push_back(ray);
952                                        }
953                                }
954                        }
955
956                        Intersectable::NewMail();
957
958                        BspViewCell *vc = dynamic_cast<BspViewCell *>(bspLeaves[i]->GetViewCell());
959
960                        //bspLeaves[j]->Mail();
961                        char s[64]; sprintf(s, "bsp-pvs%04d.x3d", i);
962
963                        Exporter *exporter = Exporter::GetExporter(s);
964                        exporter->SetFilled();
965
966                        ViewCellPvsMap::iterator it = vc->GetPvs().mEntries.begin();
967
968                        exporter->SetWireframe();
969                        //exporter->SetFilled();
970
971                        Material m;//= RandomMaterial();
972                        m.mDiffuseColor = RgbColor(0, 1, 0);
973                        exporter->SetForcedMaterial(m);
974
975                        if (vc->GetMesh())
976                                exporter->ExportViewCell(vc);
977                        else
978                        {
979                                PolygonContainer cell;
980                                // export view cell geometry
981                                mBspTree->ConstructGeometry(vc, cell);
982                                exporter->ExportPolygons(cell);
983                                CLEAR_CONTAINER(cell);
984                        }
985
986                        Debug << i << ": pvs size=" << (int)vc->GetPvs().GetSize()
987                                        << ", piercing rays=" << (int)vcRays[i].size() << endl;
988
989                        // export rays piercing this view cell
990                        exporter->ExportRays(vcRays[i], 1000, RgbColor(0, 1, 0));
991
992                        m.mDiffuseColor = RgbColor(1, 0, 0);
993                        exporter->SetForcedMaterial(m);
994
995                        // exporter->SetWireframe();
996                        exporter->SetFilled();
997
998                        // output PVS of view cell
999                        for (; it != vc->GetPvs().mEntries.end(); ++ it)
1000                        {
1001                                Intersectable *intersect = (*it).first;
1002                                if (!intersect->Mailed())
1003                                {
1004                                        exporter->ExportIntersectable(intersect);
1005                                        intersect->Mail();
1006                                }                       
1007                        }
1008                               
1009                        // output rest of the objects
1010                        if (0)
1011                        {
1012                                Material m;//= RandomMaterial();
1013                                m.mDiffuseColor = RgbColor(0, 0, 1);
1014                                exporter->SetForcedMaterial(m);
1015
1016                                for (int j = 0; j < objects.size(); ++ j)
1017                                        if (!objects[j]->Mailed())
1018                                        {
1019                                                exporter->SetForcedMaterial(m);
1020                                                exporter->ExportIntersectable(objects[j]);
1021                                                objects[j]->Mail();
1022                                        }
1023                        }
1024                        DEL_PTR(exporter);
1025                        cout << "finished" << endl;
1026                }
1027        }
1028        else
1029        {
1030                ViewCellContainer viewCells;
1031
1032                mBspTree->CollectViewCells(viewCells);
1033                stable_sort(viewCells.begin(), viewCells.end(), vc_gt);
1034
1035                int limit = min(leafOut, (int)viewCells.size());
1036               
1037                for (int i = 0; i < limit; ++ i)
1038                {
1039                        cout << "creating output for view cell " << i << " ... ";
1040                       
1041            Intersectable::NewMail();
1042                        BspViewCell *vc = dynamic_cast<BspViewCell *>(viewCells[i]);
1043
1044                        cout << "creating output for view cell " << i << " ... ";
1045                        // check whether we can add the current ray to the output rays
1046                        for (int k = 0; k < raysOut; ++ k)
1047                        {
1048                                Ray *ray = mSampleRays[k];
1049
1050                                for     (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
1051                                {
1052                                        BspLeaf *leaf = ray->bspIntersections[j].mLeaf;
1053
1054                                        if (vc == leaf->GetViewCell())
1055                                        {
1056                                                vcRays[i].push_back(ray);
1057                                        }
1058                                }
1059                        }
1060
1061                        //bspLeaves[j]->Mail();
1062                        char s[64]; sprintf(s, "bsp-pvs%04d.x3d", i);
1063
1064                        Exporter *exporter = Exporter::GetExporter(s);
1065                       
1066                        exporter->SetWireframe();
1067
1068                        Material m;//= RandomMaterial();
1069                        m.mDiffuseColor = RgbColor(0, 1, 0);
1070                        exporter->SetForcedMaterial(m);
1071
1072                        if (vc->GetMesh())
1073                                exporter->ExportViewCell(vc);
1074                        else
1075                        {
1076                                PolygonContainer cell;
1077                                // export view cell
1078                                mBspTree->ConstructGeometry(vc, cell);
1079                                exporter->ExportPolygons(cell);
1080                                CLEAR_CONTAINER(cell);
1081                        }
1082
1083                       
1084                        Debug << i << ": pvs size=" << (int)vc->GetPvs().GetSize()
1085                                        << ", piercing rays=" << (int)vcRays[i].size() << endl;
1086
1087                       
1088                        // export rays piercing this view cell
1089                        exporter->ExportRays(vcRays[i], 1000, RgbColor(0, 1, 0));
1090       
1091                        m.mDiffuseColor = RgbColor(1, 0, 0);
1092                        exporter->SetForcedMaterial(m);
1093
1094                        ViewCellPvsMap::const_iterator it,
1095                                it_end = vc->GetPvs().mEntries.end();
1096
1097                        // output PVS of view cell
1098                        for (it = vc->GetPvs().mEntries.begin(); it != it_end; ++ it)
1099                        {
1100                                Intersectable *intersect = (*it).first;
1101                                if (!intersect->Mailed())
1102                                {
1103                                        Material m = RandomMaterial();
1104                       
1105                                        exporter->SetForcedMaterial(m);
1106
1107                                        exporter->ExportIntersectable(intersect);
1108                                        intersect->Mail();
1109                                }                       
1110                        }
1111                               
1112                        DEL_PTR(exporter);
1113                        cout << "finished" << endl;
1114                }
1115        }
1116}
Note: See TracBrowser for help on using the repository browser.