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

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