Octree.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "Profiler.h"
  27. #include "Octree.h"
  28. #include "OctreeQuery.h"
  29. #include "Sort.h"
  30. #include "DebugNew.h"
  31. #ifdef _MSC_VER
  32. #pragma warning(disable:4355)
  33. #endif
  34. static const float DEFAULT_OCTREE_SIZE = 1000.0f;
  35. static const int DEFAULT_OCTREE_LEVELS = 8;
  36. inline bool CompareRayQueryResults(const RayQueryResult& lhs, const RayQueryResult& rhs)
  37. {
  38. return lhs.distance_ < rhs.distance_;
  39. }
  40. Octant::Octant(const BoundingBox& box, unsigned level, Octant* parent, Octree* root) :
  41. worldBoundingBox_(box),
  42. level_(level),
  43. parent_(parent),
  44. root_(root),
  45. numDrawables_(0)
  46. {
  47. Vector3 halfSize = worldBoundingBox_.GetSize() * 0.5f;
  48. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize, worldBoundingBox_.max_ + halfSize);
  49. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  50. children_[i] = 0;
  51. }
  52. Octant::~Octant()
  53. {
  54. Release();
  55. }
  56. Octant* Octant::GetOrCreateChild(unsigned index)
  57. {
  58. if (children_[index])
  59. return children_[index];
  60. Vector3 newMin = worldBoundingBox_.min_;
  61. Vector3 newMax = worldBoundingBox_.max_;
  62. Vector3 oldCenter = worldBoundingBox_.GetCenter();
  63. if (index & 1)
  64. newMin.x_ = oldCenter.x_;
  65. else
  66. newMax.x_ = oldCenter.x_;
  67. if (index & 2)
  68. newMin.y_ = oldCenter.y_;
  69. else
  70. newMax.y_ = oldCenter.y_;
  71. if (index & 4)
  72. newMin.z_ = oldCenter.z_;
  73. else
  74. newMax.z_ = oldCenter.z_;
  75. children_[index] = new Octant(BoundingBox(newMin, newMax), level_ + 1, this, root_);
  76. return children_[index];
  77. }
  78. void Octant::DeleteChild(unsigned index)
  79. {
  80. delete children_[index];
  81. children_[index] = 0;
  82. }
  83. void Octant::DeleteChild(Octant* octant)
  84. {
  85. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  86. {
  87. if (children_[i] == octant)
  88. {
  89. delete octant;
  90. children_[i] = 0;
  91. return;
  92. }
  93. }
  94. }
  95. void Octant::InsertDrawable(Drawable* drawable)
  96. {
  97. // If size OK or outside, stop recursion & insert here
  98. if ((CheckDrawableSize(drawable)) || (cullingBox_.IsInside(drawable->GetWorldBoundingBox()) != INSIDE))
  99. {
  100. if (drawable->octant_ != this)
  101. {
  102. // Add first, then remove, because drawable count going to zero deletes the octree branch in question
  103. Octant* oldOctant = drawable->octant_;
  104. AddDrawable(drawable);
  105. if (oldOctant)
  106. oldOctant->RemoveDrawable(drawable, false);
  107. }
  108. return;
  109. }
  110. Vector3 octantCenter = worldBoundingBox_.GetCenter();
  111. Vector3 drawableCenter = drawable->GetWorldBoundingBox().GetCenter();
  112. unsigned x = drawableCenter.x_ < octantCenter.x_ ? 0 : 1;
  113. unsigned y = drawableCenter.y_ < octantCenter.y_ ? 0 : 2;
  114. unsigned z = drawableCenter.z_ < octantCenter.z_ ? 0 : 4;
  115. GetOrCreateChild(x + y + z)->InsertDrawable(drawable);
  116. }
  117. bool Octant::CheckDrawableSize(Drawable* drawable) const
  118. {
  119. // If max split level, size always OK
  120. if (level_ == root_->GetNumLevels())
  121. return true;
  122. Vector3 octantHalfSize = worldBoundingBox_.GetSize() * 0.5;
  123. Vector3 drawableSize = drawable->GetWorldBoundingBox().GetSize();
  124. return (drawableSize.x_ >= octantHalfSize.x_) || (drawableSize.y_ >= octantHalfSize.y_) || (drawableSize.z_ >=
  125. octantHalfSize.z_);
  126. }
  127. void Octant::ResetRoot()
  128. {
  129. root_ = 0;
  130. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  131. {
  132. if (children_[i])
  133. children_[i]->ResetRoot();
  134. }
  135. }
  136. void Octant::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  137. {
  138. debug->AddBoundingBox(worldBoundingBox_, Color(0.25f, 0.25f, 0.25f), depthTest);
  139. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  140. {
  141. if (children_[i])
  142. children_[i]->DrawDebugGeometry(debug, depthTest);
  143. }
  144. }
  145. void Octant::GetDrawablesInternal(OctreeQuery& query, unsigned mask) const
  146. {
  147. if (!numDrawables_)
  148. return;
  149. if (mask != M_MAX_UNSIGNED)
  150. {
  151. Intersection res = query.TestOctant(cullingBox_, mask);
  152. if ((res == OUTSIDE) && (this != root_))
  153. // Fully outside, so cull this octant, its children & drawables
  154. return;
  155. if (res == INSIDE)
  156. // Fully inside, no culling checks necessary for children & drawables
  157. mask = M_MAX_UNSIGNED;
  158. }
  159. for (Vector<Drawable*>::ConstIterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  160. {
  161. Drawable* drawable = *i;
  162. unsigned flags = drawable->GetDrawableFlags();
  163. if ((!(flags & query.drawableFlags_)) || (!drawable->IsVisible()))
  164. continue;
  165. if ((query.occludersOnly_) && (!drawable->IsOccluder()))
  166. continue;
  167. if ((query.shadowCastersOnly_) && (!drawable->GetCastShadows()))
  168. continue;
  169. if (query.TestDrawable(drawable->GetWorldBoundingBox(), mask) != OUTSIDE)
  170. query.result_.Push(drawable);
  171. }
  172. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  173. {
  174. if (children_[i])
  175. children_[i]->GetDrawablesInternal(query, mask);
  176. }
  177. }
  178. void Octant::GetDrawablesInternal(RayOctreeQuery& query) const
  179. {
  180. if (!numDrawables_)
  181. return;
  182. float octantDist = cullingBox_.GetDistance(query.ray_);
  183. if (octantDist >= query.maxDistance_)
  184. return;
  185. for (Vector<Drawable*>::ConstIterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  186. {
  187. Drawable* drawable = *i;
  188. unsigned drawableFlags = drawable->GetDrawableFlags();
  189. if ((!(drawableFlags & query.drawableFlags_)) || (!drawable->IsVisible()))
  190. continue;
  191. if ((query.occludersOnly_) && (!drawable->IsOccluder()))
  192. continue;
  193. if ((query.shadowCastersOnly_) && (!drawable->GetCastShadows()))
  194. continue;
  195. float drawableDist = drawable->GetWorldBoundingBox().GetDistance(query.ray_);
  196. // The drawable will possibly do more accurate collision testing, then store the result(s)
  197. if (drawableDist < query.maxDistance_)
  198. drawable->ProcessRayQuery(query, drawableDist);
  199. }
  200. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  201. {
  202. if (children_[i])
  203. children_[i]->GetDrawablesInternal(query);
  204. }
  205. }
  206. void Octant::Release()
  207. {
  208. if ((root_) && (this != root_))
  209. {
  210. // Remove the drawables (if any) from this octant to the root octant
  211. for (Vector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  212. {
  213. (*i)->SetOctant(root_);
  214. root_->drawables_.Push(*i);
  215. root_->QueueReinsertion(*i);
  216. }
  217. drawables_.Clear();
  218. numDrawables_ = 0;
  219. }
  220. else if (!root_)
  221. {
  222. // If the whole octree is being destroyed, just detach the drawables
  223. for (Vector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  224. (*i)->SetOctant(0);
  225. }
  226. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  227. DeleteChild(i);
  228. }
  229. OBJECTTYPESTATIC(Octree);
  230. Octree::Octree(Context* context) :
  231. Component(context),
  232. Octant(BoundingBox(-DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE), 0, 0, this),
  233. numLevels_(DEFAULT_OCTREE_LEVELS)
  234. {
  235. }
  236. Octree::~Octree()
  237. {
  238. // Reset root pointer from all child octants now so that they do not move their drawables to root
  239. ResetRoot();
  240. }
  241. void Octree::RegisterObject(Context* context)
  242. {
  243. context->RegisterFactory<Octree>();
  244. ATTRIBUTE(Octree, VAR_VECTOR3, "Bounding Box Min", worldBoundingBox_.min_, Vector3(-DEFAULT_OCTREE_SIZE, -DEFAULT_OCTREE_SIZE, -DEFAULT_OCTREE_SIZE));
  245. ATTRIBUTE(Octree, VAR_VECTOR3, "Bounding Box Max", worldBoundingBox_.max_, Vector3(DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE));
  246. ATTRIBUTE(Octree, VAR_INT, "Number of Levels", numLevels_, DEFAULT_OCTREE_LEVELS);
  247. }
  248. void Octree::OnSetAttribute(const AttributeInfo& attr, const Variant& value)
  249. {
  250. Serializable::OnSetAttribute(attr, value);
  251. // If any of the size attributes changes, resize the octree
  252. /// \todo This may lead to unnecessary resizing, however it is fast once child nodes have been removed
  253. switch (attr.offset_)
  254. {
  255. case offsetof(Octree, worldBoundingBox_.min_):
  256. case offsetof(Octree, worldBoundingBox_.max_):
  257. case offsetof(Octree, numLevels_):
  258. Resize(worldBoundingBox_, numLevels_);
  259. break;
  260. }
  261. }
  262. void Octree::Resize(const BoundingBox& box, unsigned numLevels)
  263. {
  264. PROFILE(ResizeOctree);
  265. numLevels = Max((int)numLevels, 1);
  266. // If drawables exist, they are temporarily moved to the root
  267. Release();
  268. Vector3 halfSize = box.GetSize() * 0.5f;
  269. worldBoundingBox_ = box;
  270. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize, worldBoundingBox_.max_ + halfSize);
  271. numDrawables_ = drawables_.Size();
  272. numLevels_ = numLevels;
  273. }
  274. void Octree::Update(const FrameInfo& frame)
  275. {
  276. {
  277. PROFILE(UpdateDrawables);
  278. // Let drawables update themselves before reinsertion
  279. for (Set<Drawable*>::Iterator i = drawableUpdates_.Begin(); i != drawableUpdates_.End(); ++i)
  280. (*i)->Update(frame);
  281. }
  282. {
  283. PROFILE(ReinsertDrawables);
  284. // Reinsert drawables into the octree
  285. for (Set<Drawable*>::Iterator i = drawableReinsertions_.Begin(); i != drawableReinsertions_.End(); ++i)
  286. {
  287. Drawable* drawable = *i;
  288. Octant* octant = drawable->GetOctant();
  289. if (octant)
  290. {
  291. bool reinsert = false;
  292. if (octant == this)
  293. {
  294. // Handle root octant as special case: if outside the root, do not reinsert
  295. if ((GetCullingBox().IsInside(drawable->GetWorldBoundingBox()) == INSIDE) && (!CheckDrawableSize(drawable)))
  296. reinsert = true;
  297. }
  298. else
  299. {
  300. // Otherwise reinsert if outside current octant or if size does not fit octant size
  301. if ((octant->GetCullingBox().IsInside(drawable->GetWorldBoundingBox()) != INSIDE) ||
  302. (!octant->CheckDrawableSize(drawable)))
  303. reinsert = true;
  304. }
  305. if (reinsert)
  306. InsertDrawable(drawable);
  307. }
  308. else
  309. InsertDrawable(drawable);
  310. }
  311. }
  312. drawableUpdates_.Clear();
  313. drawableReinsertions_.Clear();
  314. }
  315. void Octree::GetDrawables(OctreeQuery& query) const
  316. {
  317. PROFILE(OctreeQuery);
  318. query.result_.Clear();
  319. GetDrawablesInternal(query, 0);
  320. }
  321. void Octree::GetDrawables(RayOctreeQuery& query) const
  322. {
  323. PROFILE(Raycast);
  324. query.result_.Clear();
  325. GetDrawablesInternal(query);
  326. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  327. }
  328. void Octree::QueueUpdate(Drawable* drawable)
  329. {
  330. drawableUpdates_.Insert(drawable);
  331. }
  332. void Octree::QueueReinsertion(Drawable* drawable)
  333. {
  334. drawableReinsertions_.Insert(drawable);
  335. }
  336. void Octree::CancelUpdate(Drawable* drawable)
  337. {
  338. drawableUpdates_.Erase(drawable);
  339. }
  340. void Octree::CancelReinsertion(Drawable* drawable)
  341. {
  342. drawableReinsertions_.Erase(drawable);
  343. }
  344. void Octree::DrawDebugGeometry(bool depthTest)
  345. {
  346. PROFILE(OctreeDrawDebug);
  347. DebugRenderer* debug = GetComponent<DebugRenderer>();
  348. if (!debug)
  349. return;
  350. Octant::DrawDebugGeometry(debug, depthTest);
  351. }