forked from tuxalin/THST
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RTree.h
1623 lines (1381 loc) · 48 KB
/
RTree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// RTree.h
//
//
#pragma once
#include "allocator.h"
#include "bbox.h"
#include "config.h"
#include "indexable.h"
#include "predicates.h"
#include "rtree_detail.h"
#include <vector>
namespace spatial {
namespace rtree {
// Type of element that allows fractional and large values such as float or
// double, for use in volume calculations.
template <typename T> struct RealType { typedef float type; };
template <> struct RealType<double> { typedef double type; };
}
/**
@class RTree
@brief Implementation of a custom RTree tree based on the version
by Greg Douglas at Auran and original algorithm was by Toni Gutman.
R-Trees provide Log(n) speed rectangular indexing into multi-dimensional
data. Only support the quadratric split heuristic.
It has the following properties:
- hierarchical, you can add values to the internal branch nodes
- custom indexable getter similar to boost's
- configurable volume calculation
- custom allocation for internal nodes
@tparam T type of the space(eg. int, float, etc.)
@tparam ValueType type of value stored in the tree's nodes
@tparam Dimension number of dimensions for the spatial space of the
bounding boxes
@tparam min_child_items m, in the range 2 <= m < M
@tparam max_child_items M, in the range 2 <= m < M
@tparam indexable_getter the indexable getter, i.e. the getter for the bounding
box of a value
@tparam bbox_volume_mode The rectangle calculation of volume, spherical results
better split classification but can be slower. While the normal can be faster
but worse classification.
@tparam RealType type of element that allows fractional and large
values such as float or double, for use in volume calculations.
@tparam custom_allocator the allocator class
@note It's recommended that ValueType should be a fast to copy object, eg: int,
id, obj*, etc.
*/
template <typename T, //
typename ValueType, //
int Dimension, //
int max_child_items = 8, //
int min_child_items = max_child_items / 2, //
typename indexable_getter = Indexable<T, ValueType>, //
int bbox_volume_mode = box::eNormalVolume, //
typename RealType = typename rtree::RealType<T>::type, //
typename custom_allocator = spatial::allocator<detail::Node<
ValueType, BoundingBox<T, Dimension>, max_child_items>>>
class RTree {
public:
typedef RealType real_type;
typedef BoundingBox<T, Dimension> bbox_type;
typedef custom_allocator allocator_type;
static const size_t max_items = max_child_items;
static const size_t min_items = min_child_items;
private:
typedef detail::Node<ValueType, bbox_type, max_child_items> node_type;
typedef node_type *node_ptr_type;
typedef node_type **node_dptr_type;
typedef typename node_type::branch_type branch_type;
typedef typename node_type::count_type count_type;
public:
class base_iterator : public detail::Stack<node_type, count_type> {
public:
/// Returns the depth level of the current branch.
int level() const;
/// Is iterator still valid.
bool valid() const;
/// Access the current data element. Caller must be sure iterator is not
/// NULL first.
ValueType &operator*();
/// Access the current data element. Caller must be sure iterator is not
/// NULL first.
const ValueType &operator*() const;
const bbox_type &bbox() const;
#ifdef TREE_DEBUG_TAG
std::string &tag();
#endif
protected:
typedef detail::Stack<node_type, count_type> base_type;
using base_type::m_stack;
using base_type::m_tos;
};
/**
@brief Iterator to traverese the items of a node of the tree.
*/
struct node_iterator {
node_iterator();
/// Returns the depth level of the current branch.
int level() const;
/// Is iterator still valid.
bool valid() const;
/// Access the current data element. Caller must be sure iterator is not
/// NULL first.
ValueType &operator*();
/// Access the current data element. Caller must be sure iterator is not
/// NULL first.
const ValueType &operator*() const;
const bbox_type &bbox() const;
/// Advances to the next item.
void next();
#ifdef TREE_DEBUG_TAG
std::string &tag();
#endif
private:
node_iterator(node_ptr_type node);
count_type m_index;
node_ptr_type m_node;
friend class RTree;
};
/**
@brief Iterator to traverse the whole tree similar to depth first search. It
reaches the lowest level
(i.e. leaves) and afterwards visits the higher levels until it reaches the
root(highest) level.
*/
class depth_iterator : public base_iterator {
typedef base_iterator base_type;
using base_type::m_stack;
using base_type::m_tos;
using base_type::push;
using base_type::pop;
public:
// Returns a lower level, ie. child, node of the current branch.
node_iterator child();
node_iterator current();
/// Advances to the next item.
void next();
private:
friend class RTree;
};
/**
@brief Iterator to traverse only the leaves(i.e. level 0) of the tree
similar, left to right order.
*/
class leaf_iterator : public base_iterator {
typedef base_iterator base_type;
using base_type::m_stack;
using base_type::m_tos;
using base_type::push;
using base_type::pop;
public:
/// Advances to the next item.
void next();
private:
friend class RTree;
};
RTree(indexable_getter indexable = indexable_getter(),
const allocator_type &allocator = allocator_type(),
bool allocateRoot = true);
template <typename Iter>
RTree(Iter first, Iter last, //
indexable_getter indexable = indexable_getter(), //
const allocator_type &allocator = allocator_type());
RTree(const RTree &src);
#ifdef SPATIAL_TREE_USE_CPP11
RTree(RTree &&src);
#endif
~RTree();
RTree &operator=(const RTree &rhs);
#ifdef SPATIAL_TREE_USE_CPP11
RTree &operator=(RTree &&rhs);
#endif
void swap(RTree &other);
template <typename Iter> void insert(Iter first, Iter last);
void insert(const ValueType &value);
/// Insert the value if the predicate condition is true.
template <typename Predicate>
bool insert(const ValueType &value, const Predicate &predicate);
void remove(const ValueType &value);
/// Translates the internal boxes with the given offset point.
void translate(const T point[Dimension]);
/// Special query to find all within search rectangle using the hierarchical
/// order.
/// @see spatial::SpatialPredicate for available predicates.
template <typename Predicate>
bool hierachical_query(const Predicate &predicate) const;
/// \return Returns the number of entries found.
template <typename Predicate, typename OutIter>
size_t hierachical_query(const Predicate &predicate, OutIter out_it) const;
/// Defines the traget query level, if 0 then leaf values are retrieved
/// otherwise hierachical node values.
/// @note Only used for hierachical_query.
void setQueryTargetLevel(int level);
/// @see spatial::SpatialPredicate for available predicates.
template <typename Predicate> bool query(const Predicate &predicate) const;
template <typename Predicate, typename OutIter>
size_t query(const Predicate &predicate, OutIter out_it) const;
/// Performs a nearest aproximation search.
/// @note Only for 2D space.
template <typename OutIter>
size_t nearest(const T point[2], T radius, OutIter out_it) const;
/// Remove all entries from tree
void clear(bool recursiveCleanup = true);
/// Count the data elements in this container.
size_t count() const;
/// Returns the estimated internal node count for the given number of elements
static size_t nodeCount(size_t numberOfItems);
/// Returns the estimated branch count for the given number of elements
static size_t branchCount(size_t numberOfItems);
/// Returns the number of levels(height) of the tree.
size_t levels() const;
/// Returns the estimated depth for the given number of elements
static double levels(size_t numberOfItems);
/// Returns the bbox of the root node.
bbox_type bbox() const;
/// Returns the custom allocator
allocator_type &allocator();
const allocator_type &allocator() const;
node_iterator root();
depth_iterator dbegin();
leaf_iterator lbegin();
/// Returns the size in bytes of the tree
/// @param estimate if true then it estimates the size via using the item
/// count for guessing the internal node
/// count, otherwise it counts the nodes which is slower
size_t bytes(bool estimate = true) const;
private:
/// Variables for finding a split partition
struct BranchVars {
branch_type branches[max_child_items + 1];
bbox_type coverSplit;
real_type coverSplitArea;
};
struct PartitionVars : BranchVars {
enum { ePartitionUnused = -1 };
int partitions[max_child_items + 1];
count_type count[2];
bbox_type cover[2];
real_type area[2];
PartitionVars()
: m_maxFill(max_child_items + 1), m_minFill(min_child_items) {}
void clear() {
count[0] = count[1] = 0;
area[0] = area[1] = (real_type)0;
for (count_type index = 0; index < m_maxFill; ++index) {
partitions[index] = PartitionVars::ePartitionUnused;
}
}
count_type totalCount() const { return count[0] + count[1]; }
count_type maxFill() const { return m_maxFill; }
count_type minFill() const { return m_minFill; }
count_type diffFill() const { return m_maxFill - m_minFill; }
private:
const count_type m_maxFill;
const count_type m_minFill;
};
struct BranchDistance {
RealType distance;
count_type index;
bool operator<(const BranchDistance &other) const {
return distance < other.distance;
}
};
template <typename Predicate>
bool insertImpl(const branch_type &branch, const Predicate &predicate,
int level);
template <typename Predicate>
bool insertRec(const branch_type &branch, const Predicate &predicate,
node_type &node, node_ptr_type &newNode, bool &added,
int level);
void copyRec(const node_ptr_type src, node_ptr_type dst);
count_type pickBranch(const bbox_type &bbox, const node_type &node) const;
void getBranches(const node_type &node, const branch_type &branch,
BranchVars &branchVars) const;
bool addBranch(const branch_type &branch, node_type &node,
node_dptr_type newNode) const;
void splitNode(node_type &node, const branch_type &branch,
node_dptr_type newNode) const;
void loadNodes(node_type &nodeA, node_type &nodeB,
const PartitionVars &partitionVars) const;
void choosePartition(PartitionVars &partitionVars) const;
void pickSeeds(PartitionVars &partitionVars) const;
void classify(count_type index, int group,
PartitionVars &partitionVars) const;
bool removeImpl(const bbox_type &bbox, const ValueType &value);
bool removeRec(const bbox_type &bbox, const ValueType &value,
node_ptr_type node, std::vector<node_ptr_type> &reInsertList);
void clearRec(const node_ptr_type node);
template <typename Predicate, typename OutIter>
void queryHierachicalRec(node_ptr_type node, const Predicate &predicate,
size_t &foundCount, OutIter out_it) const;
template <typename Predicate, typename OutIter>
void queryRec(node_ptr_type node, const Predicate &predicate,
size_t &foundCount, OutIter out_it) const;
template <typename OutIter>
void nearestRec(node_ptr_type node, const T point[2], T radius,
size_t &foundCount, OutIter it) const;
void translateRec(node_type &node, const T point[Dimension]);
size_t countImpl(const node_type &node) const;
void countRec(const node_type &node, size_t &count) const;
inline static RealType distance(T x0, T y0, T x1, T y1) {
T d1 = (x0 - x1);
T d2 = (y0 - y1);
return (RealType)std::sqrt(d1 * d1 + d2 * d2);
}
private:
indexable_getter m_indexable;
mutable allocator_type m_allocator;
mutable PartitionVars m_parVars;
size_t m_count;
int m_queryTargetLevel;
node_ptr_type m_root;
template <class RTreeClass>
friend typename RTreeClass::node_ptr_type &
detail::getRootNode(RTreeClass &tree);
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define TREE_TEMPLATE \
template <typename T, typename ValueType, int Dimension, \
int max_child_items, int min_child_items, \
typename indexable_getter, int bbox_volume_mode, \
typename RealType, typename custom_allocator>
#define TREE_QUAL \
RTree<T, ValueType, Dimension, max_child_items, min_child_items, \
indexable_getter, bbox_volume_mode, RealType, custom_allocator>
TREE_TEMPLATE
TREE_QUAL::RTree(indexable_getter indexable /*= indexable_getter()*/,
const allocator_type &allocator /*= allocator_type()*/,
bool allocateRoot /*= true*/)
: m_indexable(indexable), m_allocator(allocator), m_count(0),
m_queryTargetLevel(0),
m_root(allocateRoot ? detail::allocate(m_allocator, 0) : NULL) {
SPATIAL_TREE_STATIC_ASSERT((max_child_items > min_child_items),
"Invalid child size!");
SPATIAL_TREE_STATIC_ASSERT((min_child_items > 0), "Invalid child size!");
}
TREE_TEMPLATE
template <typename Iter>
TREE_QUAL::RTree(Iter first, Iter last,
indexable_getter indexable /*= indexable_getter()*/,
const allocator_type &allocator /*= allocator_type()*/)
: m_indexable(indexable), m_allocator(allocator), m_count(0),
m_queryTargetLevel(0) {
SPATIAL_TREE_STATIC_ASSERT((max_child_items > min_child_items),
"Invalid child size!");
SPATIAL_TREE_STATIC_ASSERT((min_child_items > 0), "Invalid child size!");
m_root = detail::allocate(m_allocator, 0);
// TODO: use packing algorithm
insert(first, last);
}
TREE_TEMPLATE
TREE_QUAL::RTree(const RTree &src)
: m_indexable(src.m_indexable), m_allocator(src.m_allocator),
m_count(src.m_count), m_queryTargetLevel(src.m_queryTargetLevel),
m_root(detail::allocate(m_allocator, 0)) {
copyRec(src.m_root, m_root);
}
#ifdef SPATIAL_TREE_USE_CPP11
TREE_TEMPLATE
TREE_QUAL::RTree(RTree &&src) : m_root(NULL) { swap(src); }
#endif
TREE_TEMPLATE
TREE_QUAL::~RTree() {
#if SPATIAL_TREE_ALLOCATOR == SPATIAL_TREE_DEFAULT_ALLOCATOR
if (m_root && !m_allocator.overflowed())
#else
if (m_root)
#endif
clearRec(m_root);
}
TREE_TEMPLATE
TREE_QUAL &TREE_QUAL::operator=(const RTree &rhs) {
if (&rhs != this) {
if (m_count > 0)
clear(true);
m_count = rhs.m_count;
m_queryTargetLevel = rhs.m_queryTargetLevel;
m_allocator = rhs.m_allocator;
m_indexable = rhs.m_indexable;
copyRec(rhs.m_root, m_root);
}
return *this;
}
#ifdef SPATIAL_TREE_USE_CPP11
TREE_TEMPLATE
TREE_QUAL &TREE_QUAL::operator=(RTree &&rhs) {
assert(this != &rhs);
if (m_count > 0)
clear(true);
swap(rhs);
return *this;
}
#endif
TREE_TEMPLATE
void TREE_QUAL::swap(RTree &other) {
std::swap(m_root, other.m_root);
std::swap(m_count, other.m_count);
std::swap(m_queryTargetLevel, other.m_queryTargetLevel);
std::swap(m_allocator, other.m_allocator);
std::swap(m_indexable, other.m_indexable);
}
TREE_TEMPLATE
template <typename Iter> void TREE_QUAL::insert(Iter first, Iter last) {
assert(m_root);
branch_type branch;
branch.child = NULL;
for (Iter it = first; it != last; ++it) {
const ValueType &value = *it;
branch.value = value;
branch.bbox.set(m_indexable.min(value), m_indexable.max(value));
insertImpl(branch, spatial::detail::DummyInsertPredicate(), 0);
++m_count;
#if SPATIAL_TREE_ALLOCATOR == SPATIAL_TREE_DEFAULT_ALLOCATOR
if (allocator_type::is_overflowable && m_allocator.overflowed())
break;
#endif
}
}
TREE_TEMPLATE
void TREE_QUAL::insert(const ValueType &value) {
assert(m_root);
branch_type branch;
branch.value = value;
branch.child = NULL;
branch.bbox.set(m_indexable.min(value), m_indexable.max(value));
insertImpl(branch, spatial::detail::DummyInsertPredicate(), 0);
++m_count;
}
TREE_TEMPLATE
template <typename Predicate>
bool TREE_QUAL::insert(const ValueType &value, const Predicate &predicate) {
assert(m_root);
branch_type branch;
branch.value = value;
branch.child = NULL;
branch.bbox.set(m_indexable.min(value), m_indexable.max(value));
bool success = insertImpl(branch, predicate, 0);
if (success)
++m_count;
return success;
}
TREE_TEMPLATE
void TREE_QUAL::translate(const T point[Dimension]) {
assert(m_root);
translateRec(*m_root, point);
}
TREE_TEMPLATE
void TREE_QUAL::remove(const ValueType &value) {
assert(m_root);
const bbox_type bbox(m_indexable.min(value), m_indexable.max(value));
if (removeImpl(bbox, value))
--m_count;
}
TREE_TEMPLATE
template <typename Predicate>
bool TREE_QUAL::hierachical_query(const Predicate &predicate) const {
return hierachical_query(predicate, spatial::detail::dummy_iterator()) > 0;
}
TREE_TEMPLATE
template <typename Predicate, typename OutIter>
size_t TREE_QUAL::hierachical_query(const Predicate &predicate,
OutIter out_it) const {
size_t foundCount = 0;
queryHierachicalRec(m_root, predicate, foundCount, out_it);
return foundCount;
}
TREE_TEMPLATE
template <typename Predicate>
bool TREE_QUAL::query(const Predicate &predicate) const {
return query(predicate, spatial::detail::dummy_iterator()) > 0;
}
TREE_TEMPLATE
template <typename Predicate, typename OutIter>
size_t TREE_QUAL::query(const Predicate &predicate, OutIter out_it) const {
size_t foundCount = 0;
queryRec(m_root, predicate, foundCount, out_it);
return foundCount;
}
TREE_TEMPLATE
template <typename OutIter>
size_t TREE_QUAL::nearest(const T point[2], T radius, OutIter out_it) const {
size_t foundCount = 0;
nearestRec(m_root, point, radius, foundCount, out_it);
return foundCount;
}
TREE_TEMPLATE
void TREE_QUAL::setQueryTargetLevel(int level) { m_queryTargetLevel = level; }
TREE_TEMPLATE
size_t TREE_QUAL::count() const {
assert(m_root);
assert(m_count == countImpl(*m_root));
return m_count;
}
TREE_TEMPLATE
size_t TREE_QUAL::bytes(bool estimate /*= true*/) const {
size_t size = sizeof(RTree);
if (!m_count)
return size;
if (estimate)
return size + nodeCount(count()) * sizeof(node_type);
depth_iterator it = const_cast<RTree &>(*this).dbegin();
size_t n = 0;
for (; !it.isNull(); ++it) {
++n;
}
return size + n * sizeof(node_type);
}
TREE_TEMPLATE
size_t TREE_QUAL::nodeCount(size_t numberOfItems) {
const double k = min_child_items;
const double invK1 = 1.0 / (k - 1.0);
const double depth = levels(numberOfItems);
// perfectly balanced k-ary tree formula
double count = std::pow(k, depth + 1.0) - 1;
count *= invK1;
return std::max(count * 0.5, 1.0);
}
TREE_TEMPLATE
size_t TREE_QUAL::branchCount(size_t numberOfItems) {
size_t count = nodeCount(numberOfItems) *
(min_child_items + max_child_items / min_child_items);
return count;
}
TREE_TEMPLATE
size_t TREE_QUAL::levels() const {
assert(m_root);
return m_root->level;
}
TREE_TEMPLATE
double TREE_QUAL::levels(size_t numberOfItems) {
static const double invLog = 1 / std::log(min_child_items);
const double depth = std::log(numberOfItems) * invLog - 1;
return depth;
}
TREE_TEMPLATE
typename TREE_QUAL::bbox_type TREE_QUAL::bbox() const {
assert(m_root);
return m_root->cover();
}
TREE_TEMPLATE
typename TREE_QUAL::allocator_type &TREE_QUAL::allocator() {
return m_allocator;
}
TREE_TEMPLATE
const typename TREE_QUAL::allocator_type &TREE_QUAL::allocator() const {
return m_allocator;
}
TREE_TEMPLATE
void TREE_QUAL::countRec(const node_type &node, size_t &count) const {
if (node.isBranch()) // not a leaf node
{
for (count_type index = 0; index < node.count; ++index) {
assert(node.children[index] != NULL);
countRec(*node.children[index], count);
}
}
else // A leaf node
{
count += node.count;
}
}
TREE_TEMPLATE
void TREE_QUAL::translateRec(node_type &node, const T point[Dimension]) {
for (count_type index = 0; index < node.count; ++index) {
node.bboxes[index].translate(point);
}
if (node.isBranch()) // not a leaf node
{
for (count_type index = 0; index < node.count; ++index) {
assert(node.children[index] != NULL);
translateRec(*node.children[index], point);
}
}
// A leaf node
}
TREE_TEMPLATE
size_t TREE_QUAL::countImpl(const node_type &node) const {
size_t count = 0;
countRec(node, count);
return count;
}
TREE_TEMPLATE
void TREE_QUAL::clear(bool recursiveCleanup /*= true*/) {
#if SPATIAL_TREE_ALLOCATOR == SPATIAL_TREE_DEFAULT_ALLOCATOR
if (allocator_type::is_overflowable)
recursiveCleanup &= !m_allocator.overflowed();
#endif
if (recursiveCleanup && m_root)
clearRec(m_root);
m_root = detail::allocate(m_allocator, 0);
m_count = 0;
}
TREE_TEMPLATE
void TREE_QUAL::clearRec(const node_ptr_type node) {
assert(node);
assert(node->level >= 0);
if (node->isBranch()) // This is an internal node in the tree
{
for (count_type index = 0; index < node->count; ++index) {
clearRec(node->children[index]);
}
}
detail::deallocate(m_allocator, node);
}
// Inserts a new data rectangle into the index structure.
// Recursively descends tree, propagates splits back up.
// Returns 0 if node was not split. Old node updated.
// If node was split, returns 1 and sets the pointer pointed to by
// new_node to point to the new node. Old node updated to become one of two.
// The level argument specifies the number of steps up from the leaf
// level to insert; e.g. a data rectangle goes in at level = 0.
TREE_TEMPLATE
template <typename Predicate>
bool TREE_QUAL::insertRec(const branch_type &branch, const Predicate &predicate,
node_type &node, node_ptr_type &newNode, bool &added,
int level) {
assert(level >= 0 && level <= node.level);
// TODO: profile and test a non-recursive version
// recurse until we reach the correct level for the new record. data records
// will always be called with level == 0 (leaf)
if (node.level > level) {
// Still above level for insertion, go down tree recursively
node_ptr_type otherNode = NULL;
// find the optimal branch for this record
const count_type index = pickBranch(branch.bbox, node);
// recursively insert this record into the picked branch
assert(node.children[index]);
bool childWasSplit = insertRec(branch, predicate, *node.children[index],
otherNode, added, level);
if (!childWasSplit) {
// Child was not split. Merge the bounding box of the new record with the
// existing bounding box
if (added)
node.bboxes[index] = branch.bbox.extended(node.bboxes[index]);
return false;
}
else if (otherNode) {
// Child was split. The old branches are now re-partitioned to two nodes
// so we have to re-calculate the bounding boxes of each node
node.bboxes[index] = node.children[index]->cover();
branch_type branch;
branch.child = otherNode;
branch.bbox = otherNode->cover();
// The old node is already a child of node. Now add the newly-created
// node to node as well. node might be split because of that.
return addBranch(branch, node, &newNode);
}
#if SPATIAL_TREE_ALLOCATOR == SPATIAL_TREE_DEFAULT_ALLOCATOR
else if (allocator_type::is_overflowable) {
// overflow error
return false;
}
#endif
}
else if (node.level == level) {
// Check if we should add the branch
if (!detail::checkInsertPredicate(predicate, node)) {
added = false;
return false;
}
// We have reached level for insertion. Add bbox, split if necessary
return addBranch(branch, node, &newNode);
}
// Should never occur
assert(0);
return false;
}
// Insert a data rectangle into an index structure.
// insertImpl provides for splitting the root;
// returns 1 if root was split, 0 if it was not.
// The level argument specifies the number of steps up from the leaf
// level to insert; e.g. a data rectangle goes in at level = 0.
// insertRec does the recursion.
TREE_TEMPLATE
template <typename Predicate>
bool TREE_QUAL::insertImpl(const branch_type &branch,
const Predicate &predicate, int level) {
assert(m_root);
assert(level >= 0 && level <= m_root->level);
#ifndef NDEBUG
for (int index = 0; index < Dimension; ++index) {
assert(branch.bbox.min[index] <= branch.bbox.max[index]);
}
#endif
node_ptr_type newNode = NULL;
bool added = true;
// Check if root was split
if (insertRec(branch, predicate, *m_root, newNode, added, level)) {
#if SPATIAL_TREE_ALLOCATOR == SPATIAL_TREE_DEFAULT_ALLOCATOR
if (allocator_type::is_overflowable && newNode == NULL) // overflow
return false;
#endif
// Grow tree taller and new root
node_ptr_type newRoot = detail::allocate(m_allocator, m_root->level + 1);
branch_type branch;
// add old root node as a child of the new root
branch.bbox = m_root->cover();
branch.child = m_root;
addBranch(branch, *newRoot, NULL);
// add the split node as a child of the new root
branch.bbox = newNode->cover();
branch.child = newNode;
addBranch(branch, *newRoot, NULL);
// set the new root as the root node
m_root = newRoot;
}
return added;
}
TREE_TEMPLATE
void TREE_QUAL::copyRec(const node_ptr_type src, node_ptr_type dst) {
*dst = *src;
for (count_type index = 0; index < src->count; ++index) {
const node_ptr_type srcCurrent = src->children[index];
if (srcCurrent) {
node_ptr_type dstCurrent = dst->children[index] =
detail::allocate(m_allocator, srcCurrent->level);
copyRec(srcCurrent, dstCurrent);
}
}
}
// Add a branch to a node. Split the node if necessary.
// Returns 0 if node not split. Old node updated.
// Returns 1 if node split, sets *new_node to address of new node.
// Old node updated, becomes one of two.
TREE_TEMPLATE
bool TREE_QUAL::addBranch(const branch_type &branch, node_type &node,
node_dptr_type newNode) const {
if (node.addBranch(branch)) {
return false;
}
assert(newNode);
splitNode(node, branch, newNode);
return true;
}
// Pick a branch. Pick the one that will need the smallest increase
// in area to accomodate the new rectangle. This will result in the
// least total area for the covering rectangles in the current node.
// In case of a tie, pick the one which was smaller before, to get
// the best resolution when searching.
TREE_TEMPLATE
typename TREE_QUAL::count_type
TREE_QUAL::pickBranch(const bbox_type &bbox, const node_type &node) const {
bool firstTime = true;
real_type increase;
real_type bestIncr = (real_type)-1;
real_type area;
real_type bestArea;
count_type best;
bbox_type tempbbox_type;
for (count_type index = 0; index < node.count; ++index) {
const bbox_type &curbbox_type = node.bboxes[index];
area = curbbox_type.template volume<bbox_volume_mode, RealType>();
tempbbox_type = bbox.extended(curbbox_type);
increase =
tempbbox_type.template volume<bbox_volume_mode, RealType>() - area;
if ((increase < bestIncr) || firstTime) {
best = index;
bestArea = area;
bestIncr = increase;
firstTime = false;
}
else if ((increase == bestIncr) && (area < bestArea)) {
best = index;
bestArea = area;
bestIncr = increase;
}
}
assert(node.count);
return best;
}
// Split a node.
// Divides the nodes branches and the extra one between two nodes.
// Old node is one of the new ones, and one really new one is created.
// Tries more than one method for choosing a partition, uses best result.
TREE_TEMPLATE
void TREE_QUAL::splitNode(node_type &node, const branch_type &branch,
node_dptr_type newNodePtr) const {
assert(newNodePtr);
node_ptr_type &newNode = *newNodePtr;
// Could just use local here, but member or external is faster since it is
// reused
m_parVars.clear();
// Load all the branches into a buffer, initialize old node
getBranches(node, branch, m_parVars);
// Find partition
choosePartition(m_parVars);
// Create a new node to hold (about) half of the branches
newNode = detail::allocate(m_allocator, node.level);
#if SPATIAL_TREE_ALLOCATOR == SPATIAL_TREE_DEFAULT_ALLOCATOR
if (allocator_type::is_overflowable && !newNode)
return;
#endif
assert(newNode);
// Put branches from buffer into 2 nodes according to the chosen partition
node.count = 0;
loadNodes(node, *newNode, m_parVars);
assert((node.count + newNode->count) == m_parVars.maxFill());
}
// Load branch buffer with branches from full node plus the extra branch.
TREE_TEMPLATE
void TREE_QUAL::getBranches(const node_type &node, const branch_type &branch,
BranchVars &branchVars) const {
assert(node.count == max_child_items);
// Load the branch buffer
for (size_t index = 0; index < max_child_items; ++index) {
branch_type &branch = branchVars.branches[index];
branch.bbox = node.bboxes[index];
branch.value = node.values[index];
branch.child = node.children[index];
}
branchVars.branches[max_child_items] = branch;
// Calculate bbox containing all in the set
branchVars.coverSplit = branchVars.branches[0].bbox;
for (int index = 1; index < max_child_items + 1; ++index) {
branchVars.coverSplit.extend(branchVars.branches[index].bbox);
}
branchVars.coverSplitArea =
branchVars.coverSplit.template volume<bbox_volume_mode, RealType>();
}
// Method #0 for choosing a partition:
// As the seeds for the two groups, pick the two rects that would waste the
// most area if covered by a single rectangle, i.e. evidently the worst pair
// to have in the same group.
// Of the remaining, one at a time is chosen to be put in one of the two groups.
// The one chosen is the one with the greatest difference in area expansion
// depending on which group - the bbox most strongly attracted to one group
// and repelled from the other.
// If one group gets too full (more would force other group to violate min
// fill requirement) then other group gets the rest.
// These last are the ones that can go in either group most easily.
TREE_TEMPLATE
void TREE_QUAL::choosePartition(PartitionVars &partitionVars) const {
real_type biggestDiff;
count_type chosen;
int group, betterGroup;
pickSeeds(partitionVars);
while (((partitionVars.totalCount()) < partitionVars.maxFill()) &&
(partitionVars.count[0] < partitionVars.diffFill()) &&
(partitionVars.count[1] < partitionVars.diffFill())) {
biggestDiff = (real_type)-1;
for (count_type index = 0; index < partitionVars.maxFill(); ++index) {
if (PartitionVars::ePartitionUnused != partitionVars.partitions[index])
continue;