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

Revision 2730, 48.4 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#include "Timer/PerfTimer.h"
16#include "Vector2.h"
17#include "RndGauss.h"
18
19
20
21namespace GtpVisibilityPreprocessor
22{
23 
24#define GVS_DEBUG 0
25#define NOT_ACCOUNTED_OBJECT 0
26#define ACCOUNTED_OBJECT 2
27
28
29static const float MIN_DIST = 0.001f;
30
31static ObjectContainer myobjects;
32static int sInvalidSamples = 0;
33
34///////////
35//-- timers
36
37
38static PerfTimer rayTimer;
39static PerfTimer kdPvsTimer;
40static PerfTimer gvsTimer;
41static PerfTimer initialTimer;
42static PerfTimer intersectionTimer;
43static PerfTimer preparationTimer;
44static PerfTimer mainLoopTimer;
45static PerfTimer contributionTimer;
46static PerfTimer castTimer;
47static PerfTimer generationTimer;
48
49
50/////////////////////
51
52
53/** Visualization structure for the GVS algorithm.
54*/
55struct VizStruct
56{
57        Polygon3 *enlargedTriangle;
58        Triangle3 originalTriangle;
59        VssRay *ray;
60};
61
62static vector<VizStruct> vizContainer;
63
64
65
66
67GvsPreprocessor::GvsPreprocessor():
68Preprocessor(),
69mProcessedViewCells(0),
70mCurrentViewCell(NULL),
71mCurrentViewPoint(Vector3(0.0f, 0.0f, 0.0f)),
72mOnlyRandomSampling(false)
73//mOnlyRandomSampling(true)
74{
75        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
76        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
77        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.gvsSamplesPerPass", mGvsSamplesPerPass);
78        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.minContribution", mMinContribution);
79        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
80        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
81        Environment::GetSingleton()->GetBoolValue("GvsPreprocessor.perViewCell", mPerViewCell);
82        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.maxViewCells", mMaxViewCells);
83
84        Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluatePixelError", mEvaluatePixelError);
85
86        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
87
88
89        char gvsStatsLog[100];
90        Environment::GetSingleton()->GetStringValue("GvsPreprocessor.stats", gvsStatsLog);
91        mGvsStatsStream.open(gvsStatsLog);
92
93        cout << "number of gvs samples per pass: " << mGvsSamplesPerPass << endl;
94        cout << "number of samples per pass: " << mSamplesPerPass << endl;
95        cout << "only random sampling: " << mOnlyRandomSampling << endl;
96
97        Debug << "Gvs preprocessor options" << endl;
98        Debug << "number of total samples: " << mTotalSamples << endl;
99        Debug << "number of initial samples: " << mInitialSamples << endl;
100        Debug << "threshold: " << mThreshold << endl;
101        Debug << "epsilon: " << mEps << endl;
102        Debug << "stats: " << gvsStatsLog << endl;
103        Debug << "per view cell: " << mPerViewCell << endl;
104        Debug << "max view cells: " << mMaxViewCells << endl;
105        Debug << "min contribution: " << mMinContribution << endl;
106
107        mDistribution = new ViewCellBasedDistribution(*this, NULL);
108
109        mGvsStats.Reset();
110
111        // hack: some generic statistical values that can be used
112        // by an application using the preprocessor
113        for (int i = 0; i < 2; ++ i)
114                mGenericStats[i] = 0;
115}
116
117
118GvsPreprocessor::~GvsPreprocessor()
119{
120        delete mDistribution;
121        ClearRayQueue();
122}
123
124
125void GvsPreprocessor::ClearRayQueue()
126{
127        // clean ray queue
128        while (!mRayQueue.empty())
129        {
130                // handle next ray
131                VssRay *ray = mRayQueue.top();
132                mRayQueue.pop();
133
134                // note: deletion of the ray is handled by ray pool
135        }
136}
137
138
139ViewCell *GvsPreprocessor::NextViewCell()
140{
141        if (mProcessedViewCells == (int)mViewCells.size())
142                return NULL; // no more view cells
143
144        ViewCell *vc = mViewCells[mProcessedViewCells];
145
146   if (!vc->GetMesh())
147                mViewCellsManager->CreateMesh(vc);
148
149        mGvsStats.mViewCellId = vc->GetId();
150
151        Debug << "vc: " << vc->GetId() << endl;
152
153        ++ mProcessedViewCells;
154   
155        return vc;
156}
157
158
159int GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
160                                                                                const Triangle3 &hitTriangle,
161                                                                                const VssRay &oldRay)
162{
163        // the predicted hitpoint: we expect to hit the same mesh again
164        Vector3 predictedHit = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
165
166        float predictedLen = Magnitude(predictedHit - currentRay.mOrigin);
167        float len = Magnitude(currentRay.mTermination - currentRay.mOrigin);
168       
169        // distance large => this is likely to be a discontinuity
170        if (!((predictedLen - len) > mThreshold))
171        // q: rather use relative distance?
172        //if ((predictedLen / len) > mThreshold)
173                return 0;
174
175        SimpleRay simpleRay;
176
177        // apply reverse sampling to find the gap
178        if (!ComputeReverseRay(currentRay, hitTriangle, oldRay, simpleRay))
179                return 0;
180
181        static VssRayContainer reverseRays;
182        reverseRays.clear();
183
184        if (0)
185        {
186                VssRay *reverseRay =
187                        mRayCaster->CastRay(simpleRay, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
188
189                reverseRays.push_back(reverseRay);
190        }
191        else
192        {
193                if (0)
194                        CastRayBundle4(simpleRay, reverseRays, mViewCellsManager->GetViewSpaceBox());
195                else
196                        CastRayBundle16(simpleRay, reverseRays);
197        }
198
199        mGvsStats.mReverseSamples += (int)reverseRays.size();
200
201        EnqueueRays(reverseRays);
202
203        return (int)reverseRays.size();
204}
205
206
207int GvsPreprocessor::CountObject(Intersectable *triObj)
208{
209        int numObjects = 0;
210
211        if ((triObj->mCounter != (NOT_ACCOUNTED_OBJECT + 1)) &&
212                (triObj->mCounter != (ACCOUNTED_OBJECT + 1)))
213        {
214                ++ triObj->mCounter;
215                ++ numObjects;
216        }
217
218        mGenericStats[1] += numObjects;
219
220        return numObjects;
221}
222
223
224void GvsPreprocessor::UpdateStatsForVisualization(KdIntersectable *kdInt)
225{
226        int numObj = 0;
227
228        // count new objects in pvs due to kd node conversion   
229        myobjects.clear();
230        // also gather duplicates to avoid mailing
231        mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
232
233        ObjectContainer::const_iterator oit, oit_end = myobjects.end();
234
235        for (oit = myobjects.begin(); oit != oit_end; ++ oit)
236                numObj += CountObject(*oit);
237
238        mViewCellsManager->UpdateStatsForViewCell(mCurrentViewCell, kdInt, numObj);
239}       
240
241
242void GvsPreprocessor::AddKdNodeToPvs(const Vector3 &termination)
243{
244        kdPvsTimer.Entry();
245
246        // exchange the triangle with the node in the pvs for kd pvs
247        KdNode *node = mKdTree->GetPvsNode(termination);
248
249        //KdNode *node = mKdTree->GetPvsNodeCheck(ray.mTermination, obj);
250        //if (!node) cerr << "e " << obj->GetBox() << " " << ray.mTermination << endl; else
251        if (!node->Mailed())
252        {
253                // add to pvs
254                node->Mail();
255                KdIntersectable *kdInt = mKdTree->GetOrCreateKdIntersectable(node);
256                mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
257
258                if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
259        }
260
261        kdPvsTimer.Exit();
262}
263
264
265bool GvsPreprocessor::HasContribution(VssRay &ray)
266{
267        if (!ray.mTerminationObject)
268                return false;
269
270        contributionTimer.Entry();
271
272        bool result;
273
274        if (!mPerViewCell)
275        {
276                // store the rays + the intersected view cells
277                const bool storeViewCells = false;
278
279                mViewCellsManager->ComputeSampleContribution(ray,
280                                                                                                         true,
281                                                                                                         storeViewCells,
282                                                                                                         true);
283
284                result = ray.mPvsContribution > 0;
285        }
286        else // original per view cell gvs
287        {
288                // test if triangle was accounted for yet
289                result = AddTriangleObject(ray.mTerminationObject);
290               
291                if (mUseKdPvs)
292                        AddKdNodeToPvs(ray.mTermination);
293        }
294
295        contributionTimer.Exit();
296
297        return result;
298}
299
300
301bool GvsPreprocessor::HandleRay(VssRay *vssRay)
302{
303        if (!HasContribution(*vssRay))
304                return false;
305
306        if (0 && GVS_DEBUG)
307                mVssRays.push_back(new VssRay(*vssRay));
308
309        // add new ray to ray queue
310        mRayQueue.push(vssRay);
311
312        ++ mGvsStats.mTotalContribution;
313
314        return true;
315}
316
317
318/** Creates 3 new vertices for triangle vertex with specified index.
319*/
320void GvsPreprocessor::CreateDisplacedVertices(VertexContainer &vertices,
321                                                                                          const Triangle3 &hitTriangle,
322                                                                                          const VssRay &ray,
323                                                                                          const int index) const
324{
325        const int indexU = (index + 1) % 3;
326        const int indexL = (index == 0) ? 2 : index - 1;
327
328        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
329        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
330        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
331       
332        const float len = Magnitude(a);
333       
334        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
335        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
336        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
337                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
338
339        // compute the new three hit points
340        // pi, i + 1:  pi+ e·|pi-xp|·di, j
341        const Vector3 pt1 = hitTriangle.mVertices[index] + mEps * len * dir1;
342        // pi, i - 1:  pi+ e·|pi-xp|·di, j
343    const Vector3 pt2 = hitTriangle.mVertices[index] + mEps * len * dir2;
344        // pi, i:  pi+ e·|pi-xp|·di, j
345        const Vector3 pt3 = hitTriangle.mVertices[index] + mEps * len * dir3;
346       
347        vertices.push_back(pt2);
348        vertices.push_back(pt3);
349        vertices.push_back(pt1);
350}
351
352
353void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
354                                                                          const Triangle3 &hitTriangle,
355                                                                          const VssRay &ray) const
356{
357        CreateDisplacedVertices(vertices, hitTriangle, ray, 0);
358        CreateDisplacedVertices(vertices, hitTriangle, ray, 1);
359        CreateDisplacedVertices(vertices, hitTriangle, ray, 2);
360}
361
362
363Vector3 GvsPreprocessor::CalcPredictedHitPoint(const VssRay &newRay,
364                                                                                           const Triangle3 &hitTriangle,
365                                                                                           const VssRay &oldRay) const
366{
367        // find the intersection of the plane induced by the
368        // hit triangle with the new ray
369        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
370
371        const Vector3 hitPt =
372                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
373       
374        return hitPt;
375}
376
377
378static bool EqualVisibility(const VssRay &a, const VssRay &b)
379{
380        return a.mTerminationObject == b.mTerminationObject;
381}
382
383
384int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
385                                                                   const Vector3 &p1,
386                                                                   const Vector3 &p2,
387                                                                   const VssRay &ray1,
388                                                                   const VssRay &ray2,
389                                                                   const VssRay &oldRay)
390{
391        //cout <<"y"<<Magnitude(p1 - p2) << " ";
392        int castRays = 0;
393
394        // cast reverse rays if necessary
395        castRays += CheckDiscontinuity(ray1, hitTriangle, oldRay);
396        castRays += CheckDiscontinuity(ray2, hitTriangle, oldRay);
397
398        if (EqualVisibility(ray1, ray2) || (SqrMagnitude(p1 - p2) <= MIN_DIST))
399        {
400                return castRays;
401        }
402       
403        // the new subdivision point
404        const Vector3 p = (p1 + p2) * 0.5f;
405        //cout << "p: " << p << " " << p1 << " " << p2 << endl;
406
407        SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
408
409        VssRay *newRay;
410
411        // cast single ray
412        castTimer.Entry();
413
414        // cast single ray to check if a triangle was missed. note: not efficient!!
415        newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
416        castTimer.Exit();
417
418        ++ castRays;
419
420        // this ray will not be further processed
421        // note: ray deletion is handled by ray pool
422        if (!newRay) return castRays;
423
424        rayTimer.Entry();
425
426        // new triangle discovered? => add new ray to queue
427        HandleRay(newRay);
428
429        rayTimer.Exit();
430       
431        //newRay->mFlags |= VssRay::BorderSample;
432
433        // subdivide further
434        castRays += SubdivideEdge(hitTriangle, p1, p, ray1, *newRay, oldRay);
435        castRays += SubdivideEdge(hitTriangle, p, p2, *newRay, ray2, oldRay);
436       
437        return castRays;
438}
439
440
441int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
442{
443        Intersectable *tObj = currentRay.mTerminationObject;
444
445        // question matt: can this be possible?
446        if (!tObj) return 0;
447
448        Triangle3 hitTriangle;
449
450        // other types not implemented yet
451        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
452                hitTriangle = static_cast<TriangleIntersectable *>(tObj)->GetItem();
453        else
454                cout << "border sampling: " << Intersectable::GetTypeName(tObj) << " not yet implemented" << endl;
455
456        //cout << "type: " << Intersectable::GetTypeName(tObj) << endl;
457        generationTimer.Entry();
458
459        static VertexContainer enlargedTriangle;
460        enlargedTriangle.clear();
461
462        /// create 3 new hit points for each vertex
463        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
464       
465        /// create rays from sample points and handle them
466        static SimpleRayContainer simpleRays;
467        simpleRays.clear();
468
469        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
470
471        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
472        {
473                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
474
475                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
476                simpleRays.AddRay(sr); 
477        }
478
479        if (0)
480        {
481                // visualize enlarged triangles
482                VizStruct dummy;
483                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
484                dummy.originalTriangle = hitTriangle;
485                vizContainer.push_back(dummy);
486        }
487
488       
489        //////////
490        //-- fill up simple rays with random rays so we can cast 16 rays at a time
491
492        const int numRandomRays = 16 - (int)simpleRays.size();
493        SimpleRay mainRay = SimpleRay(currentRay.GetOrigin(),
494                                          currentRay.GetNormalizedDir(),
495                                                                  SamplingStrategy::GVS,
496                                                                  1.0f);
497
498        GenerateJitteredRays(simpleRays, mainRay, numRandomRays, 0);
499        //GenerateRays(numRandomRays, *mDistribution, simpleRays, sInvalidSamples);
500
501        generationTimer.Exit();
502
503        /////////////////////
504        //-- cast rays to vertices and determine visibility
505       
506        static VssRayContainer vssRays;
507        vssRays.clear();
508
509        // for the original implementation we don't cast double rays
510        const bool castDoubleRays = !mPerViewCell;
511        // cannot prune invalid rays because we have to compare adjacent rays
512        const bool pruneInvalidRays = false;
513
514        //gvsTimer.Entry();
515        castTimer.Entry();
516
517        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
518       
519        castTimer.Exit();
520        //gvsTimer.Exit();
521
522        const int numBorderSamples = (int)vssRays.size() - numRandomRays;
523        int castRays = (int)simpleRays.size();
524
525        // handle cast rays
526        EnqueueRays(vssRays);
527
528        if (0)
529        {
530                // set flags
531                VssRayContainer::const_iterator rit, rit_end = vssRays.end();
532       
533                for (rit = vssRays.begin(); rit != rit_end; ++ rit)
534                        (*rit)->mFlags |= VssRay::BorderSample;
535        }
536
537    // recursivly subdivide each edge
538        for (int i = 0; i < numBorderSamples; ++ i)
539        {
540                castRays += SubdivideEdge(hitTriangle,
541                                                                  enlargedTriangle[i],
542                                                                  enlargedTriangle[(i + 1) % numBorderSamples],
543                                                                  *vssRays[i],
544                                                                  *vssRays[(i + 1) % numBorderSamples],
545                                                                  currentRay);
546        }
547       
548        mGvsStats.mBorderSamples += castRays;
549       
550        return castRays;
551}
552
553
554int GvsPreprocessor::AdaptiveBorderSamplingOpt(const VssRay &currentRay)
555{
556        Intersectable *tObj = currentRay.mTerminationObject;
557
558        // question matt: can this be possible?
559        if (!tObj) return 0;
560
561        Triangle3 hitTriangle;
562
563        // other types not implemented yet
564        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
565                hitTriangle = static_cast<TriangleIntersectable *>(tObj)->GetItem();
566        else
567                cout << "border sampling: " << Intersectable::GetTypeName(tObj) << " not yet implemented" << endl;
568
569        generationTimer.Entry();
570
571        static VertexContainer enlargedTriangle;
572        enlargedTriangle.clear();
573       
574        /// create 3 new hit points for each vertex
575        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
576
577        static VertexContainer subdivEnlargedTri;       
578        subdivEnlargedTri.clear();
579
580        for (size_t i = 0; i < enlargedTriangle.size(); ++ i)
581        {
582                const Vector3 p1 = enlargedTriangle[i];
583                const Vector3 p2 = enlargedTriangle[(i + 1) % enlargedTriangle.size()];
584
585                // the new subdivision point
586                const Vector3 p = (p1 + p2) * 0.5f;
587
588                subdivEnlargedTri.push_back(p1);
589                subdivEnlargedTri.push_back(p);
590        }
591
592        /// create rays from sample points and handle them
593        static SimpleRayContainer simpleRays;
594        simpleRays.clear();
595       
596        VertexContainer::const_iterator vit, vit_end = subdivEnlargedTri.end();
597
598        for (vit = subdivEnlargedTri.begin(); vit != vit_end; ++ vit)
599        {
600                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
601
602                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
603                simpleRays.AddRay(sr); 
604        }
605
606       
607        //////////
608        //-- fill up simple rays with random rays so we can cast 16 rays at a time
609
610        const int numRandomRays = 16 - ((int)simpleRays.size() % 16);
611
612        SimpleRay mainRay = SimpleRay(currentRay.GetOrigin(),
613                                                                  currentRay.GetNormalizedDir(),
614                                                                  SamplingStrategy::GVS, 1.0f);
615
616        GenerateJitteredRays(simpleRays, mainRay, numRandomRays, 0);
617        //GenerateRays(numRandomRays, *mDistribution, simpleRays, sInvalidSamples);
618
619        generationTimer.Exit();
620
621
622        /////////////////////
623        //-- cast rays to vertices and determine visibility
624       
625        static VssRayContainer vssRays;
626        vssRays.clear();
627
628        // for the original implementation we don't cast double rays
629        const bool castDoubleRays = !mPerViewCell;
630        // cannot prune invalid rays because we have to compare adjacent rays
631        const bool pruneInvalidRays = false;
632
633        //if ((simpleRays.size() % 16) != 0) cerr << "ray size not aligned" << endl;
634       
635        //gvsTimer.Entry();
636        castTimer.Entry();
637
638        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
639       
640        castTimer.Exit();
641        //gvsTimer.Exit();
642
643        const int numBorderSamples = (int)vssRays.size() - numRandomRays;
644        int castRays = (int)simpleRays.size();
645
646        // handle cast rays
647        EnqueueRays(vssRays);
648       
649#if 0
650       
651    // recursivly subdivide each edge
652        for (int i = 0; i < numBorderSamples; ++ i)
653        {
654                castRays += SubdivideEdge(hitTriangle,
655                                                                  subdivEnlargedTri[i],
656                                                                  subdivEnlargedTri[(i + 1) % numBorderSamples],
657                                                                  *vssRays[i],
658                                                                  *vssRays[(i + 1) % numBorderSamples],
659                                                                  currentRay);
660        }
661       
662#endif
663
664
665        mGvsStats.mBorderSamples += castRays;
666       
667        return castRays;
668}
669
670
671bool GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
672                                                                          const Triangle3 &occluder,
673                                                                          const VssRay &oldRay,
674                                                                          Vector3 &newPoint) const
675{
676        /////////////////////////
677        //-- We interserct the plane p = (xp, hit(x), hit(xold))
678        //-- with the newly found occluder (xold is the previous ray from
679        //-- which x was generated). On the intersecting line, we select a point
680        //-- pnew which lies just outside of the new triangle so the ray
681        //-- just passes through the gap
682
683        const Plane3 plane(currentRay.GetOrigin(),
684                                           currentRay.GetTermination(),
685                                           oldRay.GetTermination());
686       
687        Vector3 pt1, pt2;
688
689        if (!occluder.GetPlaneIntersection(plane, pt1, pt2))
690                return false;
691
692        // get the intersection point on the old ray
693        const Plane3 triPlane(occluder.GetNormal(), occluder.mVertices[0]);
694
695        const float t = triPlane.FindT(oldRay.mOrigin, oldRay.mTermination);
696        const Vector3 pt3 = oldRay.mOrigin + t * (oldRay.mTermination - oldRay.mOrigin);
697
698        // evaluate new hitpoint just outside the triangle
699        // the point is chosen to be on the side closer to the original ray
700        if (SqrDistance(pt1, pt3) < SqrDistance(pt2, pt3))
701                newPoint = pt1 + mEps * (pt1 - pt2);
702        else
703                newPoint = pt2 + mEps * (pt2 - pt1);
704
705        //cout << "passing point: " << newPoint << endl << endl;
706        return true;
707}
708
709
710bool GvsPreprocessor::ComputeReverseRay(const VssRay &currentRay,
711                                                                                const Triangle3 &hitTriangle,
712                                                                                const VssRay &oldRay,
713                                                                                SimpleRay &reverseRay)
714{
715        // get triangle occluding the path to the hit mesh
716        Triangle3 occluder;
717        Intersectable *tObj = currentRay.mTerminationObject;
718
719        // q: why can this happen?
720        if (!tObj)
721                return false;
722
723        // other types not implemented yet
724        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
725                occluder = static_cast<TriangleIntersectable *>(tObj)->GetItem();
726        else
727                cout << "reverse sampling: " << tObj->Type() << " not yet implemented" << endl;
728       
729        // get a point which is passing just outside of the occluder
730    Vector3 newPoint;
731
732        // q: why is there sometimes no intersecton found?
733        if (!GetPassingPoint(currentRay, occluder, oldRay, newPoint))
734                return false;
735
736        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
737
738        Vector3 newDir, newOrigin;
739
740        //////////////
741        //-- Construct the mutated ray with xnew,
742        //-- dir = predicted(x)- pnew as direction vector
743
744        newDir = predicted - newPoint;
745
746        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
747        // difficult to say!!
748        const float offset = 0.5f;
749        newOrigin = newPoint - newDir * offset;
750       
751
752        //////////////
753        //-- for per view cell sampling, we must check for intersection
754        //-- with the current view cell
755
756    if (mPerViewCell)
757        {
758                // send ray to view cell
759                static Ray ray;
760
761                ray.Clear();
762                ray.Init(newOrigin, -newDir, Ray::LOCAL_RAY);
763               
764                // check if ray intersects view cell
765                if (!mCurrentViewCell->CastRay(ray))
766                        return NULL;
767
768                Ray::Intersection &hit = ray.intersections[0];
769       
770                // the ray starts from the view cell
771                newOrigin = ray.Extrap(hit.mT);
772        }
773
774        reverseRay = SimpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
775
776        return true;
777}
778
779
780int GvsPreprocessor::CastInitialSamples(int numSamples)
781{       
782        initialTimer.Entry();
783
784        // generate simple rays
785        static SimpleRayContainer simpleRays;
786        simpleRays.clear();
787
788        generationTimer.Entry();
789
790        ViewCellBorderBasedDistribution vcStrat(*this, mCurrentViewCell);
791        GenerateRays(numSamples, *mDistribution, simpleRays, sInvalidSamples);
792
793        generationTimer.Exit();
794
795        // cast generated samples
796        static VssRayContainer vssRays;
797        vssRays.clear();
798
799        castTimer.Entry();
800
801        if (0)
802        {
803                const bool castDoubleRays = !mPerViewCell;
804                const bool pruneInvalidRays = false;
805                //const bool pruneInvalidRays = true;
806                CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
807        }
808        else
809        {
810                if (0)
811                        // casting bundles of 4 rays generated from the simple rays
812                        CastRayBundles4(simpleRays, vssRays);
813                else
814                        CastRayBundles16(simpleRays, vssRays);
815        }
816
817        castTimer.Exit();
818
819        // add to ray queue
820        EnqueueRays(vssRays);
821
822        initialTimer.Exit();
823
824        return (int)vssRays.size();
825}
826
827
828void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
829{
830        rayTimer.Entry();
831
832        // add samples to ray queue
833        VssRayContainer::const_iterator vit, vit_end = samples.end();
834        for (vit = samples.begin(); vit != vit_end; ++ vit)
835        {
836                VssRay *ray = *vit;
837                HandleRay(ray);
838                // note: deletion of invalid samples handked by ray pool
839        }
840
841        rayTimer.Exit();
842}
843
844
845int GvsPreprocessor::ProcessQueue()
846{
847        gvsTimer.Entry();
848
849        ++ mGvsStats.mGvsRuns;
850
851        int castSamples = 0;
852
853        while (!mRayQueue.empty())
854        {
855                // handle next ray
856                VssRay *ray = mRayQueue.top();
857                mRayQueue.pop();
858               
859                if (1)
860                        castSamples += AdaptiveBorderSampling(*ray);
861                else
862                        castSamples += AdaptiveBorderSamplingOpt(*ray);
863                // note: don't have to delete because handled by ray pool
864        }
865
866        gvsTimer.Exit();
867
868        return castSamples;
869}
870
871
872void ExportVssRays(Exporter *exporter, const VssRayContainer &vssRays)
873{
874        VssRayContainer vcRays, vcRays2, vcRays3;
875
876        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
877
878        // prepare some rays for output
879        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
880        {
881                //const float p = RandomValue(0.0f, (float)vssRays.size());
882
883                if (1)//(p < raysOut)
884                {
885                        if ((*rit)->mFlags & VssRay::BorderSample)
886                                vcRays.push_back(*rit);
887                        else if ((*rit)->mFlags & VssRay::ReverseSample)
888                                vcRays2.push_back(*rit);
889                        else
890                                vcRays3.push_back(*rit);
891                }
892        }
893
894        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
895        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
896        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
897}
898
899
900void GvsPreprocessor::VisualizeViewCell(const ObjectContainer &objects)
901{
902    Intersectable::NewMail();
903        Material m;
904       
905        char str[64]; sprintf_s(str, "pass%06d.wrl", mProcessedViewCells);
906
907        Exporter *exporter = Exporter::GetExporter(str);
908        if (!exporter)
909                return;
910
911        ObjectContainer::const_iterator oit, oit_end = objects.end();
912
913        for (oit = objects.begin(); oit != oit_end; ++ oit)
914        {
915                Intersectable *intersect = *oit;
916               
917                m = RandomMaterial();
918                exporter->SetForcedMaterial(m);
919                exporter->ExportIntersectable(intersect);
920        }
921
922        cout << "vssrays: " << (int)mVssRays.size() << endl;
923        ExportVssRays(exporter, mVssRays);
924
925
926        /////////////////
927        //-- export view cell geometry
928
929        //exporter->SetWireframe();
930
931        m.mDiffuseColor = RgbColor(0, 1, 0);
932        exporter->SetForcedMaterial(m);
933
934        AxisAlignedBox3 bbox = mCurrentViewCell->GetMesh()->mBox;
935        exporter->ExportBox(bbox);
936        //exporter->SetFilled();
937
938        delete exporter;
939}
940
941
942void GvsPreprocessor::VisualizeViewCells()
943{
944        char str[64]; sprintf_s(str, "tmp/pass%06d_%04d-", mProcessedViewCells, mPass);
945                       
946        // visualization
947        if (mGvsStats.mPassContribution > 0)
948        {
949                const bool exportRays = true;
950                const bool exportPvs = true;
951
952                mViewCellsManager->ExportSingleViewCells(mObjects,
953                                                                                                 10,
954                                                                                                 false,
955                                                                                                 exportPvs,
956                                                                                                 exportRays,
957                                                                                                 1000,
958                                                                                                 str);
959        }
960
961        // remove pass samples
962        ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
963
964        for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
965        {
966                (*vit)->DelRayRefs();
967        }
968}
969
970
971void GvsPreprocessor::CompileViewCellsFromPointList()
972{
973        ViewCell::NewMail();
974
975        // Receive list of view cells from view cells manager
976        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
977
978        vector<ViewCellPoints *>::const_iterator vit, vit_end = vcPoints->end();
979
980        for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
981        {
982                ViewCellPoints *vp = *vit;
983
984                if (vp->first) // view cell  specified
985                {
986                        ViewCell *viewCell = vp->first;
987
988                        if (!viewCell->Mailed())
989                        {
990                                viewCell->Mail();
991                                mViewCells.push_back(viewCell);
992
993                                if (mViewCells.size() >= mMaxViewCells)
994                                        break;
995                        }
996                }
997                else // no view cell specified => compute view cells using view point
998                {
999                        SimpleRayContainer::const_iterator rit, rit_end = vp->second.end();
1000
1001                        for (rit = vp->second.begin(); rit != rit_end; ++ rit)
1002                        {
1003                                SimpleRay ray = *rit;
1004
1005                                ViewCell *viewCell = mViewCellsManager->GetViewCell(ray.mOrigin);
1006
1007                                if (viewCell && !viewCell->Mailed())
1008                                {
1009                                        viewCell->Mail();
1010                                        mViewCells.push_back(viewCell);
1011
1012                                        if (mViewCells.size() >= mMaxViewCells)
1013                                                break;
1014                                }
1015                        }
1016                }
1017        }
1018}
1019
1020
1021void GvsPreprocessor::CompileViewCellsList()
1022{
1023        if (!mViewCellsManager->GetViewCellPointsList()->empty())
1024        {
1025                cout << "processing view point list" << endl;
1026                CompileViewCellsFromPointList();
1027        }
1028        else
1029        {
1030                ViewCell::NewMail();
1031
1032                while ((int)mViewCells.size() < mMaxViewCells)
1033                {
1034                        const int tries = 10000;
1035                        int i = 0;
1036
1037                        for (i = 0; i < tries; ++ i)
1038                        {
1039                                const int idx = (int)RandomValue(0.0f, (float)mViewCellsManager->GetNumViewCells() - 0.5f);
1040
1041                                ViewCell *viewCell = mViewCellsManager->GetViewCell(idx);
1042
1043                                if (!viewCell->Mailed())
1044                                {
1045                                        viewCell->Mail();
1046                                        break;
1047                                }
1048
1049                                mViewCells.push_back(viewCell);
1050                        }
1051
1052                        if (i == tries)
1053                        {
1054                                cerr << "big error! no view cell found" << endl;
1055                                break;
1056                        }
1057                }
1058        }
1059
1060        cout << "\ncomputing list of " << mViewCells.size() << " view cells" << endl;
1061}
1062
1063
1064void GvsPreprocessor::ComputeViewCellGeometryIntersection()
1065{
1066        intersectionTimer.Entry();
1067
1068        AxisAlignedBox3 box = mCurrentViewCell->GetBox();
1069
1070        int oldTrianglePvs = (int)mTrianglePvs.size();
1071        int newKdObj = 0;
1072
1073        // compute pvs kd nodes that intersect view cell
1074        ObjectContainer kdobjects;
1075
1076        // find intersecting objects not in pvs (i.e., only unmailed)
1077        mKdTree->CollectKdObjects(box, kdobjects);
1078
1079        ObjectContainer pvsKdObjects;
1080
1081        ObjectContainer::const_iterator oit, oit_end = kdobjects.end();
1082
1083        for (oit = kdobjects.begin(); oit != oit_end; ++ oit)
1084        {
1085        KdIntersectable *kdInt = static_cast<KdIntersectable *>(*oit);
1086       
1087                myobjects.clear();
1088                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
1089
1090                // account for kd object pvs
1091                bool addkdobj = false;
1092
1093                ObjectContainer::const_iterator oit, oit_end = myobjects.end();
1094
1095                for (oit = myobjects.begin(); oit != oit_end; ++ oit)
1096                {
1097                        TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(*oit);
1098             
1099                        // test if the triangle itself intersects
1100                        if (box.Intersects(triObj->GetItem()))
1101                                addkdobj = AddTriangleObject(triObj);
1102                }
1103               
1104                // add node to kd pvs
1105                if (1 && addkdobj)
1106                {
1107                        ++ newKdObj;
1108                        mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
1109                        //mCurrentViewCell->GetPvs().AddSampleDirtyCheck(kdInt, 1.0f);
1110                        if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
1111                }
1112        }
1113
1114        cout << "added " << (int)mTrianglePvs.size() - oldTrianglePvs << " triangles (" << newKdObj << " objects) by intersection" << endl;
1115
1116        intersectionTimer.Exit();
1117}
1118
1119
1120void GvsPreprocessor::PerViewCellComputation()
1121{
1122        while (mCurrentViewCell = NextViewCell())
1123        {
1124                preparationTimer.Entry();
1125
1126                // hack: reset counters (could be done with a mailing-like approach
1127                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
1128                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
1129                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
1130
1131                preparationTimer.Exit();
1132
1133                mDistribution->SetViewCell(mCurrentViewCell);
1134
1135        ComputeViewCell();
1136        }
1137}
1138
1139
1140void GvsPreprocessor::PerViewCellComputation2()
1141{
1142        while (1)
1143        {
1144                if (!mRendererWidget)
1145                        continue;
1146
1147        mCurrentViewCell = mViewCellsManager->GetViewCell(mRendererWidget->GetViewPoint());
1148
1149                // no valid view cell or view cell already computed
1150                if (!mCurrentViewCell || !mCurrentViewCell->GetPvs().Empty() || !mRendererWidget->mComputeGVS)
1151                        continue;
1152
1153                mRendererWidget->mComputeGVS = false;
1154                // hack: reset counters
1155                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
1156
1157                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
1158                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
1159
1160                ComputeViewCell();
1161                ++ mProcessedViewCells;
1162        }
1163}
1164
1165
1166void GvsPreprocessor::StorePvs(const ObjectContainer &objectPvs)
1167{
1168        ObjectContainer::const_iterator oit, oit_end = objectPvs.end();
1169
1170        for (oit = objectPvs.begin(); oit != oit_end; ++ oit)
1171        {
1172                mCurrentViewCell->GetPvs().AddSample(*oit, 1);
1173        }
1174}
1175
1176
1177void GvsPreprocessor::UpdatePvs(ViewCell *currentViewCell)
1178{
1179        ObjectPvs newPvs;
1180        BvhLeaf::NewMail();
1181
1182        ObjectPvsIterator pit = currentViewCell->GetPvs().GetIterator();
1183
1184        // output PVS of view cell
1185        while (pit.HasMoreEntries())
1186        {               
1187                Intersectable *intersect = pit.Next();
1188
1189                BvhLeaf *bv = intersect->mBvhLeaf;
1190
1191                if (!bv || bv->Mailed())
1192                        continue;
1193               
1194                bv->Mail();
1195
1196                //m.mDiffuseColor = RgbColor(1, 0, 0);
1197                newPvs.AddSampleDirty(bv, 1.0f);
1198        }
1199
1200        newPvs.SimpleSort();
1201
1202        currentViewCell->SetPvs(newPvs);
1203}
1204
1205 
1206void GvsPreprocessor::GetObjectPvs(ObjectContainer &objectPvs) const
1207{
1208        BvhLeaf::NewMail();
1209
1210        objectPvs.reserve((int)mTrianglePvs.size());
1211
1212        ObjectContainer::const_iterator oit, oit_end = mTrianglePvs.end();
1213
1214        for (oit = mTrianglePvs.begin(); oit != oit_end; ++ oit)
1215        {
1216                Intersectable *intersect = *oit;
1217       
1218                BvhLeaf *bv = intersect->mBvhLeaf;
1219
1220                // hack: reset counter
1221                (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
1222
1223                if (!bv || bv->Mailed())
1224                        continue;
1225
1226                bv->Mail();
1227                objectPvs.push_back(bv);
1228        }
1229}
1230
1231
1232void GvsPreprocessor::GlobalComputation()
1233{
1234        int passSamples = 0;
1235        int randomSamples = 0;
1236        int gvsSamples = 0;
1237        int oldContribution = 0;
1238
1239        while (mGvsStats.mTotalSamples < mTotalSamples)
1240        {
1241                mRayCaster->InitPass();
1242
1243                int newRandomSamples, newGvsSamples;
1244
1245                // Ray queue empty =>
1246                // cast a number of uniform samples to fill ray queue
1247                newRandomSamples = CastInitialSamples(mInitialSamples);
1248               
1249                if (!mOnlyRandomSampling)
1250                        newGvsSamples = ProcessQueue();
1251
1252                passSamples += newRandomSamples + newGvsSamples;
1253                mGvsStats.mTotalSamples += newRandomSamples + newGvsSamples;
1254
1255                mGvsStats.mRandomSamples += newRandomSamples;
1256                mGvsStats.mGvsSamples += newGvsSamples;
1257
1258
1259                if (passSamples % (mGvsSamplesPerPass + 1) == mGvsSamplesPerPass)
1260                {
1261                        ++ mPass;
1262
1263                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1264                       
1265                        ////////
1266                        //-- stats
1267
1268                        //cout << "\nPass " << mPass << " #samples: " << mGvsStats.mTotalSamples << " of " << mTotalSamples << endl;
1269                        mGvsStats.mPass = mPass;
1270                        mGvsStats.Stop();
1271                        mGvsStats.Print(mGvsStatsStream);
1272
1273                        // reset
1274                        oldContribution = mGvsStats.mTotalContribution;
1275                        mGvsStats.mPassContribution = 0;
1276                        passSamples = 0;
1277
1278                        if (GVS_DEBUG)
1279                                VisualizeViewCells();
1280                }
1281        }
1282}
1283
1284
1285bool GvsPreprocessor::ComputeVisibility()
1286{
1287        cout << "Gvs Preprocessor started\n" << flush;
1288        const long startTime = GetTime();
1289
1290        //Randomize(0);
1291        mGvsStats.Reset();
1292        mGvsStats.Start();
1293
1294        if (!mLoadViewCells)
1295        {       
1296                /// construct the view cells from the scratch
1297                ConstructViewCells();
1298                // reset pvs already gathered during view cells construction
1299                mViewCellsManager->ResetPvs();
1300                cout << "finished view cell construction" << endl;
1301        }
1302
1303        if (mPerViewCell)
1304        {
1305#if 1
1306                // provide list of view cells to compute
1307                CompileViewCellsList();
1308
1309                // start per view cell gvs
1310                PerViewCellComputation();
1311#else
1312                PerViewCellComputation2();
1313
1314#endif
1315        }
1316        else
1317        {
1318                GlobalComputation();
1319        }
1320
1321        cout << "cast " << mGvsStats.mTotalSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M single rays/s" << endl;
1322
1323        if (GVS_DEBUG)
1324        {
1325                Visualize();
1326                CLEAR_CONTAINER(mVssRays);
1327        }
1328       
1329        // export the preprocessed information to a file
1330        if (0 && mExportVisibility)
1331                ExportPreprocessedData(mVisibilityFileName);
1332       
1333        // compute the pixel error of this visibility solution
1334        if (0 && mEvaluatePixelError)
1335                ComputeRenderError();
1336
1337        return true;
1338}
1339
1340
1341void GvsPreprocessor::DeterminePvsObjects(VssRayContainer &rays)
1342{
1343        // store triangle directly
1344        mViewCellsManager->DeterminePvsObjects(rays, true);
1345}
1346
1347
1348void GvsPreprocessor::Visualize()
1349{
1350        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
1351
1352        if (!exporter)
1353                return;
1354       
1355        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
1356       
1357        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
1358        {
1359                exporter->SetWireframe();
1360                exporter->ExportPolygon((*vit).enlargedTriangle);
1361                //Material m;
1362                exporter->SetFilled();
1363                Polygon3 poly = Polygon3((*vit).originalTriangle);
1364                exporter->ExportPolygon(&poly);
1365        }
1366
1367        VssRayContainer::const_iterator rit, rit_end = mVssRays.end();
1368
1369        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
1370        {
1371                Intersectable *obj = (*rit)->mTerminationObject;
1372                exporter->ExportIntersectable(obj);
1373        }
1374
1375        ExportVssRays(exporter, mVssRays);
1376       
1377        delete exporter;
1378}
1379
1380
1381void GvsStatistics::Print(ostream &app) const
1382{
1383        app << "#ViewCells\n" << mViewCells << endl;
1384        app << "#Id\n" << mViewCellId << endl;
1385        app << "#Time\n" << mTimePerViewCell << endl;;
1386        app << "#TriPvs\n" << mTrianglePvs << endl;
1387        app << "#ObjectPvs\n" << mPerViewCellPvs << endl;
1388        app << "#UpdatedPvs\n" << (int)mPvsCost << endl;
1389
1390        app << "#PerViewCellSamples\n" << mPerViewCellSamples << endl;
1391        app << "#RaysPerSec\n" << RaysPerSec() << endl;
1392       
1393        app << "#TotalPvs\n" << mTotalPvs << endl;
1394        app << "#TotalTime\n" << mTotalTime << endl;
1395        app << "#TotalSamples\n" << mTotalSamples << endl;
1396
1397        app << "#AvgPvs: " << mPvsCost / mViewCells << endl;
1398        app << "#TotalTrianglePvs\n" << mTotalTrianglePvs << endl;
1399       
1400        if (0)
1401        {
1402                app << "#ReverseSamples\n" << mReverseSamples << endl;
1403                app << "#BorderSamples\n" << mBorderSamples << endl;
1404
1405                app << "#Pass\n" << mPass << endl;
1406                app << "#ScDiff\n" << mPassContribution << endl;
1407                app << "#GvsRuns\n" << mGvsRuns << endl;       
1408
1409                app     << "#SamplesContri\n" << mTotalContribution << endl;
1410        }
1411
1412        app << endl;
1413}
1414
1415
1416void GvsPreprocessor::ComputeViewCell()
1417{
1418        const long startTime = GetTime();
1419
1420        // initialise
1421        mGvsStats.mPerViewCellSamples = 0;
1422        mGvsStats.mRandomSamples = 0;
1423        mGvsStats.mGvsSamples = 0;
1424
1425        //renderer->mPvsStat.currentPass = 0;
1426        mPass = 0;
1427
1428        int oldContribution = 0;
1429        int passSamples = 0;
1430
1431        for (int i = 0; i < 2; ++ i)
1432                mGenericStats[i] = 0;
1433
1434        mTrianglePvs.clear();
1435
1436
1437        // hack: take bounding box of view cell as view cell bounds
1438        mCurrentViewCell->GetMesh()->ComputeBoundingBox();
1439
1440        // use mailing for kd node pvs
1441        KdNode::NewMail();
1442
1443        cout << "\n***********************\n"
1444                << "computing view cell " << mProcessedViewCells
1445                << " (id: " << mCurrentViewCell->GetId() << ")" << endl;
1446        cout << "bb: " << mCurrentViewCell->GetBox() << endl;
1447
1448        mainLoopTimer.Entry();
1449
1450        while (1)
1451        {
1452                sInvalidSamples = 0;
1453                int oldPvsSize = mCurrentViewCell->GetPvs().GetSize();
1454               
1455                mRayCaster->InitPass();
1456
1457                int newRandomSamples, newGvsSamples, newSamples;
1458
1459                // Ray queue empty =>
1460                // cast a number of uniform samples to fill ray queue
1461                newRandomSamples = CastInitialSamples(mInitialSamples);
1462               
1463                if (!mOnlyRandomSampling)
1464                        newGvsSamples = ProcessQueue();
1465
1466                newSamples = newRandomSamples + newGvsSamples;
1467
1468                passSamples += newSamples;
1469                mGvsStats.mPerViewCellSamples += newSamples;
1470
1471                mGvsStats.mRandomSamples += newRandomSamples;
1472                mGvsStats.mGvsSamples += newGvsSamples;
1473
1474
1475                if (passSamples >= mGvsSamplesPerPass)
1476                {
1477                        if (GVS_DEBUG) VisualizeViewCell(mTrianglePvs);
1478
1479                        //const bool convertPerPass = true;
1480                        const bool convertPerPass = false;
1481
1482                        if (convertPerPass)
1483                        {       
1484                                int newObjects = ConvertObjectPvs();
1485
1486                                cout << "added " << newObjects << " triangles to triangle pvs" << endl;
1487                                mGvsStats.mTotalContribution += newObjects;
1488                        }
1489
1490                        ++ mPass;
1491                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1492
1493
1494                        ////////
1495                        //-- stats
1496
1497                        mGvsStats.mPass = mPass;
1498
1499                        cout << "\nPass " << mPass << " #samples: " << mGvsStats.mPerViewCellSamples << endl;
1500                        cout << "contribution=" << mGvsStats.mPassContribution << " (of " << mMinContribution << ")" << endl;
1501                        cout << "obj contri=" << mCurrentViewCell->GetPvs().GetSize() - oldPvsSize << " (of " << mMinContribution << ")" << endl;
1502
1503                        // termination criterium
1504                        if (mGvsStats.mPassContribution < mMinContribution)
1505                                break;
1506
1507                        // reset stats
1508                        oldContribution = mGvsStats.mTotalContribution;
1509                        mGvsStats.mPassContribution = 0;
1510                        passSamples = 0;
1511                       
1512                        // compute the pixel error of this visibility solution
1513                        if (mEvaluatePixelError)
1514                                ComputeRenderError();
1515                }
1516        }
1517       
1518        mainLoopTimer.Exit();
1519
1520        // at last compute objects that directly intersect view cell
1521        ComputeViewCellGeometryIntersection();
1522               
1523
1524        ////////
1525        //-- stats
1526
1527        // timing
1528        mGvsStats.mTimePerViewCell = TimeDiff(startTime, GetTime()) * 1e-3f;
1529
1530        ComputeStats();
1531}
1532
1533
1534void GvsPreprocessor::ComputeStats()
1535{
1536        // compute pvs size using larger (bvh objects)
1537        // note: for kd pvs we had to do this during gvs computation
1538        if (!mUseKdPvs)
1539        {
1540                ObjectContainer objectPvs;
1541
1542                // optain object pvs
1543                GetObjectPvs(objectPvs);
1544
1545                // add pvs
1546                ObjectContainer::const_iterator it, it_end = objectPvs.end();
1547
1548                for (it = objectPvs.begin(); it != it_end; ++ it)
1549                {
1550                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1551                }
1552
1553                cout << "triangle pvs of " << (int)mTrianglePvs.size()
1554                        << " was converted to object pvs of " << (int)objectPvs.size() << endl;
1555
1556                mGvsStats.mPerViewCellPvs = (int)objectPvs.size();
1557                mGvsStats.mPvsCost = 0; // todo objectPvs.EvalPvsCost();
1558        }
1559        else
1560        {
1561                 if (0) // compute pvs kd nodes that intersect view cell
1562                 {
1563                         ObjectContainer mykdobjects;
1564
1565                         // extract kd pvs
1566                         ObjectContainer::const_iterator it, it_end = mTrianglePvs.end();
1567
1568                         for (it = mTrianglePvs.begin(); it != it_end; ++ it)
1569                         {
1570                                 Intersectable *obj = *it;
1571                                 // find intersecting objects not yet in pvs (i.e., only unmailed)
1572                                 mKdTree->CollectKdObjects(obj->GetBox(), mykdobjects);
1573                         }
1574
1575                         // add pvs
1576                         it_end = mykdobjects.end();
1577
1578                         for (it = mykdobjects.begin(); it != it_end; ++ it)
1579                         {
1580                                 mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1581                         }
1582                 
1583                         cout << "added " << (int)mykdobjects.size() << " new objects " << endl;
1584                 }
1585
1586                 mGvsStats.mPerViewCellPvs = mCurrentViewCell->GetPvs().GetSize();
1587                 mGvsStats.mPvsCost = mCurrentViewCell->GetPvs().EvalPvsCost();
1588
1589        }
1590
1591        mGvsStats.mTrianglePvs = (int)mTrianglePvs.size();
1592
1593
1594        ////////////////
1595        // global values
1596
1597        mGvsStats.mViewCells = mProcessedViewCells;
1598        mGvsStats.mTotalTrianglePvs += mGvsStats.mTrianglePvs;
1599        mGvsStats.mTotalTime += mGvsStats.mTimePerViewCell;
1600    mGvsStats.mTotalPvs += mGvsStats.mPerViewCellPvs;
1601        mGvsStats.mTotalSamples += mGvsStats.mPerViewCellSamples;
1602
1603        cout << "id: " << mCurrentViewCell->GetId() << endl;
1604        cout << "pvs cost "  << mGvsStats.mPvsCost / 1000000 << " M" << endl;
1605        cout << "pvs tri: " << mTrianglePvs.size() << endl;
1606        cout << "samples: " << mGvsStats.mTotalSamples / 1000000 << " M" << endl;
1607        printf("contri: %f tri / K rays\n", 1000.0f * (float)mTrianglePvs.size() / mGvsStats.mTotalSamples);
1608
1609        //cout << "invalid samples ratio: " << (float)sInvalidSamples / mGvsStats.mPerViewCellSamples << endl;
1610
1611        double rayTime = rayTimer.TotalTime();
1612        double kdPvsTime = kdPvsTimer.TotalTime();
1613        double gvsTime = gvsTimer.TotalTime();
1614        double initialTime = initialTimer.TotalTime();
1615        double intersectionTime = intersectionTimer.TotalTime();
1616        double preparationTime = preparationTimer.TotalTime();
1617        double mainLoopTime = mainLoopTimer.TotalTime();
1618        double contributionTime = contributionTimer.TotalTime();
1619        double castTime = castTimer.TotalTime();
1620        double generationTime = generationTimer.TotalTime();
1621        double rawCastTime = mRayCaster->rawCastTimer.TotalTime();
1622
1623        cout << "handleRay              : " << rayTime << endl;
1624        cout << "kd pvs                 : " << kdPvsTime << endl;
1625        cout << "gvs sampling           : " << gvsTime << endl;
1626        cout << "initial sampling       : " << initialTime << endl;
1627        cout << "view cell intersection : " << intersectionTime << endl;
1628        cout << "preparation            : " << preparationTime << endl;
1629        cout << "main loop              : " << mainLoopTime << endl;
1630        cout << "has contribution       : " << contributionTime << endl;
1631        cout << "cast time              : " << castTime << endl;
1632        cout << "generation time        : " << generationTime << endl;
1633        cout << "raw cast time          : " << rawCastTime << endl;
1634
1635        double randomRaysPerSec = mGvsStats.mRandomSamples / (1e6 * initialTime);
1636        double gvsRaysPerSec = mGvsStats.mGvsSamples / (1e6 * gvsTime);
1637        double rawRaysPerSec = mGvsStats.mPerViewCellSamples / (1e6 * rawCastTime);
1638
1639        cout << "cast " << randomRaysPerSec << " M random rays/s: " << endl;
1640        cout << "cast " << gvsRaysPerSec << " M gvs rays/s: " << endl;
1641        cout << "cast " << rawRaysPerSec << " M raw rays/s: " << endl;
1642
1643        mGvsStats.Stop();
1644        mGvsStats.Print(mGvsStatsStream);
1645}
1646
1647
1648int GvsPreprocessor::ConvertObjectPvs()
1649{
1650        static ObjectContainer triangles;
1651
1652        int newObjects = 0;
1653
1654        ObjectPvsIterator pit = mCurrentViewCell->GetPvs().GetIterator();
1655
1656        triangles.clear();
1657
1658        // output PVS of view cell
1659        while (pit.HasMoreEntries())
1660        {               
1661                KdIntersectable *kdInt = static_cast<KdIntersectable *>(pit.Next());
1662
1663                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), triangles);
1664
1665                ObjectContainer::const_iterator oit, oit_end = triangles.end();
1666
1667                for (oit = triangles.begin(); oit != oit_end; ++ oit)
1668                {
1669                        if (AddTriangleObject(*oit))
1670                                ++ newObjects;
1671                }
1672        }
1673
1674        return newObjects;
1675}
1676
1677
1678bool GvsPreprocessor::AddTriangleObject(Intersectable *triObj)
1679{
1680        if ((triObj->mCounter < ACCOUNTED_OBJECT))
1681        {
1682                triObj->mCounter += ACCOUNTED_OBJECT;
1683
1684                mTrianglePvs.push_back(triObj);
1685                mGenericStats[0] = (int)mTrianglePvs.size();
1686
1687                return true;
1688        }
1689
1690        return false;
1691}
1692
1693
1694void GvsPreprocessor::CastRayBundles4(const SimpleRayContainer &rays, VssRayContainer &vssRays)
1695{
1696        AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1697
1698        SimpleRayContainer::const_iterator it, it_end = rays.end();
1699
1700        for (it = rays.begin(); it != it_end; ++ it)
1701                CastRayBundle4(*it, vssRays, box);
1702}
1703
1704
1705void GvsPreprocessor::CastRayBundle4(const SimpleRay &ray,
1706                                                                         VssRayContainer &vssRays,
1707                                                                         const AxisAlignedBox3 &box)
1708{
1709        const float pertubDir = 0.01f;
1710        static Vector3 pertub;
1711
1712        static int hit_triangles[4];
1713        static float dist[4];
1714        static Vector3 dirs[4];
1715        static Vector3 origs[4];
1716
1717        origs[0] = ray.mOrigin;
1718        dirs[0] = ray.mDirection;
1719
1720        for (int i = 1; i < 4; ++ i)
1721        {
1722                origs[i] = ray.mOrigin;
1723
1724                pertub.x = RandomValue(-pertubDir, pertubDir);
1725                pertub.y = RandomValue(-pertubDir, pertubDir);
1726                pertub.z = RandomValue(-pertubDir, pertubDir);
1727
1728                dirs[i] = ray.mDirection + pertub;
1729                dirs[i] *= 1.0f / Magnitude(dirs[i]);
1730        }
1731
1732        Cast4Rays(dist, dirs, origs, vssRays, box);
1733}
1734
1735
1736void GvsPreprocessor::CastRays4(const SimpleRayContainer &rays, VssRayContainer &vssRays)
1737{
1738        SimpleRayContainer::const_iterator it, it_end = rays.end();
1739       
1740        static float dist[4];
1741        static Vector3 dirs[4];
1742        static Vector3 origs[4];
1743
1744        AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1745
1746        for (it = rays.begin(); it != it_end; ++ it)
1747        {
1748                for (int i = 1; i < 4; ++ i)
1749                {
1750                        origs[i] = rays[i].mOrigin;
1751                        dirs[i] = rays[i].mDirection;
1752                }
1753        }
1754
1755        Cast4Rays(dist, dirs, origs, vssRays, box);
1756}
1757
1758
1759void GvsPreprocessor::Cast4Rays(float *dist,
1760                                                                Vector3 *dirs,
1761                                                                Vector3 *origs,
1762                                                                VssRayContainer &vssRays,
1763                                                                const AxisAlignedBox3 &box)
1764{
1765        static int hit_triangles[4];
1766
1767        mRayCaster->CastRaysPacket4(box.Min(), box.Max(), origs, dirs, hit_triangles,   dist);       
1768
1769        VssRay *ray;
1770
1771        for (int i = 0; i < 4; ++ i)
1772        {
1773                if (hit_triangles[i] != -1)
1774                {
1775                        TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(mObjects[hit_triangles[i]]);
1776
1777                        if (DotProd(triObj->GetItem().GetNormal(), dirs[i] >= 0))
1778                                ray = NULL;
1779                        else
1780                                ray = mRayCaster->RequestRay(origs[i], origs[i] + dirs[i] * dist[i], NULL, triObj, mPass, 1.0f);
1781                }
1782                else
1783                {
1784                        ray = NULL;
1785                }
1786
1787                vssRays.push_back(ray);
1788        }
1789}
1790
1791
1792void GvsPreprocessor::CastRayBundle16(const SimpleRay &ray, VssRayContainer &vssRays)
1793{
1794        static SimpleRayContainer simpleRays;
1795        simpleRays.clear();
1796
1797        simpleRays.push_back(ray);
1798        GenerateJitteredRays(simpleRays, ray, 15, 0);
1799
1800        CastRays(simpleRays, vssRays, false, false);
1801}
1802
1803
1804void GvsPreprocessor::CastRayBundles16(const SimpleRayContainer &rays, VssRayContainer &vssRays)
1805{
1806        SimpleRayContainer::const_iterator it, it_end = rays.end();
1807
1808        for (it = rays.begin(); it != it_end; ++ it)
1809                CastRayBundle16(*it, vssRays);
1810}
1811
1812
1813void GvsPreprocessor::ComputeRenderError()
1814{
1815        // compute rendering error     
1816        if (renderer && renderer->mPvsStatFrames)
1817        {
1818                if (!mViewCellsManager->GetViewCellPointsList()->empty())
1819                {
1820                        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
1821                        ViewCellPointsList::const_iterator vit = vcPoints->begin(),     vit_end = vcPoints->end();
1822
1823                        SimpleRayContainer viewPoints;
1824
1825                        for (; vit != vit_end; ++ vit)
1826                        {
1827                                ViewCellPoints *vp = *vit;
1828                               
1829                                SimpleRayContainer::const_iterator rit = vp->second.begin(), rit_end = vp->second.end();
1830                       
1831                                for (; rit!=rit_end; ++rit)
1832                                {
1833                                        ViewCell *vc = mViewCellsManager->GetViewCell((*rit).mOrigin);
1834                                        if (vc == mCurrentViewCell)
1835                                                viewPoints.push_back(*rit);
1836                                }
1837                        }
1838
1839                        renderer->mPvsErrorBuffer.clear();
1840
1841                        if (viewPoints.size() != renderer->mPvsErrorBuffer.size())
1842                        {
1843                                renderer->mPvsErrorBuffer.resize(viewPoints.size());
1844                                renderer->ClearErrorBuffer();
1845                        }
1846
1847                        cout << "evaluating list of " << viewPoints.size() << " pts" << endl;
1848                        renderer->EvalPvsStat(viewPoints);
1849                }
1850                else
1851                {
1852                        cout << "evaluating random points" << endl;
1853                        renderer->EvalPvsStat();
1854                }
1855
1856                mStats <<
1857                        "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
1858                        "#AvgPixelError\n" <<renderer->GetAvgPixelError()<<endl<<
1859                        "#MaxPixelError\n" <<renderer->GetMaxPixelError()<<endl<<
1860                        "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
1861                        "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
1862                        "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
1863        }
1864}
1865
1866
1867SimpleRay GvsPreprocessor::GenerateJitteredSample(const SimpleRay &sray)
1868{
1869        // mutate the origin
1870        Vector3 d = sray.mDirection;
1871 
1872        // Compute right handed coordinate system from direction
1873        Vector3 U, V;
1874        d.RightHandedBase(U, V);
1875
1876        float rr[2];
1877
1878        rr[0] = RandomValue(0, 1);
1879        rr[1] = RandomValue(0, 1);
1880
1881        Vector2 vr2(rr[0], rr[1]);
1882        Vector2 gaussvec2;
1883
1884        const float sigma = 0.2f;
1885
1886        GaussianOn2D(vr2, sigma, // input
1887                         gaussvec2); // output
1888       
1889        Vector3 shift = gaussvec2.xx * U + gaussvec2.yy * V;
1890       
1891        d += shift;
1892 
1893        d.Normalize();
1894
1895        return SimpleRay(sray.mOrigin, d, SamplingStrategy::GVS, 1.0f);
1896}
1897
1898
1899}
Note: See TracBrowser for help on using the repository browser.