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

Revision 1576, 14.3 KB checked in by mattausch, 18 years ago (diff)

added measurement for pvs entries size decrease during subdivision

  • 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;
[1572]69                cout << "here9444 " << (int) newRay->mFlags << " " << newRay << endl;
[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{
[1576]83        cout << "x " << (int)vssRay->mFlags;
[1570]84        const bool storeRaysForViz = true;
85        mViewCellsManager->ComputeSampleContribution(*vssRay, true, storeRaysForViz);
[1528]86               
87        // some pvs contribution for this ray?
88        if (vssRay->mPvsContribution > 0)
89        {
[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);
98                                nray->mFlags = vssRay->mFlags;
99                                (*vit)->mVssRays.push_back(nray);
100nray->mFlags = 10;
101                                cout << "\nhere58 " << (int)nray->mFlags << "  " << (int)vssRay->mFlags << endl;
[1570]102                        }
103                }
104                //mVssRays.push_back(new VssRay(*vssRay));
[1545]105        ++ mSampleContriPerPass;
[1533]106
[1500]107                return true;
[1473]108        }
[1500]109
110        return false;
[1460]111}
112
[1500]113
114/** Creates 3 new vertices for triangle vertex with specified index.
[1489]115*/
[1500]116static void CreateNewVertices(VertexContainer &vertices,
117                                                          const Triangle3 &hitTriangle,
118                                                          const VssRay &ray,
119                                                          const int index,
120                                                          const float eps)
[1460]121{
[1486]122        const int indexU = (index + 1) % 3;
123        const int indexL = (index == 0) ? 2 : index - 1;
124
[1524]125        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
[1486]126        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
127        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
[1492]128       
[1533]129        const float len = Magnitude(a);
[1486]130
[1523]131        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
132        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
[1524]133        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
134                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
[1492]135
[1486]136        // compute the new three hit points
[1500]137        // pi, i + 1:  pi+ e·|pi-xp|·di, j
138        const Vector3 pt1 = hitTriangle.mVertices[index] + eps * len * dir1;
139        // pi, i - 1:  pi+ e·|pi-xp|·di, j
140    const Vector3 pt2 = hitTriangle.mVertices[index] + eps * len * dir2;
141        // pi, i:  pi+ e·|pi-xp|·di, j
142        const Vector3 pt3 = hitTriangle.mVertices[index] + eps * len * dir3;
[1489]143       
[1524]144        vertices.push_back(pt2);
145        vertices.push_back(pt3);
[1500]146        vertices.push_back(pt1);
[1489]147}
148
149
[1500]150void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
151                                                                          const Triangle3 &hitTriangle,
152                                                                          const VssRay &ray)
153{
154        CreateNewVertices(vertices, hitTriangle, ray, 0, mEps);
155        CreateNewVertices(vertices, hitTriangle, ray, 1, mEps);
156        CreateNewVertices(vertices, hitTriangle, ray, 2, mEps);
157}
[1492]158
[1500]159
160static Vector3 CalcPredictedHitPoint(const VssRay &newRay,
161                                                                         const Triangle3 &hitTriangle,
162                                                                         const VssRay &oldRay)
[1489]163{
[1500]164        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
165
166        const Vector3 hitPt =
167                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
168       
169        return hitPt;
170}
171
172
173static bool EqualVisibility(const VssRay &a, const VssRay &b)
174{
175        return a.mTerminationObject == b.mTerminationObject;
176}
177
178
179int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
180                                                                   const Vector3 &p1,
181                                                                   const Vector3 &p2,
182                                                                   const VssRay &x,
183                                                                   const VssRay &y,
184                                                                   const VssRay &oldRay)
185{
186        // the predicted hitpoint expects to hit the same mesh again
187        const Vector3 predictedHitX = CalcPredictedHitPoint(x, hitTriangle, oldRay);
188        const Vector3 predictedHitY = CalcPredictedHitPoint(y, hitTriangle, oldRay);
189
190        CheckDiscontinuity(x, hitTriangle, oldRay);
191        CheckDiscontinuity(y, hitTriangle, oldRay);
192
193        if (EqualVisibility(x, y))
194        {
[1533]195                return 0;
[1500]196        }
197        else
198        {
[1533]199                cout << "s";
[1500]200                const Vector3 p = (p1 + p2) * 0.5f;
201                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin);
[1521]202       
[1566]203                // cast ray into the new subdivision point
[1563]204                VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), false);
[1571]205               
[1551]206                if (!newRay) return 0;
[1571]207newRay->mFlags |= VssRay::BorderSample;
[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
[1492]269        // add to ray queue
270        EnqueueRays(vssRays);
[1528]271       
[1524]272        const int n = (int)enlargedTriangle.size();
[1533]273        int castRays = (int)vssRays.size();
[1571]274
275        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
276        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
277        {
278                (*rit)->mFlags |= VssRay::BorderSample;
279                cout << "here390 " << (int) (*rit)->mFlags << endl;
280        }
281
[1533]282#if 1
[1500]283    // recursivly subdivide each edge
[1524]284        for (int i = 0; i < n; ++ i)
[1500]285        {
[1533]286                castRays += SubdivideEdge(
[1500]287                        hitTriangle,
288                        enlargedTriangle[i],
[1524]289                        enlargedTriangle[(i + 1) % n],
[1500]290                        *vssRays[i],
[1524]291                        *vssRays[(i + 1) % n],
[1500]292                        currentRay);
293        }
[1522]294#endif
[1533]295
[1545]296        mBorderSamples += castRays;
[1533]297        return castRays;
[1473]298}
299
300
[1500]301static Vector3 GetPassingPoint(const VssRay &currentRay,
[1533]302                                                           const Triangle3 &hitTriangle,
303                                                           const VssRay &oldRay)
[1473]304{
[1500]305        // intersect triangle plane with plane spanned by current samples
306        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
307        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
308
309        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
310
311        // Evaluate new hitpoint just outside the triangle
312        const float factor = 0.95f;
313        float t = triPlane.FindT(intersectLine);
314        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
315
316        return newPoint;
317}
318
319
320VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
321                                                                                 const Triangle3 &hitTriangle,
322                                                                                 const VssRay &oldRay)
323{
324        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
325        //-- with the newly found triangle (xold is the previous ray from
326        //-- which x was generated). On the intersecting line, we select a point
327        //-- pnew which lies just outside of the new triangle so the ray
328        //-- just passes by inside the gap
329    const Vector3 newPoint = GetPassingPoint(currentRay, hitTriangle, oldRay);
330        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
331
332        //-- Construct the mutated ray with xnew,dir = predicted(x)- pnew
333        //-- as direction vector
334        const Vector3 newDir = predicted - newPoint ;
335        // take xnew,p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
336        // difficult to say!!
337        const Vector3 newOrigin = newDir * -5000.0f;
338
[1571]339        ++ mReverseSamples;
340
[1500]341        return new VssRay(currentRay);
[1473]342}
343
[1489]344
345int GvsPreprocessor::CastInitialSamples(const int numSamples,
346                                                                                const int sampleType)
347{       
[1473]348        const long startTime = GetTime();
349
[1489]350        // generate simple rays
351        SimpleRayContainer simpleRays;
352        GenerateRays(numSamples, sampleType, simpleRays);
[1528]353
[1489]354        // generate vss rays
[1473]355        VssRayContainer samples;
[1520]356        CastRays(simpleRays, samples, true);
[1489]357        // add to ray queue
[1492]358        EnqueueRays(samples);
[1533]359
[1545]360        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
[1489]361        return (int)samples.size();
362}
363
364
[1500]365void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
[1489]366{
[1486]367        // add samples to ray queue
[1473]368        VssRayContainer::const_iterator vit, vit_end = samples.end();
[1576]369        for (vit = samples.begin(); vit != vit_end; ++ vit)
[1473]370        {
[1521]371                HandleRay(*vit);
[1460]372        }
373}
374
[1473]375
[1486]376int GvsPreprocessor::Pass()
[1460]377{
[1528]378        // reset samples
[1533]379        int castSamples = 0;
380        mSampleContriPerPass = 0;
[1545]381
[1533]382        while (castSamples < mSamplesPerPass)
[1528]383        {       
[1473]384                // Ray queue empty =>
[1545]385                // cast a number of uniform samples to fill ray queue
386                castSamples += CastInitialSamples(mInitialSamples, mSamplingType);
[1533]387                castSamples += ProcessQueue();
[1545]388                //cout << "\ncast " << castSamples << " samples in a processing pass" << endl;
[1473]389        }
390
[1533]391        mTotalSampleContri += mSampleContriPerPass;
392        return castSamples;
[1460]393}
394
[1473]395
[1489]396int GvsPreprocessor::ProcessQueue()
[1460]397{
[1473]398        int castSamples = 0;
[1545]399        ++ mGvsPass;
[1473]400
401        while (!mRayQueue.empty())
402        {
403                // handle next ray
[1500]404                VssRay *ray = mRayQueue.top();
[1473]405                mRayQueue.pop();
[1545]406
[1501]407                castSamples += AdaptiveBorderSampling(*ray);
[1521]408                delete ray;
[1460]409        }
[1528]410       
[1473]411        return castSamples;
[1460]412}
413
414
[1489]415bool GvsPreprocessor::ComputeVisibility()
[1460]416{
[1533]417        cout << "Gvs Preprocessor started\n" << flush;
[1545]418        const long startTime = GetTime();
[1533]419
[1473]420        Randomize(0);
[1545]421       
422        mPass = 0;
423        mGvsPass = 0;
424        mSampleContriPerPass = 0;
425        mTotalSampleContri = 0;
426        mReverseSamples = 0;
427        mBorderSamples = 0;
428
[1533]429        int castSamples = 0;
[1545]430
[1486]431        if (!mLoadViewCells)
[1563]432        {       
433                /// construct the view cells from the scratch
434                ConstructViewCells();
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                {
482                        CLEAR_CONTAINER((*vit)->mVssRays);
483                }
484
[1566]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.