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

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