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

Revision 1521, 10.4 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
11
12namespace GtpVisibilityPreprocessor
13{
14 
15
16GvsPreprocessor::GvsPreprocessor(): Preprocessor(), mSamplingType(0)
17{
18        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
19        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
20        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.samplesPerPass", mSamplesPerPass);
21        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
22        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
23
24        Debug << "Gvs preprocessor options" << endl;
25        Debug << "number of total samples: " << mTotalSamples << endl;
26        Debug << "number of initial samples: " << mInitialSamples << endl;
27        Debug << "number of samples per pass: " << mSamplesPerPass << endl;
28        Debug << "threshold: " << mThreshold << endl;
29        Debug << "eps: " << mEps << endl;
30
31        mStats.open("gvspreprocessor.log");
32}
33
34
35bool GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
36                                                                                 const Triangle3 &hitTriangle,
37                                                                                 const VssRay &oldRay)
38{
39        const float dist = Magnitude(oldRay.GetDir());
40        const float newDist = Magnitude(currentRay.GetDir());
41 
42#if 0
43        if ((dist - newDist) > mThresHold)
44#else // rather take relative distance
45        if ((dist / newDist) > mThreshold)
46#endif
47        {
48                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
49                if (!HandleRay(newRay))
50                        delete newRay;
51
52                return true;
53        }
54
55        return false;
56}
57
58
59bool GvsPreprocessor::HandleRay(VssRay *vssRay)
60{
61        if (mViewCellsManager->ComputeSampleContribution(*vssRay, true, false))
62        {
63                //cout << "h";
64                mRayQueue.push(vssRay);
65                return true;
66        }
67
68        return false;
69}
70
71
72/** Creates 3 new vertices for triangle vertex with specified index.
73*/
74static void CreateNewVertices(VertexContainer &vertices,
75                                                          const Triangle3 &hitTriangle,
76                                                          const VssRay &ray,
77                                                          const int index,
78                                                          const float eps)
79{
80        const int indexU = (index + 1) % 3;
81        const int indexL = (index == 0) ? 2 : index - 1;
82
83        const Vector3 a = hitTriangle.mVertices[index] - ray.GetDir();
84        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
85        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
86       
87        const float len = Magnitude(a);
88
89        const Vector3 dir1 = CrossProd(a, b); //N((pi-xp)×(pi+1- pi));
90        const Vector3 dir2 = CrossProd(a, c); // N((pi-xp)×(pi- pi-1))
91        const Vector3 dir3 = DotProd(dir1, dir2) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
92                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir2) + CrossProd(dir1, a));
93
94        // compute the new three hit points
95        // pi, i + 1:  pi+ e·|pi-xp|·di, j
96        const Vector3 pt1 = hitTriangle.mVertices[index] + eps * len * dir1;
97        // pi, i - 1:  pi+ e·|pi-xp|·di, j
98    const Vector3 pt2 = hitTriangle.mVertices[index] + eps * len * dir2;
99        // pi, i:  pi+ e·|pi-xp|·di, j
100        const Vector3 pt3 = hitTriangle.mVertices[index] + eps * len * dir3;
101       
102        vertices.push_back(pt1);
103        vertices.push_back(pt2);
104        vertices.push_back(pt3);
105}
106
107
108void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
109                                                                          const Triangle3 &hitTriangle,
110                                                                          const VssRay &ray)
111{
112        CreateNewVertices(vertices, hitTriangle, ray, 0, mEps);
113        CreateNewVertices(vertices, hitTriangle, ray, 1, mEps);
114        CreateNewVertices(vertices, hitTriangle, ray, 2, mEps);
115}
116
117
118static Vector3 CalcPredictedHitPoint(const VssRay &newRay,
119                                                                         const Triangle3 &hitTriangle,
120                                                                         const VssRay &oldRay)
121{
122        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
123
124        const Vector3 hitPt =
125                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
126       
127        return hitPt;
128}
129
130
131static bool EqualVisibility(const VssRay &a, const VssRay &b)
132{
133        return a.mTerminationObject == b.mTerminationObject;
134}
135
136
137int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
138                                                                   const Vector3 &p1,
139                                                                   const Vector3 &p2,
140                                                                   const VssRay &x,
141                                                                   const VssRay &y,
142                                                                   const VssRay &oldRay)
143{
144        // the predicted hitpoint expects to hit the same mesh again
145        const Vector3 predictedHitX = CalcPredictedHitPoint(x, hitTriangle, oldRay);
146        const Vector3 predictedHitY = CalcPredictedHitPoint(y, hitTriangle, oldRay);
147
148        CheckDiscontinuity(x, hitTriangle, oldRay);
149        CheckDiscontinuity(y, hitTriangle, oldRay);
150
151        if (EqualVisibility(x, y))
152        {
153                return 2;
154        }
155        else
156        {
157                const Vector3 p = (p1 + p2) * 0.5f;
158                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin);
159       
160                VssRay *newRay = mRayCaster->CastSingleRay(sray.mOrigin, sray.mDirection, 1, mViewSpaceBox);
161                bool addedToQueue = HandleRay(newRay);
162               
163                const int s1 = SubdivideEdge(hitTriangle, p1, p, x, *newRay, oldRay);
164                const int s2 = SubdivideEdge(hitTriangle, p, p2, *newRay, y, oldRay);
165                return s1 + s2;
166               
167                if (!addedToQueue)
168                        delete newRay;
169        }
170}
171
172
173int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
174{
175        cout << "a";
176        Intersectable *tObj = currentRay.mTerminationObject;
177        Triangle3 hitTriangle;
178
179        // other types not implemented yet
180        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
181        {
182                hitTriangle = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
183        }
184
185        VertexContainer enlargedTriangle;
186       
187        /// create 3 new hit points for each vertex
188        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
189       
190        /// create rays from sample points and handle them
191        SimpleRayContainer simpleRays;
192        simpleRays.reserve(9);
193
194        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
195
196        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
197        {
198                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
199                simpleRays.push_back(SimpleRay(*vit, rayDir));
200        }
201
202        // establish visibility
203        VssRayContainer vssRays;
204        CastRays(simpleRays, vssRays, false);
205        // add to ray queue
206        EnqueueRays(vssRays);
207/*
208    // recursivly subdivide each edge
209        for (int i = 0; i < 9; ++ i)
210        {
211                SubdivideEdge(
212                        hitTriangle,
213                        enlargedTriangle[i],
214                        enlargedTriangle[(i + 1) % 9],
215                        *vssRays[i],
216                        *vssRays[(i + 1) % 9],
217                        currentRay);
218        }
219*/
220        return (int)vssRays.size();
221}
222
223
224static Vector3 GetPassingPoint(const VssRay &currentRay,
225                                                                                 const Triangle3 &hitTriangle,
226                                                                                 const VssRay &oldRay)
227{
228        // intersect triangle plane with plane spanned by current samples
229        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
230        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
231
232        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
233
234        // Evaluate new hitpoint just outside the triangle
235        const float factor = 0.95f;
236        float t = triPlane.FindT(intersectLine);
237
238        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
239
240        return newPoint;
241}
242
243
244VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
245                                                                                 const Triangle3 &hitTriangle,
246                                                                                 const VssRay &oldRay)
247{
248        cout << "r" << endl;
249        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
250        //-- with the newly found triangle (xold is the previous ray from
251        //-- which x was generated). On the intersecting line, we select a point
252        //-- pnew which lies just outside of the new triangle so the ray
253        //-- just passes by inside the gap
254    const Vector3 newPoint = GetPassingPoint(currentRay, hitTriangle, oldRay);
255        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
256
257        //-- Construct the mutated ray with xnew,dir = predicted(x)- pnew
258        //-- as direction vector
259        const Vector3 newDir = predicted - newPoint ;
260        // take xnew,p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
261        // difficult to say!!
262        const Vector3 newOrigin = newDir * -5000.0f;
263
264        return new VssRay(currentRay);
265}
266
267
268int GvsPreprocessor::CastInitialSamples(const int numSamples,
269                                                                                const int sampleType)
270{       
271        const long startTime = GetTime();
272
273        // generate simple rays
274        SimpleRayContainer simpleRays;
275        GenerateRays(numSamples, sampleType, simpleRays);
276       
277        // generate vss rays
278        VssRayContainer samples;
279        CastRays(simpleRays, samples, true);
280       
281        // add to ray queue
282        EnqueueRays(samples);
283
284        Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
285
286        return (int)samples.size();
287}
288
289
290void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
291{
292        // add samples to ray queue
293        VssRayContainer::const_iterator vit, vit_end = samples.end();
294       
295        for (vit = samples.begin(); vit != vit_end; ++ vit)
296        {
297                HandleRay(*vit);
298        }
299}
300
301
302int GvsPreprocessor::Pass()
303{
304        int castSamples = 0;
305        const int mSampleType = 0;
306        while (castSamples < mSamplesPerPass)
307        {
308                // Ray queue empty =>
309                // cast a number of uniform samples to fill ray Queue
310                CastInitialSamples(mInitialSamples, mSampleType);
311
312                const int gvsSamples = ProcessQueue();
313#if 0
314                castSamples += gvsSamples;
315#else
316                castSamples += mInitialSamples;
317#endif
318                //cout << "\ncast " << castSamples << " of " << mSamplesPerPass << endl;
319        }
320
321        return castSamples;
322}
323
324
325int GvsPreprocessor::ProcessQueue()
326{
327        int castSamples = 0;
328
329        while (!mRayQueue.empty())
330        {
331                // handle next ray
332                VssRay *ray = mRayQueue.top();
333                mRayQueue.pop();
334               
335                castSamples += AdaptiveBorderSampling(*ray);
336
337                delete ray;
338        }
339
340        return castSamples;
341}
342
343
344bool GvsPreprocessor::ComputeVisibility()
345{
346        Randomize(0);
347        const long startTime = GetTime();
348       
349        mViewSpaceBox = mKdTree->GetBox();
350        cout << "Gvs Preprocessor started\n" << flush;
351       
352        if (!mLoadViewCells)
353        {       /// construct the view cells from the scratch
354                ConstructViewCells(mViewSpaceBox);
355                cout << "view cells loaded" << endl;
356        }
357
358        int castSamples = 0;
359
360        while (castSamples < mTotalSamples)
361        {
362                const int passSamples = Pass();
363                castSamples += passSamples;
364               
365                ////////
366                //-- stats
367                cout << "+";
368                cout << "\nsamples cast " << passSamples << " (=" << castSamples << " of " << mTotalSamples << ")" << endl;
369                //mVssRays.PrintStatistics(mStats);
370                mStats << "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl
371                           << "#TotalSamples\n" << castSamples << endl;
372
373                mViewCellsManager->PrintPvsStatistics(mStats);
374                // ComputeRenderError();
375        }
376
377        return true;
378}
379
380}
Note: See TracBrowser for help on using the repository browser.