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

Revision 2690, 37.5 KB checked in by mattausch, 16 years ago (diff)

strange errors!!

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