2 * PositionedOctree - define a spatial octree containing Positioned items
3 * arranged by their global cartesian position.
6 // Written by James Turner, started 2012.
8 // Copyright (C) 2012 James Turner
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include "PositionedOctree.hxx"
29 #include "positioned.hxx"
32 #include <algorithm> // for sort
33 #include <cstring> // for memset
36 #include <boost/foreach.hpp>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/structure/exception.hxx>
47 Node* global_spatialOctree = NULL;
49 Leaf::Leaf(const SGBoxd& aBox, int64_t aIdent) :
55 void Leaf::visit(const SGVec3d& aPos, double aCutoff,
56 FGPositioned::Filter* aFilter,
57 FindNearestResults& aResults, FindNearestPQueue&)
59 int previousResultsSize = aResults.size();
61 NavDataCache* cache = NavDataCache::instance();
65 ChildMap::const_iterator it = children.lower_bound(aFilter->minType());
66 ChildMap::const_iterator end = children.upper_bound(aFilter->maxType());
68 for (; it != end; ++it) {
69 FGPositioned* p = cache->loadById(it->second);
70 double d = dist(aPos, p->cart());
75 if (aFilter && !aFilter->pass(p)) {
80 aResults.push_back(OrderedPositioned(p, d));
83 if (addedCount == 0) {
87 // keep aResults sorted
88 // sort the new items, usually just one or two items
89 std::sort(aResults.begin() + previousResultsSize, aResults.end());
91 // merge the two sorted ranges together - in linear time
92 std::inplace_merge(aResults.begin(),
93 aResults.begin() + previousResultsSize, aResults.end());
96 void Leaf::insertChild(FGPositioned::Type ty, PositionedID id)
98 assert(childrenLoaded);
99 children.insert(children.end(), TypedPositioned(ty, id));
102 void Leaf::loadChildren()
104 if (childrenLoaded) {
108 NavDataCache* cache = NavDataCache::instance();
109 BOOST_FOREACH(TypedPositioned tp, cache->getOctreeLeafChildren(guid())) {
110 children.insert(children.end(), tp);
111 } // of leaf members iteration
113 childrenLoaded = true;
116 Branch::Branch(const SGBoxd& aBox, int64_t aIdent) :
118 childrenLoaded(false)
120 memset(children, 0, sizeof(Node*) * 8);
123 void Branch::visit(const SGVec3d& aPos, double aCutoff,
124 FGPositioned::Filter*,
125 FindNearestResults&, FindNearestPQueue& aQ)
128 for (unsigned int i=0; i<8; ++i) {
133 double d = children[i]->distToNearest(aPos);
135 continue; // exceeded cutoff
138 aQ.push(Ordered<Node*>(children[i], d));
139 } // of child iteration
142 Node* Branch::childForPos(const SGVec3d& aCart) const
144 assert(contains(aCart));
147 SGVec3d center(_box.getCenter());
148 // tests must match indices in SGbox::getCorner
149 if (aCart.x() < center.x()) {
153 if (aCart.y() < center.y()) {
157 if (aCart.z() < center.z()) {
161 return childAtIndex(childIndex);
164 Node* Branch::childAtIndex(int childIndex) const
166 Node* child = children[childIndex];
167 if (!child) { // lazy building of children
168 SGBoxd cb(boxForChild(childIndex));
169 double d2 = dot(cb.getSize(), cb.getSize());
171 assert(((_ident << 3) >> 3) == _ident);
173 // child index is 0..7, so 3-bits is sufficient, and hence we can
174 // pack 20 levels of octree into a int64, which is plenty
175 int64_t childIdent = (_ident << 3) | childIndex;
177 if (d2 < LEAF_SIZE_SQR) {
178 child = new Leaf(cb, childIdent);
180 child = new Branch(cb, childIdent);
183 children[childIndex] = child;
185 if (childrenLoaded) {
186 // childrenLoad is done, so we're defining a new node - add it to the
188 NavDataCache::instance()->defineOctreeNode(const_cast<Branch*>(this), child);
192 return children[childIndex];
195 void Branch::loadChildren() const
197 if (childrenLoaded) {
201 int childrenMask = NavDataCache::instance()->getOctreeBranchChildren(guid());
202 for (int i=0; i<8; ++i) {
203 if ((1 << i) & childrenMask) {
204 childAtIndex(i); // accessing will create!
206 } // of child index iteration
208 // set this after creating the child nodes, so the cache update logic
209 // in childAtIndex knows any future created children need to be added.
210 childrenLoaded = true;
213 int Branch::childMask() const
216 for (int i=0; i<8; ++i) {
225 void findNearestN(const SGVec3d& aPos, unsigned int aN, double aCutoffM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
228 FindNearestPQueue pq;
229 FindNearestResults results;
230 pq.push(Ordered<Node*>(global_spatialOctree, 0));
231 double cut = aCutoffM;
233 while (!pq.empty()) {
234 if (!results.empty()) {
235 // terminate the search if we have sufficent results, and we are
236 // sure no node still on the queue contains a closer match
237 double furthestResultOrder = results.back().order();
238 // std::cout << "furthest result:" << furthestResultOrder << ", top node order:" << pq.top().order() << std::endl;
239 if ((results.size() >= aN) && (furthestResultOrder < pq.top().order())) {
244 Node* nd = pq.top().get();
247 // std::cout << "visiting:" << std::oct << nd->guid() << "(" << std::dec << nd->guid() << ")" << std::endl;
248 nd->visit(aPos, cut, aFilter, results, pq);
249 } // of queue iteration
251 // depending on leaf population, we may have (slighty) more results
253 unsigned int numResults = std::min((unsigned int) results.size(), aN);
255 aResults.resize(numResults);
256 for (unsigned int r=0; r<numResults; ++r) {
257 aResults[r] = results[r].get();
261 void findAllWithinRange(const SGVec3d& aPos, double aRangeM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
264 FindNearestPQueue pq;
265 FindNearestResults results;
266 pq.push(Ordered<Node*>(global_spatialOctree, 0));
267 double rng = aRangeM;
269 while (!pq.empty()) {
270 Node* nd = pq.top().get();
273 nd->visit(aPos, rng, aFilter, results, pq);
274 } // of queue iteration
276 unsigned int numResults = results.size();
278 aResults.resize(numResults);
279 for (unsigned int r=0; r<numResults; ++r) {
280 aResults[r] = results[r].get();
284 } // of namespace Octree
286 } // of namespace flightgear