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

Revision 1696, 14.2 KB checked in by mattausch, 18 years ago (diff)

removed memory leaks

  • Property svn:executable set to *
RevLine 
[1460]1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
[1473]4#include "VssRay.h"
5#include "ViewCellsManager.h"
[1486]6#include "Triangle3.h"
[1489]7#include "IntersectableWrapper.h"
[1500]8#include "Plane3.h"
[1521]9#include "RayCaster.h"
[1522]10#include "Exporter.h"
[1545]11#include "SamplingStrategy.h"
[1460]12
[1473]13
[1460]14namespace GtpVisibilityPreprocessor
15{
16 
[1522]17struct VizStruct
18{
19        Polygon3 *enlargedTriangle;
20        Triangle3 originalTriangle;
21        VssRay *ray;
22};
[1460]23
[1522]24static vector<VizStruct> vizContainer;
25
[1533]26GvsPreprocessor::GvsPreprocessor():
[1545]27Preprocessor(),
28//mSamplingType(SamplingStrategy::DIRECTION_BASED_DISTRIBUTION),
29mSamplingType(SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION),
30mSampleContriPerPass(0),
31mTotalSampleContri(0),
32mReverseSamples(0),
33mBorderSamples(0)
[1460]34{
[1486]35        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
36        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
37        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.samplesPerPass", mSamplesPerPass);
38        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
[1500]39        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
[1473]40
[1486]41        Debug << "Gvs preprocessor options" << endl;
42        Debug << "number of total samples: " << mTotalSamples << endl;
43        Debug << "number of initial samples: " << mInitialSamples << endl;
44        Debug << "number of samples per pass: " << mSamplesPerPass << endl;
[1501]45        Debug << "threshold: " << mThreshold << endl;
46        Debug << "eps: " << mEps << endl;
[1486]47
48        mStats.open("gvspreprocessor.log");
[1460]49}
50
[1473]51
[1500]52bool GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
53                                                                                 const Triangle3 &hitTriangle,
54                                                                                 const VssRay &oldRay)
[1460]55{
[1500]56        const float dist = Magnitude(oldRay.GetDir());
57        const float newDist = Magnitude(currentRay.GetDir());
58 
59#if 0
60        if ((dist - newDist) > mThresHold)
[1545]61#else
62        // rather take relative distance
[1500]63        if ((dist / newDist) > mThreshold)
64#endif
65        {
66                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
[1572]67                // set flag for visualization
[1571]68                newRay->mFlags |= VssRay::ReverseSample;
[1580]69               
[1570]70                // ray is not pushed into the queue => can delete ray
[1521]71                if (!HandleRay(newRay))
72                        delete newRay;
[1570]73               
[1500]74                return true;
75        }
76
[1486]77        return false;
78}
[1473]79
[1486]80
[1521]81bool GvsPreprocessor::HandleRay(VssRay *vssRay)
[1486]82{
[1570]83        const bool storeRaysForViz = true;
84        mViewCellsManager->ComputeSampleContribution(*vssRay, true, storeRaysForViz);
[1528]85               
86        // some pvs contribution for this ray?
87        if (vssRay->mPvsContribution > 0)
88        {
[1580]89                // add new ray to ray queue
[1521]90                mRayQueue.push(vssRay);
[1570]91
92                if (storeRaysForViz)
93                {
94                        ViewCellContainer::const_iterator vit, vit_end = vssRay->mViewCells.end();
95                        for (vit = vssRay->mViewCells.begin(); vit != vit_end; ++ vit)
96                        {
[1571]97                                VssRay *nray = new VssRay(*vssRay);
[1696]98                                (*vit)->GetOrCreateRays()->push_back(nray);                             
[1570]99                        }
100                }
101                //mVssRays.push_back(new VssRay(*vssRay));
[1545]102        ++ mSampleContriPerPass;
[1533]103
[1500]104                return true;
[1473]105        }
[1500]106
107        return false;
[1460]108}
109
[1500]110
111/** Creates 3 new vertices for triangle vertex with specified index.
[1489]112*/
[1500]113static void CreateNewVertices(VertexContainer &vertices,
114                                                          const Triangle3 &hitTriangle,
115                                                          const VssRay &ray,
116                                                          const int index,
117                                                          const float eps)
[1460]118{
[1486]119        const int indexU = (index + 1) % 3;
120        const int indexL = (index == 0) ? 2 : index - 1;
121
[1524]122        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
[1486]123        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
124        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
[1492]125       
[1533]126        const float len = Magnitude(a);
[1486]127
[1523]128        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
129        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
[1524]130        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
131                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
[1492]132
[1486]133        // compute the new three hit points
[1500]134        // pi, i + 1:  pi+ e·|pi-xp|·di, j
135        const Vector3 pt1 = hitTriangle.mVertices[index] + eps * len * dir1;
136        // pi, i - 1:  pi+ e·|pi-xp|·di, j
137    const Vector3 pt2 = hitTriangle.mVertices[index] + eps * len * dir2;
138        // pi, i:  pi+ e·|pi-xp|·di, j
139        const Vector3 pt3 = hitTriangle.mVertices[index] + eps * len * dir3;
[1489]140       
[1524]141        vertices.push_back(pt2);
142        vertices.push_back(pt3);
[1500]143        vertices.push_back(pt1);
[1489]144}
145
146
[1500]147void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
148                                                                          const Triangle3 &hitTriangle,
149                                                                          const VssRay &ray)
150{
151        CreateNewVertices(vertices, hitTriangle, ray, 0, mEps);
152        CreateNewVertices(vertices, hitTriangle, ray, 1, mEps);
153        CreateNewVertices(vertices, hitTriangle, ray, 2, mEps);
154}
[1492]155
[1500]156
157static Vector3 CalcPredictedHitPoint(const VssRay &newRay,
158                                                                         const Triangle3 &hitTriangle,
159                                                                         const VssRay &oldRay)
[1489]160{
[1500]161        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
162
163        const Vector3 hitPt =
164                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
165       
166        return hitPt;
167}
168
169
170static bool EqualVisibility(const VssRay &a, const VssRay &b)
171{
172        return a.mTerminationObject == b.mTerminationObject;
173}
174
175
176int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
177                                                                   const Vector3 &p1,
178                                                                   const Vector3 &p2,
179                                                                   const VssRay &x,
180                                                                   const VssRay &y,
181                                                                   const VssRay &oldRay)
182{
183        // the predicted hitpoint expects to hit the same mesh again
184        const Vector3 predictedHitX = CalcPredictedHitPoint(x, hitTriangle, oldRay);
185        const Vector3 predictedHitY = CalcPredictedHitPoint(y, hitTriangle, oldRay);
186
187        CheckDiscontinuity(x, hitTriangle, oldRay);
188        CheckDiscontinuity(y, hitTriangle, oldRay);
189
190        if (EqualVisibility(x, y))
191        {
[1533]192                return 0;
[1500]193        }
194        else
195        {
[1533]196                cout << "s";
[1500]197                const Vector3 p = (p1 + p2) * 0.5f;
198                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin);
[1521]199       
[1566]200                // cast ray into the new subdivision point
[1563]201                VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), false);
[1571]202               
[1551]203                if (!newRay) return 0;
[1580]204
205                newRay->mFlags |= VssRay::BorderSample;
206
207                // add new ray to queue
[1522]208                const bool enqueued = HandleRay(newRay);
[1521]209               
[1566]210                // subdivide further
[1500]211                const int s1 = SubdivideEdge(hitTriangle, p1, p, x, *newRay, oldRay);
212                const int s2 = SubdivideEdge(hitTriangle, p, p2, *newRay, y, oldRay);
[1533]213                               
[1522]214                if (!enqueued)
[1521]215                        delete newRay;
[1533]216               
217                return s1 + s2 + 1;
[1500]218        }
219}
220
221
222int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
223{
[1486]224        cout << "a";
[1500]225        Intersectable *tObj = currentRay.mTerminationObject;
[1486]226        Triangle3 hitTriangle;
[1489]227
228        // other types not implemented yet
229        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
230        {
231                hitTriangle = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
232        }
[1522]233        else
234        {
235                cout << "not yet implemented" << endl;
236        }
[1489]237
[1500]238        VertexContainer enlargedTriangle;
239       
240        /// create 3 new hit points for each vertex
241        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
242       
243        /// create rays from sample points and handle them
[1492]244        SimpleRayContainer simpleRays;
245        simpleRays.reserve(9);
[1486]246
[1500]247        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
[1486]248
[1500]249        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
250        {
251                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
[1528]252                SimpleRay sr(currentRay.GetOrigin(), rayDir);
253                simpleRays.AddRay(sr);
[1500]254        }
[1522]255
[1566]256        if (0)
257        {
258                VizStruct dummy;
259                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
260                dummy.originalTriangle = hitTriangle;
261                //dummy.ray = new VssRay(currentRay);
262                vizContainer.push_back(dummy);
263        }
264
[1524]265        // cast rays to triangle vertices and determine visibility
[1489]266        VssRayContainer vssRays;
[1528]267        CastRays(simpleRays, vssRays, false, false);
[1533]268
[1580]269        // set flags
270        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
271        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
[1595]272        {
[1580]273                (*rit)->mFlags |= VssRay::BorderSample;
274        }
[1595]275
[1492]276        // add to ray queue
277        EnqueueRays(vssRays);
[1528]278       
[1524]279        const int n = (int)enlargedTriangle.size();
[1533]280        int castRays = (int)vssRays.size();
[1571]281
[1500]282    // recursivly subdivide each edge
[1595]283        for (int i = 0; 1 && (i < n); ++ i)
[1500]284        {
[1533]285                castRays += SubdivideEdge(
[1500]286                        hitTriangle,
287                        enlargedTriangle[i],
[1524]288                        enlargedTriangle[(i + 1) % n],
[1500]289                        *vssRays[i],
[1524]290                        *vssRays[(i + 1) % n],
[1500]291                        currentRay);
292        }
[1533]293
[1545]294        mBorderSamples += castRays;
[1533]295        return castRays;
[1473]296}
297
298
[1500]299static Vector3 GetPassingPoint(const VssRay &currentRay,
[1533]300                                                           const Triangle3 &hitTriangle,
301                                                           const VssRay &oldRay)
[1473]302{
[1500]303        // intersect triangle plane with plane spanned by current samples
304        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
305        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
306
307        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
308
309        // Evaluate new hitpoint just outside the triangle
310        const float factor = 0.95f;
311        float t = triPlane.FindT(intersectLine);
312        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
313
314        return newPoint;
315}
316
317
318VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
319                                                                                 const Triangle3 &hitTriangle,
320                                                                                 const VssRay &oldRay)
321{
322        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
323        //-- with the newly found triangle (xold is the previous ray from
324        //-- which x was generated). On the intersecting line, we select a point
325        //-- pnew which lies just outside of the new triangle so the ray
326        //-- just passes by inside the gap
327    const Vector3 newPoint = GetPassingPoint(currentRay, hitTriangle, oldRay);
328        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
329
330        //-- Construct the mutated ray with xnew,dir = predicted(x)- pnew
331        //-- as direction vector
332        const Vector3 newDir = predicted - newPoint ;
333        // take xnew,p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
334        // difficult to say!!
335        const Vector3 newOrigin = newDir * -5000.0f;
336
[1571]337        ++ mReverseSamples;
338
[1500]339        return new VssRay(currentRay);
[1473]340}
341
[1489]342
343int GvsPreprocessor::CastInitialSamples(const int numSamples,
344                                                                                const int sampleType)
345{       
[1473]346        const long startTime = GetTime();
[1595]347
[1489]348        // generate simple rays
349        SimpleRayContainer simpleRays;
350        GenerateRays(numSamples, sampleType, simpleRays);
[1528]351
[1489]352        // generate vss rays
[1473]353        VssRayContainer samples;
[1520]354        CastRays(simpleRays, samples, true);
[1489]355        // add to ray queue
[1492]356        EnqueueRays(samples);
[1533]357
[1545]358        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
[1489]359        return (int)samples.size();
360}
361
362
[1500]363void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
[1489]364{
[1486]365        // add samples to ray queue
[1473]366        VssRayContainer::const_iterator vit, vit_end = samples.end();
[1576]367        for (vit = samples.begin(); vit != vit_end; ++ vit)
[1473]368        {
[1521]369                HandleRay(*vit);
[1460]370        }
371}
372
[1473]373
[1486]374int GvsPreprocessor::Pass()
[1460]375{
[1528]376        // reset samples
[1533]377        int castSamples = 0;
378        mSampleContriPerPass = 0;
[1545]379
[1533]380        while (castSamples < mSamplesPerPass)
[1528]381        {       
[1473]382                // Ray queue empty =>
[1545]383                // cast a number of uniform samples to fill ray queue
384                castSamples += CastInitialSamples(mInitialSamples, mSamplingType);
[1533]385                castSamples += ProcessQueue();
[1545]386                //cout << "\ncast " << castSamples << " samples in a processing pass" << endl;
[1473]387        }
388
[1533]389        mTotalSampleContri += mSampleContriPerPass;
390        return castSamples;
[1460]391}
392
[1473]393
[1489]394int GvsPreprocessor::ProcessQueue()
[1460]395{
[1473]396        int castSamples = 0;
[1545]397        ++ mGvsPass;
[1473]398
399        while (!mRayQueue.empty())
400        {
401                // handle next ray
[1500]402                VssRay *ray = mRayQueue.top();
[1473]403                mRayQueue.pop();
[1545]404
[1501]405                castSamples += AdaptiveBorderSampling(*ray);
[1521]406                delete ray;
[1460]407        }
[1528]408       
[1473]409        return castSamples;
[1460]410}
411
412
[1489]413bool GvsPreprocessor::ComputeVisibility()
[1460]414{
[1533]415        cout << "Gvs Preprocessor started\n" << flush;
[1545]416        const long startTime = GetTime();
[1533]417
[1473]418        Randomize(0);
[1545]419       
420        mPass = 0;
421        mGvsPass = 0;
422        mSampleContriPerPass = 0;
423        mTotalSampleContri = 0;
424        mReverseSamples = 0;
425        mBorderSamples = 0;
426
[1533]427        int castSamples = 0;
[1545]428
[1486]429        if (!mLoadViewCells)
[1563]430        {       
431                /// construct the view cells from the scratch
432                ConstructViewCells();
[1580]433                // reset pvs already gathered during view cells construction
434                mViewCellsManager->ResetPvs();
[1563]435                cout << "finished view cell construction" << endl;
[1486]436        }
[1571]437        else if (0)
[1563]438        {       
[1551]439                //-- load view cells from file
440                //-- test successful view cells loading by exporting them again
441                VssRayContainer dummies;
442                mViewCellsManager->Visualize(mObjects, dummies);
[1563]443                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
[1551]444        }
[1460]445
[1533]446        while (castSamples < mTotalSamples)
[1473]447        {
[1533]448                castSamples += Pass();
[1528]449                               
[1500]450                ////////
451                //-- stats
[1545]452                cout << "\nPass " << mPass << " #samples: " << castSamples << " of " << mTotalSamples << endl;
[1533]453
[1486]454                //mVssRays.PrintStatistics(mStats);
[1545]455                mStats
456                        << "#Pass\n" << mPass << endl
457                        << "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl
458                        << "#TotalSamples\n" << castSamples << endl
459                        << "#ScDiff\n" << mSampleContriPerPass << endl
460                        << "#SamplesContri\n" << mTotalSampleContri << endl
461                        << "#ReverseSamples\n" << mReverseSamples << endl
462                        << "#BorderSamples\n" << mBorderSamples << endl                 
463                        << "#GvsRuns\n" << mGvsPass << endl;
[1460]464
[1473]465                mViewCellsManager->PrintPvsStatistics(mStats);
[1566]466
[1570]467                char str[64]; sprintf(str, "tmp/pass%04d-", mPass);
468               
[1571]469        // visualization
470                if (mSampleContriPerPass > 0)
471                {
472                        const bool exportRays = true;
473                        const bool exportPvs = true;
474
475                        mViewCellsManager->ExportSingleViewCells(mObjects, 10, false, exportPvs, exportRays, 1000, str);
476                }
477
[1570]478                // remove pass samples
479                ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
480                for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
481                {
[1696]482                        (*vit)->DelRayRefs();
[1570]483                }
484
[1696]485                //CLEAR_CONTAINER(mVssRays);
[1473]486                // ComputeRenderError();
[1545]487                ++ mPass;
[1460]488        }
489
[1545]490        cout << 2 * castSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
491        Visualize();
492
[1473]493        return true;
[1460]494}
495
[1522]496
497void GvsPreprocessor::Visualize()
498{
499        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
500
501        if (!exporter)
502                return;
503       
504        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
505        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
506        {
[1524]507                exporter->SetWireframe();
[1522]508                exporter->ExportPolygon((*vit).enlargedTriangle);
509                //Material m;
[1524]510                exporter->SetFilled();
511                Polygon3 poly = Polygon3((*vit).originalTriangle);
512                exporter->ExportPolygon(&poly);
[1522]513        }
514
515        exporter->ExportRays(mVssRays);
516        delete exporter;
[1460]517}
[1522]518
519}
Note: See TracBrowser for help on using the repository browser.