source: GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.h @ 1184

Revision 1184, 12.5 KB checked in by mattausch, 18 years ago (diff)
Line 
1#ifndef _KdTree_H__
2#define _KdTree_H__
3
4#include <functional>
5using namespace std;
6
7#include "Containers.h"
8#include "AxisAlignedBox3.h"
9#include "Ray.h"
10#include "Pvs.h"
11#include "Viewcell.h"
12#include "VssRay.h"
13
14
15namespace GtpVisibilityPreprocessor {
16
17 
18  class KdNode;
19  class KdLeaf;
20  class KdInterior;
21  class Intersectable;
22  //class KdViewCell;
23  class Beam;
24
25  class KdTree;
26 
27  //  KdTree *SceneKdTree;
28
29// --------------------------------------------------------------
30// Static statistics for kd-tree search
31// --------------------------------------------------------------
32class KdTreeStatistics
33{
34public: 
35  // total number of nodes
36  int nodes;
37  // number of splits along each of the axes
38  int splits[7];
39  // totals number of rays
40  int rays;
41  // total number of query domains
42  int queryDomains;
43  // total number of ray references
44  int rayRefs;
45  // refs in non empty leafs
46  int rayRefsNonZeroQuery;
47  // total number of query references
48  int objectRefs;
49  // nodes with zero queries
50  int zeroQueryNodes;
51  // max depth nodes
52  int maxDepthNodes;
53  // max depth nodes
54  int minCostNodes;
55  // max number of rays per node
56  int maxObjectRefs;
57  // number of dynamically added ray refs
58  int addedRayRefs;
59  // number of dynamically removed ray refs
60  int removedRayRefs;
61 
62  // Constructor
63  KdTreeStatistics() {
64    Reset();
65  }
66
67  int Nodes() const {return nodes;}
68  int Interior() const { return nodes / 2; }
69  int Leaves() const { return (nodes / 2) + 1; }
70
71  void Reset() {
72    nodes = 0;
73    for (int i=0; i<7; i++)
74      splits[i] = 0;
75    rays = queryDomains = 0;
76    rayRefs = rayRefsNonZeroQuery = objectRefs = 0;
77    zeroQueryNodes = 0;
78    maxDepthNodes = 0;
79    minCostNodes = 0;
80    maxObjectRefs = 0;
81    addedRayRefs = removedRayRefs = 0;
82  }
83
84  void
85  Print(ostream &app) const;
86
87  friend ostream &operator<<(ostream &s, const KdTreeStatistics &stat) {
88    stat.Print(s);
89    return s;
90  }
91 
92};
93
94 
95class KdInterior;
96/** Abstract class for kd-tree node */
97class KdNode {
98public:
99 
100        static int sMailId;
101        static int sReservedMailboxes;
102  int mMailbox;
103 
104  void Mail() { mMailbox = sMailId; }
105  //static void NewMail() { sMailId ++; }
106  bool Mailed() const { return mMailbox == sMailId; }
107 
108  static void NewMail(const int reserve = 1) {
109                sMailId += sReservedMailboxes;
110                sReservedMailboxes = reserve;
111        }
112        void Mail(const int mailbox) { mMailbox = sMailId + mailbox; }
113        bool Mailed(const int mailbox) const { return mMailbox == sMailId + mailbox; }
114
115  virtual ~KdNode(){};
116  KdNode(KdInterior *parent);
117
118  /** Determines whether this node is a leaf or interior node
119      @return true if leaf
120  */
121  virtual bool IsLeaf() const = 0;
122
123  /** Determines whether this node is the root of the tree
124      @return true if root
125  */
126  virtual bool IsRoot() const {
127    return mParent == NULL;
128  }
129
130  /** Parent of the node - the parent is a little overhead for maintanance of the tree,
131      but allows various optimizations of tree traversal algorithms */
132  KdInterior *mParent;
133  int mDepth;
134};
135
136/** Implementation of the kd-tree interior node */
137class KdInterior : public KdNode {
138
139public:
140   
141  KdInterior(KdInterior *parent):KdNode(parent), mBack(NULL), mFront(NULL) {}
142
143  ~KdInterior();
144
145  /** \sa KdNode::IsLeaf() */
146  virtual bool IsLeaf() const { return false; }
147
148  /** splitting axis */
149  int mAxis;
150  /** splitting position, absolute position within the bounding box of this node */
151  float mPosition;
152  /** bounding box of interior node */
153  AxisAlignedBox3 mBox;
154
155  /** back node */
156  KdNode *mBack;
157  /** front node */
158  KdNode *mFront;
159
160  void SetupChildLinks(KdNode *b, KdNode *f) {
161    mBack = b;
162    mFront = f;
163    b->mParent = f->mParent = this;
164  }
165 
166  void ReplaceChildLink(KdNode *oldChild, KdNode *newChild) {
167    if (mBack == oldChild)
168      mBack = newChild;
169    else
170      mFront = newChild;
171  }
172 
173 
174};
175 
176class SplitCandidate;
177 
178/** Implementation of the kd-tree leaf node */
179class KdLeaf : public KdNode {
180public:
181  KdLeaf(KdInterior *parent, const int objects):
182          KdNode(parent), mViewCell(NULL) {
183    mObjects.reserve(objects);
184  }
185 
186  void AddPassingRay(const Ray &ray, const int contributions) {
187    mPassingRays.AddRay(ray, contributions);
188                //              Debug << "adding passing ray" << endl;
189  }
190
191  ~KdLeaf() { DEL_PTR(mViewCell);  }
192       
193        void AddPassingRay2(const Ray &ray,
194                                                const int objects,
195                                                const int viewcells
196                                                ) {
197    mPassingRays.AddRay2(ray, objects, viewcells);
198                //              Debug << "adding passing ray" << endl;
199  }
200
201  /** \sa KdNode::IsLeaf() */
202  virtual bool IsLeaf() const { return true; }
203
204
205  /** pointers to occluders contained in this node */
206  ObjectContainer mObjects;
207
208  /** Ray set description of the rays passing through this node */
209  PassingRaySet mPassingRays;
210       
211  /** PVS consisting of visible KdTree nodes */
212  KdPvs mKdPvs;
213
214  /// pvs of view cells seeing this node.
215  SplitCandidate *mSplitCandidate;
216
217  /// pointer to view cell.
218  KdViewCell *mViewCell;
219
220  VssRayContainer mVssRays;
221
222   /// Objects that are referenced in more than one leaf.
223  ObjectContainer mMultipleObjects;
224
225  /// universal counter
226  int mCounter;
227};
228
229 
230
231/** KdTree for indexing scene entities - occluders/occludees/viewcells */
232class KdTree {
233 
234protected:
235  struct TraversalData
236  { 
237    KdNode *mNode;
238    AxisAlignedBox3 mBox;
239    int mDepth;
240    float mPriority;
241   
242    TraversalData() {}
243
244    TraversalData(KdNode *n, const float p):
245      mNode(n), mPriority(p)
246    {}
247   
248    TraversalData(KdNode *n,
249                   const AxisAlignedBox3 &b,
250                   const int d):
251      mNode(n), mBox(b), mDepth(d) {}
252   
253
254    bool operator<(
255                                   const TraversalData &b) const {
256      KdLeaf *leafa = (KdLeaf *) mNode;
257      KdLeaf *leafb = (KdLeaf *) b.mNode;
258      return
259                leafa->mObjects.size()*mBox.SurfaceArea()
260                <
261                leafb->mObjects.size()*b.mBox.SurfaceArea();
262    }
263
264
265    // comparator for the
266    struct less_priority : public
267    binary_function<const TraversalData, const TraversalData, bool> {
268     
269      bool operator()(const TraversalData a, const TraversalData b) {
270                                return a.mPriority < b.mPriority;
271      }
272     
273    };
274
275  };
276
277 
278
279public:
280
281  enum {SPLIT_OBJECT_MEDIAN,
282        SPLIT_SPATIAL_MEDIAN,
283        SPLIT_SAH};
284 
285  KdTree();
286
287  ~KdTree();
288   
289  /** Insert view cell into the tree */
290  virtual void InsertViewCell(ViewCell *viewCell) {
291    //      mRoot->mViewcells.push_back(viewCell);
292  }
293
294  virtual bool Construct();
295
296  /** Check whether subdivision criteria are met for the given subtree.
297      If not subdivide the leafs of the subtree. The criteria are specified in
298      the environment as well as the subdivision method. By default surface area
299      heuristics is used.
300       
301      @param subtree root of the subtree
302
303      @return true if subdivision was performed, false if subdivision criteria
304      were already met
305  */
306  virtual KdNode *Subdivide(const TraversalData &tdata);
307
308  /** Get the root of the tree */
309  KdNode *GetRoot() const {
310    return mRoot;
311  }
312
313
314  AxisAlignedBox3 GetBox() const { return mBox; }
315
316  int
317  CastRay(
318                  Ray &ray
319                  );
320 
321
322  int
323  CastBeam(
324                   Beam &beam
325                   );
326 
327 
328  /** Casts line segment into tree.
329          @returns intersected view cells.
330  */
331  int CastLineSegment(const Vector3 &origin,
332                                          const Vector3 &termination,
333                                          vector<ViewCell *> &viewcells);
334
335
336  const KdTreeStatistics &GetStatistics() const {
337    return mStat;
338  }
339
340  void
341  CollectObjects(KdNode *n, ObjectContainer &objects);
342
343  void
344  CollectObjects(const AxisAlignedBox3 &box,
345                                 ObjectContainer &objects);
346
347  void
348  CollectLeaves(vector<KdLeaf *> &leaves);
349       
350  /** If the kd tree is used as view cell container, this
351          methods creates the view cells.
352          @returns the newly created view cells in a view cell container
353  */
354  void
355  CreateAndCollectViewCells(ViewCellContainer &viewCells) const;
356
357  AxisAlignedBox3 GetBox(const KdNode *node) const {
358    KdInterior *parent = node->mParent;
359    if (parent == NULL)
360      return mBox;
361   
362    if (!node->IsLeaf())
363      return ((KdInterior *)node)->mBox;
364   
365    AxisAlignedBox3 box(parent->mBox);
366    if (parent->mFront == node)
367      box.SetMin(parent->mAxis, parent->mPosition);
368    else
369      box.SetMax(parent->mAxis, parent->mPosition);
370    return box;
371  }
372       
373  KdNode *
374  FindRandomNeighbor(KdNode *n,
375                                         bool onlyUnmailed
376                                         );
377 
378  KdNode *
379  KdTree::GetRandomLeaf(const Plane3 &halfspace);
380
381  KdNode *
382  GetRandomLeaf(const bool onlyUnmailed = false);
383 
384  int
385  FindNeighbors(KdNode *n,
386                                vector<KdNode *> &neighbors,
387                                bool onlyUnmailed
388                                );
389
390  int
391  CollectLeafPvs();
392
393protected:
394
395  struct RayData {
396    // pointer to the actual ray
397    Ray *ray;
398   
399    // endpoints  - do we need them?
400#if USE_FIXEDPOINT_T
401    short tmin, tmax;
402#else
403    float tmin, tmax;
404#endif
405
406    RayData():ray(NULL) {}
407    RayData(Ray *r):ray(r), tmin(0),
408
409#if USE_FIXEDPOINT_T
410#define FIXEDPOINT_ONE 0x7FFE
411                          //                      tmax(0xFFFF)
412                          tmax(FIXEDPOINT_ONE)
413#else
414      tmax(1.0f)
415#endif
416    {}
417
418    RayData(Ray *r,
419            const float _min,
420            const float _max
421            ):ray(r) {
422      SetTMin(_min);
423      SetTMax(_max);
424    }
425
426    RayData(Ray *r,
427            const short _min,
428            const float _max
429            ):ray(r), tmin(_min) {
430      SetTMax(_max);
431    }
432
433    RayData(Ray *r,
434            const float _min,
435            const short _max
436            ):ray(r), tmax(_max) {
437      SetTMin(_min);
438    }
439
440    friend bool operator<(const RayData &a, const RayData &b) {
441      return a.ray < b.ray;
442    }
443   
444   
445    float ExtrapOrigin(const int axis) const {
446      return ray->GetLoc(axis) + GetTMin()*ray->GetDir(axis);
447    }
448   
449    float ExtrapTermination(const int axis) const {
450      return ray->GetLoc(axis) + GetTMax()*ray->GetDir(axis);
451    }
452   
453#if USE_FIXEDPOINT_T
454    float GetTMin () const { return tmin/(float)(FIXEDPOINT_ONE); }
455    float GetTMax () const { return tmax/(float)(FIXEDPOINT_ONE); }
456
457    void SetTMin (const float t) {
458      tmin = (short) (t*(float)(FIXEDPOINT_ONE));
459    }
460   
461    void SetTMax (const float t) {
462      tmax = (short) (t*(float)(FIXEDPOINT_ONE));
463      tmax++;
464      //      if (tmax!=0xFFFF)
465      //        tmax++;
466    }
467#else
468    float GetTMin () const { return tmin; }
469    float GetTMax () const { return tmax; }
470
471    void SetTMin (const float t) { tmin = t; }
472    void SetTMax (const float t) { tmax = t; }
473#endif
474  };
475
476  struct RayTraversalData {
477    KdNode *mNode;
478    Vector3 mExitPoint;
479    float mMaxT;
480   
481    RayTraversalData() {}
482    RayTraversalData(KdNode *n,
483                     const Vector3 &p,
484                     const float maxt):
485      mNode(n), mExitPoint(p), mMaxT(maxt) {}
486  };
487
488  // --------------------------------------------------------------
489  // For sorting objects
490  // --------------------------------------------------------------
491  struct  SortableEntry
492  {
493    enum {
494      BOX_MIN,
495      BOX_MAX
496    };
497   
498    int type;
499    float value;
500    Intersectable *intersectable;
501   
502    SortableEntry() {}
503    SortableEntry(const int t, const float v, Intersectable *i):type(t),
504                                                                value(v),
505                                                                intersectable(i) {}
506   
507    bool operator<(const SortableEntry &b) const {
508      return value < b.value;
509    }
510   
511  };
512 
513  // reusable array of split candidates
514  vector<SortableEntry> *splitCandidates;
515
516  float
517  BestCostRatio(
518                KdLeaf *node,
519                const AxisAlignedBox3 &box,
520                const int axis,
521                float &position,
522                int &objectsBack,
523                int &objectsFront
524                );
525
526  void
527  SortSplitCandidates(
528                      KdLeaf *node,
529                      const int axis
530                      );
531
532  void
533  EvaluateLeafStats(const TraversalData &data);
534
535  KdNode *
536  SubdivideNode(
537                KdLeaf *leaf,
538                const AxisAlignedBox3 &box,
539                AxisAlignedBox3 &backBBox,
540                AxisAlignedBox3 &frontBBox
541                );
542
543  bool
544  TerminationCriteriaMet(const KdLeaf *leaf);
545 
546  int
547  SelectPlane(KdLeaf *leaf,
548              const AxisAlignedBox3 &box,
549              float &position
550              );
551
552        /** does some post processing on the objects in the new child leaves.
553        */
554        void ProcessMultipleRefs(KdLeaf *leaf) const;
555
556  int mTermMaxNodes;
557  float mSplitBorder;
558  int mTermMaxDepth;
559  int mTermMinCost;
560  float mMaxCostRatio;
561  float mCt_div_ci;
562  int mSplitMethod;
563  bool mSahUseFaces;
564  /// root of the tree
565  KdNode *mRoot;
566  /// bounding box of the tree root
567  AxisAlignedBox3 mBox;
568  KdTreeStatistics mStat;
569 
570};
571 
572
573
574
575}
576
577#endif
Note: See TracBrowser for help on using the repository browser.