source: GTP/trunk/Lib/Vis/Preprocessing/src/GvsPreprocessor.cpp @ 2048

Revision 2048, 31.5 KB checked in by mattausch, 17 years ago (diff)
  • Property svn:executable set to *
Line 
1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
4#include "VssRay.h"
5#include "ViewCellsManager.h"
6#include "Triangle3.h"
7#include "IntersectableWrapper.h"
8#include "Plane3.h"
9#include "RayCaster.h"
10#include "Exporter.h"
11#include "SamplingStrategy.h"
12#include "BvHierarchy.h"
13
14
15namespace GtpVisibilityPreprocessor
16{
17 
18#define GVS_DEBUG 0
19
20struct VizStruct
21{
22        Polygon3 *enlargedTriangle;
23        Triangle3 originalTriangle;
24        VssRay *ray;
25};
26
27
28static const float MIN_DIST = 0.001f;
29
30static vector<VizStruct> vizContainer;
31
32GvsPreprocessor::GvsPreprocessor():
33Preprocessor(),
34mSamplingType(SamplingStrategy::VIEWCELL_BASED_DISTRIBUTION),
35mProcessedViewCells(0),
36mCurrentViewCell(NULL)
37{
38        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
39        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
40        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.gvsSamplesPerPass", mGvsSamplesPerPass);
41        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.minContribution", mMinContribution);
42        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
43        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
44        Environment::GetSingleton()->GetBoolValue("GvsPreprocessor.perViewCell", mPerViewCell);
45        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.maxViewCells", mMaxViewCells);
46
47        Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluatePixelError", mEvaluatePixelError);
48
49        char gvsStatsLog[100];
50        Environment::GetSingleton()->GetStringValue("GvsPreprocessor.stats", gvsStatsLog);
51        mGvsStatsStream.open(gvsStatsLog);
52
53        Debug << "Gvs preprocessor options" << endl;
54        Debug << "number of total samples: " << mTotalSamples << endl;
55        Debug << "number of initial samples: " << mInitialSamples << endl;
56        cout << "number of gvs samples per pass: " << mGvsSamplesPerPass << endl;
57        cout << "number of samples per pass: " << mSamplesPerPass << endl;
58        Debug << "threshold: " << mThreshold << endl;
59        Debug << "epsilon: " << mEps << endl;
60        Debug << "stats: " << gvsStatsLog << endl;
61        Debug << "per view cell: " << mPerViewCell << endl;
62        Debug << "max view cells: " << mMaxViewCells << endl;
63        Debug << "min contribution: " << mMinContribution << endl;
64
65        if (1)
66                mOnlyRandomSampling = false;           
67        else
68                mOnlyRandomSampling = true;
69
70        mGvsStats.Reset();
71}
72
73
74GvsPreprocessor::~GvsPreprocessor()
75{
76        ClearRayQueue();
77}
78
79
80void GvsPreprocessor::ClearRayQueue()
81{
82        // clean ray queue
83        while (!mRayQueue.empty())
84        {
85                // handle next ray
86                VssRay *ray = mRayQueue.top();
87                mRayQueue.pop();
88
89                //delete ray;
90        }
91}
92
93
94bool GvsPreprocessor::NextViewCell()
95{
96        //if (mViewCellsManager->GetNumViewCells() == mProcessedViewCells)
97        //      return false; // no more view cells
98
99        if (mProcessedViewCells == (int)mViewCells.size())
100                return false; // no more view cells
101
102        mCurrentViewCell = mViewCells[mProcessedViewCells];
103
104   if (!mCurrentViewCell->GetMesh())
105                mViewCellsManager->CreateMesh(mCurrentViewCell);
106
107        mGvsStats.mViewCellId = mCurrentViewCell->GetId();
108
109        Debug << "vc: " << mCurrentViewCell->GetId() << endl;
110
111        ++ mProcessedViewCells;
112   
113        return true;
114}
115
116
117int GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
118                                                                                const Triangle3 &hitTriangle,
119                                                                                const VssRay &oldRay)
120{
121        // the predicted hitpoint: we expect to hit the same mesh again
122        const Vector3 predictedHit = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
123
124        const float predictedLen = Magnitude(predictedHit - currentRay.mOrigin);
125        const float len = Magnitude(currentRay.mTermination - currentRay.mOrigin);
126       
127        // distance large => this is likely to be a discontinuity
128#if 1
129        if ((predictedLen - len) > mThreshold)
130#else // rather use relative distance
131        if ((predictedLen / len) > mThreshold)
132#endif
133        {
134                //cout << "r";
135                // apply reverse sampling to find the gap
136                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
137
138                if (!newRay)
139                        return 1;
140
141                // set flag for visualization
142                newRay->mFlags |= VssRay::ReverseSample;
143               
144                // if ray is not further processed => delete ray
145                if (!HandleRay(newRay))
146                {
147                        //delete newRay;
148                }
149               
150                return 1;
151        }
152
153        return 0;
154}
155
156// #id: 1270
157bool GvsPreprocessor::HasContribution(VssRay &ray)
158{
159        if (!ray.mTerminationObject)
160                return false;
161
162        bool result;
163
164        if (!mPerViewCell)
165        {
166                // store the rays + the intersected view cells
167                const bool storeViewCells = false; //GVS_DEBUG;
168
169                mViewCellsManager->ComputeSampleContribution(ray,
170                                                                                                         true,
171                                                                                                         storeViewCells,
172                                                                                                         true);
173
174                result = ray.mPvsContribution > 0;
175        }
176        else
177        {
178                Intersectable *obj = ray.mTerminationObject;
179
180                if (!obj->mCounter)
181                {
182                        obj->mCounter = 1;
183                        mTrianglePvs.push_back(obj);
184
185                        /*mViewCellsManager->ComputeSampleContribution(ray,
186                                                                                                         true,
187                                                                                                         mCurrentViewCell,
188                                                                                                         true);*/
189                       
190                        result = true;
191                }
192                else
193                {
194                        result = false;
195                }
196        }
197
198        return result;
199}
200
201
202bool GvsPreprocessor::HandleRay(VssRay *vssRay)
203{
204        if (!HasContribution(*vssRay))
205                return false;
206
207        if (0 && GVS_DEBUG)
208                mVssRays.push_back(new VssRay(*vssRay));
209
210        // add new ray to ray queue
211        mRayQueue.push(vssRay);
212
213        ++ mGvsStats.mTotalContribution;
214
215        return true;
216}
217
218
219/** Creates 3 new vertices for triangle vertex with specified index.
220*/
221void GvsPreprocessor::CreateDisplacedVertices(VertexContainer &vertices,
222                                                                                          const Triangle3 &hitTriangle,
223                                                                                          const VssRay &ray,
224                                                                                          const int index) const
225{
226        const int indexU = (index + 1) % 3;
227        const int indexL = (index == 0) ? 2 : index - 1;
228
229        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
230        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
231        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
232       
233        const float len = Magnitude(a);
234       
235        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
236        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
237        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
238                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
239
240        // compute the new three hit points
241        // pi, i + 1:  pi+ e·|pi-xp|·di, j
242        const Vector3 pt1 = hitTriangle.mVertices[index] + mEps * len * dir1;
243        // pi, i - 1:  pi+ e·|pi-xp|·di, j
244    const Vector3 pt2 = hitTriangle.mVertices[index] + mEps * len * dir2;
245        // pi, i:  pi+ e·|pi-xp|·di, j
246        const Vector3 pt3 = hitTriangle.mVertices[index] + mEps * len * dir3;
247       
248        vertices.push_back(pt2);
249        vertices.push_back(pt3);
250        vertices.push_back(pt1);
251}
252
253
254void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
255                                                                          const Triangle3 &hitTriangle,
256                                                                          const VssRay &ray) const
257{
258        CreateDisplacedVertices(vertices, hitTriangle, ray, 0);
259        CreateDisplacedVertices(vertices, hitTriangle, ray, 1);
260        CreateDisplacedVertices(vertices, hitTriangle, ray, 2);
261}
262
263
264Vector3 GvsPreprocessor::CalcPredictedHitPoint(const VssRay &newRay,
265                                                                                           const Triangle3 &hitTriangle,
266                                                                                           const VssRay &oldRay) const
267{
268        // find the intersection of the plane induced by the
269        // hit triangle with the new ray
270        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
271
272        const Vector3 hitPt =
273                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
274       
275        return hitPt;
276}
277
278
279static bool EqualVisibility(const VssRay &a, const VssRay &b)
280{
281        return a.mTerminationObject == b.mTerminationObject;
282}
283
284
285int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
286                                                                   const Vector3 &p1,
287                                                                   const Vector3 &p2,
288                                                                   const VssRay &ray1,
289                                                                   const VssRay &ray2,
290                                                                   const VssRay &oldRay)
291{
292        //cout <<"y"<<Magnitude(p1 - p2) << " ";
293        int castRays = 0;
294
295        // cast reverse rays if necessary
296        castRays += CheckDiscontinuity(ray1, hitTriangle, oldRay);
297        castRays += CheckDiscontinuity(ray2, hitTriangle, oldRay);
298
299        if (EqualVisibility(ray1, ray2) || (SqrMagnitude(p1 - p2) <= MIN_DIST))
300        {
301                return castRays;
302        }
303       
304        // the new subdivision point
305        const Vector3 p = (p1 + p2) * 0.5f;
306        //cout << "p: " << p << " " << p1 << " " << p2 << endl;
307        // cast ray into the new point
308        SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
309
310        VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
311       
312        ++ castRays;
313
314        if (!newRay) return castRays;
315
316        newRay->mFlags |= VssRay::BorderSample;
317
318        // add new ray to queue
319        const bool enqueued = HandleRay(newRay);
320
321        // subdivide further
322        castRays += SubdivideEdge(hitTriangle, p1, p, ray1, *newRay, oldRay);
323        castRays += SubdivideEdge(hitTriangle, p, p2, *newRay, ray2, oldRay);
324
325        // this ray will not be further processed
326        //if (!enqueued) delete newRay;
327
328        return castRays;
329}
330
331
332int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
333{
334        Intersectable *tObj = currentRay.mTerminationObject;
335        Triangle3 hitTriangle;
336
337        // other types not implemented yet
338        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
339        {
340                hitTriangle = static_cast<TriangleIntersectable *>(tObj)->GetItem();
341        }
342        else
343        {
344                cout << "border sampling: " << tObj->Type() << " not yet implemented" << endl;
345        }
346
347        VertexContainer enlargedTriangle;
348       
349        /// create 3 new hit points for each vertex
350        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
351       
352        /// create rays from sample points and handle them
353        SimpleRayContainer simpleRays;
354        simpleRays.reserve(9);
355
356        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
357
358        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
359        {
360                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
361
362                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
363                simpleRays.AddRay(sr); 
364        }
365
366        if (0)
367        {
368                // visualize enlarged triangles
369                VizStruct dummy;
370                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
371                dummy.originalTriangle = hitTriangle;
372                vizContainer.push_back(dummy);
373        }
374
375        // cast rays to triangle vertices and determine visibility
376        VssRayContainer vssRays;
377
378        // don't cast double rays as we need only the forward rays
379        const bool castDoubleRays = !mPerViewCell;
380        // cannot prune invalid rays because we have to compare adjacent  rays.
381        const bool pruneInvalidRays = false;
382
383
384        //////////
385        //-- fill up simple rays with random rays so we can cast 16
386
387        //const int numRandomRays = 0;
388        const int numRandomRays = 16 - (int)simpleRays.size();
389        ViewCellBasedDistribution vcStrat(*this, mCurrentViewCell);
390
391        GenerateRays(numRandomRays, vcStrat, simpleRays);
392
393        /////////////////////
394
395
396        // keep origin for per view cell sampling
397        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
398
399        const int numBorderSamples = (int)vssRays.size() - numRandomRays;
400
401        // set flags
402        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
403        int i = 0;
404 
405        for (rit = vssRays.begin(); rit != rit_end; ++ rit, ++ i)
406        {
407                if (i < numBorderSamples)
408                        (*rit)->mFlags |= VssRay::BorderSample;
409        }
410
411        int castRays = (int)simpleRays.size();
412
413        VssRayContainer invalidSamples;
414
415        // handle rays
416        EnqueueRays(vssRays, invalidSamples);
417
418    // recursivly subdivide each edge
419        for (int i = 0; i < numBorderSamples; ++ i)
420        {
421                castRays += SubdivideEdge(hitTriangle,
422                                                                  enlargedTriangle[i],
423                                                                  enlargedTriangle[(i + 1) % numBorderSamples],
424                                                                  *vssRays[i],
425                                                                  *vssRays[(i + 1) % numBorderSamples],
426                                                                  currentRay);
427        }
428       
429        mGvsStats.mBorderSamples += castRays;
430
431        CLEAR_CONTAINER(invalidSamples);
432       
433        //cout << "cast rays: " << castRays << endl;
434        return castRays;
435}
436
437
438bool GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
439                                                                          const Triangle3 &occluder,
440                                                                          const VssRay &oldRay,
441                                                                          Vector3 &newPoint) const
442{
443        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
444        //-- with the newly found occluder (xold is the previous ray from
445        //-- which x was generated). On the intersecting line, we select a point
446        //-- pnew which lies just outside of the new triangle so the ray
447        //-- just passes through the gap
448
449        const Plane3 plane(currentRay.GetOrigin(),
450                                           currentRay.GetTermination(),
451                                           oldRay.GetTermination());
452       
453        Vector3 pt1, pt2;
454
455        const bool intersects = occluder.GetPlaneIntersection(plane, pt1, pt2);
456
457        if (!intersects)
458        {
459                //cerr << "big error!! no intersection " << pt1 << " " << pt2 << endl;
460                return false;
461        }
462
463        // get the intersection point on the old ray
464        const Plane3 triPlane(occluder.GetNormal(), occluder.mVertices[0]);
465
466        const float t = triPlane.FindT(oldRay.mOrigin, oldRay.mTermination);
467        const Vector3 pt3 = oldRay.mOrigin + t * (oldRay.mTermination - oldRay.mOrigin);
468
469        // Evaluate new hitpoint just outside the triangle
470        const float eps = mEps;
471
472        // the point is chosen to be on the side closer to the original ray
473        if (Distance(pt1, pt3) < Distance(pt2, pt3))
474        {
475                newPoint = pt1 + eps * (pt1 - pt2);
476        }       
477        else
478        {
479                newPoint = pt2 + eps * (pt2 - pt1);
480        }
481
482        //cout << "passing point: " << newPoint << endl << endl;
483        return true;
484}
485
486
487VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
488                                                                                 const Triangle3 &hitTriangle,
489                                                                                 const VssRay &oldRay)
490{
491        // get triangle occluding the path to the hit mesh
492        Triangle3 occluder;
493        Intersectable *tObj = currentRay.mTerminationObject;
494
495        // q: why can this happen?
496        if (!tObj)
497                return NULL;
498
499        // other types not implemented yet
500        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
501        {
502                occluder = static_cast<TriangleIntersectable *>(tObj)->GetItem();
503        }
504        else
505        {
506                cout << "reverse sampling: " << tObj->Type() << " not yet implemented" << endl;
507        }
508        // get a point which is passing just outside of the occluder
509    Vector3 newPoint;
510
511        // why is there sometimes no intersecton found?
512        if (!GetPassingPoint(currentRay, occluder, oldRay, newPoint))
513                return NULL;
514
515        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
516
517        Vector3 newDir, newOrigin;
518
519        //-- Construct the mutated ray with xnew,
520        //-- dir = predicted(x)- pnew as direction vector
521        newDir = predicted - newPoint;
522
523        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
524        // difficult to say!!
525        const float offset = 0.5f;
526        newOrigin = newPoint - newDir * offset;
527       
528        //////////////
529        //-- for per view cell sampling, we must check for intersection
530        //-- with the current view cell
531
532    if (mPerViewCell)
533        {
534                // send ray to view cell
535                static Ray ray;
536                ray.Clear();
537                ray.Init(newOrigin, -newDir, Ray::LOCAL_RAY);
538               
539                //cout << "z";
540                // check if ray intersects view cell
541                if (!mCurrentViewCell->CastRay(ray))
542                        return NULL;
543
544                Ray::Intersection &hit = ray.intersections[0];
545       
546                //cout << "q";
547                // the ray starts from the view cell
548                newOrigin = ray.Extrap(hit.mT);
549        }
550
551        const SimpleRay simpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
552
553        VssRay *reverseRay =
554                mRayCaster->CastRay(simpleRay, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
555
556    ++ mGvsStats.mReverseSamples;
557
558        return reverseRay;
559}
560
561
562int GvsPreprocessor::CastInitialSamples(const int numSamples,
563                                                                                const int sampleType)
564{       
565        const long startTime = GetTime();
566
567        // generate simple rays
568        SimpleRayContainer simpleRays;
569       
570        ViewCellBasedDistribution vcStrat(*this, mCurrentViewCell);
571    GenerateRays(numSamples, vcStrat, simpleRays);
572
573        //cout << "sr: " << simpleRays.size() << endl;
574        // generate vss rays
575        VssRayContainer samples;
576       
577        const bool castDoubleRays = !mPerViewCell;
578        const bool pruneInvalidRays = true;
579       
580        CastRays(simpleRays, samples, castDoubleRays, pruneInvalidRays);
581       
582        VssRayContainer invalidSamples;
583
584        // add to ray queue
585        EnqueueRays(samples, invalidSamples);
586
587        CLEAR_CONTAINER(invalidSamples);
588        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
589        return (int)simpleRays.size();
590}
591
592
593void GvsPreprocessor::EnqueueRays(VssRayContainer &samples, VssRayContainer &invalidSamples)
594{
595        // add samples to ray queue
596        VssRayContainer::const_iterator vit, vit_end = samples.end();
597        for (vit = samples.begin(); vit != vit_end; ++ vit)
598        {
599                VssRay *ray = *vit;
600
601                if (!HandleRay(ray))
602                        invalidSamples.push_back(ray);
603        }
604}
605
606
607int GvsPreprocessor::ProcessQueue()
608{
609        int castSamples = 0;
610        ++ mGvsStats.mGvsPass;
611
612        while (!mRayQueue.empty())//&& (mGvsStats.mTotalSamples + castSamples < mTotalSamples) )
613        {
614                // handle next ray
615                VssRay *ray = mRayQueue.top();
616                mRayQueue.pop();
617               
618                const int newSamples = AdaptiveBorderSampling(*ray);
619
620                castSamples += newSamples;
621
622                //delete ray;
623        }
624
625        // HACK
626        if (mRayCaster->mVssRayPool.mIndex > mSamplesPerPass)
627        {
628                cout << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
629                Debug << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
630        }
631
632        return castSamples;
633}
634
635
636void ExportVssRays(Exporter *exporter, const VssRayContainer &vssRays)
637{
638        VssRayContainer vcRays, vcRays2, vcRays3;
639
640        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
641
642        // prepare some rays for output
643        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
644        {
645                //const float p = RandomValue(0.0f, (float)vssRays.size());
646
647                if (1)//(p < raysOut)
648                {
649                        if ((*rit)->mFlags & VssRay::BorderSample)
650                        {
651                                vcRays.push_back(*rit);
652                        }
653                        else if ((*rit)->mFlags & VssRay::ReverseSample)
654                        {
655                                vcRays2.push_back(*rit);
656                        }
657                        else
658                        {
659                                vcRays3.push_back(*rit);
660                        }       
661                }
662        }
663
664        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
665        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
666        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
667}
668
669
670//void GvsPreprocessor::VisualizeViewCell(ViewCell *vc)
671void GvsPreprocessor::VisualizeViewCell(const ObjectContainer &objects)
672{
673    Intersectable::NewMail();
674
675        Material m;
676       
677        char str[64]; sprintf(str, "pass%06d.wrl", mProcessedViewCells);
678
679        Exporter *exporter = Exporter::GetExporter(str);
680        if (!exporter)
681                return;
682
683        /*ObjectPvsIterator pit = vc->GetPvs().GetIterator();
684
685        // output PVS of view cell
686        while (pit.HasMoreEntries())
687        {               
688                ObjectPvsEntry entry = pit.Next();
689
690                Intersectable *intersect = entry.mObject;
691               
692                if (intersect->Mailed())
693                        continue;
694               
695                intersect->Mail();
696                //m.mDiffuseColor = RgbColor(1, 0, 0);
697                m = RandomMaterial();
698                exporter->SetForcedMaterial(m);
699
700                exporter->ExportIntersectable(intersect);
701        }*/
702        ObjectContainer::const_iterator oit, oit_end = objects.end();
703
704        for (oit = objects.begin(); oit != oit_end; ++ oit)
705        {
706                Intersectable *intersect = *oit;
707               
708                m = RandomMaterial();
709                exporter->SetForcedMaterial(m);
710                exporter->ExportIntersectable(intersect);
711        }
712
713        cout << "vssrays: " << (int)mVssRays.size() << endl;
714        ExportVssRays(exporter, mVssRays);
715
716        /////////////////
717        //-- export view cell geometry
718
719        exporter->SetWireframe();
720
721        m.mDiffuseColor = RgbColor(0, 1, 0);
722        exporter->SetForcedMaterial(m);
723
724        //mViewCellsManager->ExportViewCellGeometry(exporter, vc, NULL, NULL);
725        //mViewCellsManager->ExportViewCellGeometry(exporter, mCurrentViewCell, NULL, NULL);
726
727        AxisAlignedBox3 bbox = mCurrentViewCell->GetMesh()->mBox;
728        exporter->ExportBox(bbox);
729        //exporter->SetFilled();
730
731        DEL_PTR(exporter);
732}
733
734
735void GvsPreprocessor::VisualizeViewCells()
736{
737        char str[64]; sprintf(str, "tmp/pass%06d_%04d-", mProcessedViewCells, mPass);
738                       
739        // visualization
740        if (mGvsStats.mPassContribution > 0)
741        {
742                const bool exportRays = true;
743                const bool exportPvs = true;
744
745                mViewCellsManager->ExportSingleViewCells(mObjects,
746                                                                                                 10,
747                                                                                                 false,
748                                                                                                 exportPvs,
749                                                                                                 exportRays,
750                                                                                                 1000,
751                                                                                                 str);
752        }
753
754        // remove pass samples
755        ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
756
757        for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
758        {
759                (*vit)->DelRayRefs();
760        }
761}
762
763
764void GvsPreprocessor::ProcessViewCell()
765{
766        //Intersectable::NewMail();
767
768        // compute direct intersections with view cell
769        IntersectWithViewCell();
770
771        mGvsStats.mPerViewCellSamples = 0;
772        int oldContribution = mGvsStats.mTotalContribution;
773        int passSamples = 0;
774
775        //while (mGvsStats.mPerViewCellSamples < mTotalSamples)
776        while (1)
777        {
778                mRayCaster->InitPass();
779
780                // Ray queue empty =>
781                // cast a number of uniform samples to fill ray queue
782                int newSamples = CastInitialSamples(mInitialSamples, mSamplingType);
783
784                if (!mOnlyRandomSampling)
785                        newSamples += ProcessQueue();
786
787                passSamples += newSamples;
788                mGvsStats.mPerViewCellSamples += newSamples;
789               
790                if (passSamples >= mGvsSamplesPerPass)
791                {
792                        ++ mPass;
793                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
794
795                        ////////
796                        //-- stats
797
798                        mGvsStats.mPass = mPass;
799
800                        cout << "\nPass " << mPass << " #samples: " << mGvsStats.mPerViewCellSamples << endl;
801                        cout << "contribution=" << mGvsStats.mPassContribution << " (of " << mMinContribution << ")" << endl;
802
803                        // termination criterium
804                        if (mGvsStats.mPassContribution < mMinContribution)
805                        {
806                                break;
807                        }
808
809                        // reset
810                        oldContribution = mGvsStats.mTotalContribution;
811                        mGvsStats.mPassContribution = 0;
812                        passSamples = 0;
813                }
814        }
815}
816
817
818void GvsPreprocessor::CompileViewCellsList()
819{
820        vector<ViewCellPoints *> *vcPoints = mViewCellsManager->GetViewCellPoints();
821
822        if (!vcPoints->empty())
823        {
824                vector<ViewCellPoints *>::const_iterator vit, vit_end = vcPoints->end();
825
826                for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
827                {
828                        mViewCells.push_back((*vit)->first);
829                }
830
831                return;
832        }
833
834        while ((int)mViewCells.size() < mMaxViewCells)
835    {
836                if (0)
837                {
838                        mViewCells.push_back(mViewCellsManager->GetViewCell((int)mViewCells.size()));
839                        continue;
840                }
841               
842                // HACK
843                const int tries = 10000;
844                int i = 0;
845
846                for (i = 0; i < tries; ++ i)
847                {
848                        const int idx = (int)RandomValue(0.0f, (float)mViewCellsManager->GetNumViewCells() - 0.5f);
849       
850                        ViewCell *viewCell = mViewCellsManager->GetViewCell(idx);
851
852                        if (!viewCell->Mailed())
853                        {
854                                viewCell->Mail();
855                                break;
856                        }
857//if (viewCell->GetId() == 36658)
858//{
859                        mViewCells.push_back(viewCell);
860//                      return;
861//}
862                }
863
864                if (i == tries)
865                {
866                        cerr << "big error! no view cell found" << endl;
867                        return;
868                }
869        }
870}
871
872
873void GvsPreprocessor::IntersectWithViewCell()
874{
875        mCurrentViewCell->GetMesh()->ComputeBoundingBox();
876        AxisAlignedBox3 box = mCurrentViewCell->GetMesh()->mBox;
877        //cout << "box: " << box << endl;
878        vector<KdLeaf *> leaves;
879
880        mKdTree->GetBoxIntersections(box, leaves);
881
882        vector<KdLeaf *>::const_iterator lit, lit_end = leaves.end();
883
884        for (lit = leaves.begin(); lit != leaves.end(); ++ lit)
885        {
886                KdLeaf *leaf = *lit;
887                ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
888
889                for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
890                {
891                        TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(*oit);
892
893                        if (box.Intersects(triObj->GetItem()))
894                        {
895                                if (!triObj->mCounter)
896                                {
897                                        triObj->mCounter = 1;
898                                        mTrianglePvs.push_back(triObj);
899                                }
900                        }
901                }
902        }
903}
904
905
906void GvsPreprocessor::PerViewCellComputation()
907{
908        // hack: reset counter
909        ObjectContainer::const_iterator oit, oit_end = mObjects.end();
910
911        for (oit = mObjects.begin(); oit != oit_end; ++ oit)
912        {
913                (*oit)->mCounter = 0;
914        }
915//int dummy = 0;
916        while (NextViewCell())// && (dummy < 3))
917        {//++ dummy;
918                long startTime = GetTime();
919                cout << "\n***********************\n"
920                         << "processing view cell " << mProcessedViewCells
921                         << " (id: " << mCurrentViewCell->GetId() << ")" << endl;
922
923                // compute the pvs of the current view cell
924                ProcessViewCell();
925
926                //mGvsStats.mTrianglePvs = mCurrentViewCell->GetPvs().GetSize();
927                mGvsStats.mTrianglePvs = (int)mTrianglePvs.size();
928                mGvsStats.mTotalTrianglePvs += mGvsStats.mTrianglePvs;
929
930                ObjectContainer objectPvs;
931
932                // exchange triangle pvs with objects
933                //UpdatePvs(mCurrentViewCell);
934                GetObjectPvs(objectPvs);
935
936                cout << "triangle pvs of " << (int)mTrianglePvs.size()
937                         << " was converted to object pvs of " << (int)objectPvs.size() << endl;
938
939                ////////
940                //-- stats
941               
942                mGvsStats.mViewCells = mProcessedViewCells;//mPass;
943                //mGvsStats.mPerViewCellPvs = mCurrentViewCell->GetPvs().GetSize();
944                mGvsStats.mPerViewCellPvs = (int)objectPvs.size();
945
946                mGvsStats.mTotalPvs += mGvsStats.mPerViewCellPvs;
947                mGvsStats.mTotalSamples += mGvsStats.mPerViewCellSamples;
948
949                // timing
950                const long currentTime = GetTime();
951       
952                mGvsStats.mTimePerViewCell = TimeDiff(startTime, currentTime) * 1e-3f;
953                mGvsStats.mTotalTime += mGvsStats.mTimePerViewCell;
954
955                //lastTime = currentTime;
956
957                mGvsStats.Stop();
958                mGvsStats.Print(mGvsStatsStream);
959
960        mTrianglePvs.clear();
961
962                if (GVS_DEBUG)
963                {
964                        //VisualizeViewCell(mCurrentViewCell);
965                        VisualizeViewCell(objectPvs);
966                        CLEAR_CONTAINER(mVssRays);
967                }
968
969                // is this really necessary?
970                //ClearRayQueue();
971
972                if (mEvaluatePixelError || mExportVisibility)
973                {
974                        StorePvs(objectPvs);
975                }
976        }
977}
978
979
980void GvsPreprocessor::StorePvs(const ObjectContainer &objectPvs)
981{
982        ObjectContainer::const_iterator oit, oit_end = objectPvs.end();
983
984        for (oit = objectPvs.begin(); oit != oit_end; ++ oit)
985        {
986                mCurrentViewCell->GetPvs().AddSample(*oit, 1);
987        }
988}
989
990
991void GvsPreprocessor::ComputeRenderError()
992{
993        cout << "computing gvs render error" << endl;
994        vector<ViewCellPoints *> *vcPoints = mViewCellsManager->GetViewCellPoints();
995
996        vector<ViewCellPoints *>::const_iterator vit, vit_end = vcPoints->end();
997
998        for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
999        {
1000                ViewCellPoints *vcPoints = *vit;
1001               
1002                renderer->EvalPvsStat(vcPoints->second);
1003
1004                mStats <<
1005                        "#ViewCell\n" << vcPoints->first->GetId() << endl <<
1006                        "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError() << endl <<
1007                        "#AvgPixelError\n" << renderer->GetAvgPixelError() << endl <<
1008                        "#MaxPixelError\n" << renderer->GetMaxPixelError() << endl <<
1009                        "#MaxPvsRenderError\n" << renderer->mPvsStat.GetMaxError() << endl <<
1010                        "#ErrorFreeFrames\n" << renderer->mPvsStat.GetErrorFreeFrames() << endl <<
1011                        "#AvgRenderPvs\n" << renderer->mPvsStat.GetAvgPvs() << endl;
1012        }
1013}
1014
1015
1016void GvsPreprocessor::UpdatePvs(ViewCell *currentViewCell)
1017{
1018        ObjectPvs newPvs;
1019        BvhLeaf::NewMail();
1020
1021        ObjectPvsIterator pit = currentViewCell->GetPvs().GetIterator();
1022
1023        // output PVS of view cell
1024        while (pit.HasMoreEntries())
1025        {               
1026                ObjectPvsEntry entry = pit.Next();
1027
1028                Intersectable *intersect = entry.mObject;
1029       
1030                BvhLeaf *bv = intersect->mBvhLeaf;
1031
1032                if (!bv || bv->Mailed())
1033                        continue;
1034               
1035                bv->Mail();
1036
1037                //m.mDiffuseColor = RgbColor(1, 0, 0);
1038                newPvs.AddSampleDirty(bv, 1.0f);
1039        }
1040
1041        newPvs.SimpleSort();
1042
1043        currentViewCell->SetPvs(newPvs);
1044}
1045
1046 
1047void GvsPreprocessor::GetObjectPvs(ObjectContainer &objectPvs) const
1048{
1049        BvhLeaf::NewMail();
1050
1051        ObjectContainer::const_iterator oit, oit_end = mTrianglePvs.end();
1052
1053        for (oit = mTrianglePvs.begin(); oit != oit_end; ++ oit)
1054        {
1055                Intersectable *intersect = *oit;
1056       
1057                BvhLeaf *bv = intersect->mBvhLeaf;
1058
1059                if (!bv || bv->Mailed())
1060                        continue;
1061               
1062                bv->Mail();
1063
1064                objectPvs.push_back(bv);
1065                // hack: reset counter
1066                (*oit)->mCounter = 0;
1067        }
1068}
1069
1070
1071void GvsPreprocessor::GlobalComputation()
1072{
1073        int passSamples = 0;
1074        int oldContribution = 0;
1075
1076        while (mGvsStats.mTotalSamples < mTotalSamples)
1077        {
1078                mRayCaster->InitPass();
1079                // Ray queue empty =>
1080                // cast a number of uniform samples to fill ray queue
1081                int newSamples = CastInitialSamples(mInitialSamples, mSamplingType);
1082
1083                if (!mOnlyRandomSampling)
1084                        newSamples += ProcessQueue();
1085
1086                passSamples += newSamples;
1087                mGvsStats.mTotalSamples += newSamples;
1088
1089                if (passSamples % (mGvsSamplesPerPass + 1) == mGvsSamplesPerPass)
1090                {
1091                        ++ mPass;
1092
1093                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1094
1095                        ////////
1096                        //-- stats
1097
1098                        //cout << "\nPass " << mPass << " #samples: " << mGvsStats.mTotalSamples << " of " << mTotalSamples << endl;
1099                        mGvsStats.mPass = mPass;
1100                        mGvsStats.Stop();
1101                        mGvsStats.Print(mGvsStatsStream);
1102
1103                        // reset
1104                        oldContribution = mGvsStats.mTotalContribution;
1105                        mGvsStats.mPassContribution = 0;
1106                        passSamples = 0;
1107
1108                        if (GVS_DEBUG)
1109                                VisualizeViewCells();
1110                }
1111        }
1112}
1113
1114
1115bool GvsPreprocessor::ComputeVisibility()
1116{
1117        cout << "Gvs Preprocessor started\n" << flush;
1118        const long startTime = GetTime();
1119
1120        //Randomize(0);
1121        mGvsStats.Reset();
1122        mGvsStats.Start();
1123
1124        if (!mLoadViewCells)
1125        {       
1126                /// construct the view cells from the scratch
1127                ConstructViewCells();
1128                // reset pvs already gathered during view cells construction
1129                mViewCellsManager->ResetPvs();
1130                cout << "finished view cell construction" << endl;
1131        }
1132        else if (0)
1133        {       
1134                //-- test successful view cells loading by exporting them again
1135                VssRayContainer dummies;
1136                mViewCellsManager->Visualize(mObjects, dummies);
1137                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
1138        }
1139
1140        mGvsStats.Stop();
1141        mGvsStats.Print(mGvsStatsStream);
1142
1143        if (mPerViewCell)
1144        {
1145                // list of view cells to compute
1146                CompileViewCellsList();
1147                PerViewCellComputation();
1148
1149                if (mEvaluatePixelError)
1150                {
1151                        ComputeRenderError();
1152                }
1153        }
1154        else
1155        {
1156                GlobalComputation();
1157        }
1158
1159        cout << "cast " << 2 * mGvsStats.mTotalSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
1160
1161        if (GVS_DEBUG)
1162        {
1163                Visualize();
1164                CLEAR_CONTAINER(mVssRays);
1165        }
1166       
1167        // export the preprocessed information to a file
1168        if (0 && mExportVisibility)
1169        {
1170                ExportPreprocessedData(mVisibilityFileName);
1171        }
1172
1173        return true;
1174}
1175
1176
1177void GvsPreprocessor::DeterminePvsObjects(VssRayContainer &rays)
1178{
1179        mViewCellsManager->DeterminePvsObjects(rays, true);
1180}
1181
1182
1183void GvsPreprocessor::Visualize()
1184{
1185        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
1186
1187        if (!exporter)
1188                return;
1189       
1190        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
1191       
1192        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
1193        {
1194                exporter->SetWireframe();
1195                exporter->ExportPolygon((*vit).enlargedTriangle);
1196                //Material m;
1197                exporter->SetFilled();
1198                Polygon3 poly = Polygon3((*vit).originalTriangle);
1199                exporter->ExportPolygon(&poly);
1200        }
1201
1202        VssRayContainer::const_iterator rit, rit_end = mVssRays.end();
1203
1204        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
1205        {
1206                Intersectable *obj = (*rit)->mTerminationObject;
1207                exporter->ExportIntersectable(obj);
1208        }
1209
1210        ExportVssRays(exporter, mVssRays);
1211       
1212        delete exporter;
1213}
1214
1215
1216void GvsStatistics::Print(ostream &app) const
1217{
1218        app << "#ViewCells\n" << mViewCells << endl;
1219        app << "#ViewCellId\n" << mViewCellId << endl;
1220        app << "#TotalTime\n" << mTotalTime << endl;
1221        app << "#TimePerViewCell\n" << mTimePerViewCell << endl;;
1222
1223        app << "#RaysPerSec\n" << RaysPerSec() << endl;
1224
1225        app << "#TrianglePvs\n" << mTrianglePvs << endl;
1226        app << "#TotalTrianglePvs\n" << mTotalTrianglePvs << endl;
1227
1228        app << "#PerViewCellPvs\n" << mPerViewCellPvs << endl;
1229        app << "#TotalPvs\n" << mTotalPvs << endl;
1230       
1231        app << "#PerViewCellSamples\n" << mPerViewCellSamples << endl;
1232        app << "#TotalSamples\n" << mTotalSamples << endl;
1233        app     << "#SamplesContri\n" << mTotalContribution << endl;
1234               
1235        //app << "#ReverseSamples\n" << mReverseSamples << endl;
1236        //app << "#BorderSamples\n" << mBorderSamples << endl;
1237
1238        //app << "#Pass\n" << mPass << endl;
1239        //app << "#ScDiff\n" << mPassContribution << endl;
1240        //app << "#GvsRuns\n" << mGvsPass << endl;     
1241
1242        app << endl;
1243}
1244
1245
1246}
Note: See TracBrowser for help on using the repository browser.