Octree.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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_.Size() * 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_.Center();
  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_.Center();
  111. Vector3 drawableCenter = drawable->GetWorldBoundingBox().Center();
  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_.Size() * 0.5;
  123. Vector3 drawableSize = drawable->GetWorldBoundingBox().Size();
  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, bool inside) const
  146. {
  147. if (!numDrawables_)
  148. return;
  149. Intersection res = query.TestOctant(cullingBox_, inside);
  150. if (res == OUTSIDE && this != root_)
  151. // Fully outside, so cull this octant, its children & drawables
  152. return;
  153. if (res == INSIDE)
  154. inside = true;
  155. for (PODVector<Drawable*>::ConstIterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  156. {
  157. Drawable* drawable = *i;
  158. unsigned flags = drawable->GetDrawableFlags();
  159. if (!(flags & query.drawableFlags_) || !drawable->IsVisible())
  160. continue;
  161. if (query.occludersOnly_ && !drawable->IsOccluder())
  162. continue;
  163. if (query.shadowCastersOnly_ && !drawable->GetCastShadows())
  164. continue;
  165. if (query.TestDrawable(drawable->GetWorldBoundingBox(), inside) != OUTSIDE)
  166. query.result_.Push(drawable);
  167. }
  168. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  169. {
  170. if (children_[i])
  171. children_[i]->GetDrawablesInternal(query, inside);
  172. }
  173. }
  174. void Octant::GetDrawablesInternal(RayOctreeQuery& query) const
  175. {
  176. if (!numDrawables_)
  177. return;
  178. float octantDist = cullingBox_.Distance(query.ray_);
  179. if (octantDist >= query.maxDistance_)
  180. return;
  181. for (PODVector<Drawable*>::ConstIterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  182. {
  183. Drawable* drawable = *i;
  184. unsigned drawableFlags = drawable->GetDrawableFlags();
  185. if (!(drawableFlags & query.drawableFlags_) || !drawable->IsVisible())
  186. continue;
  187. if (query.occludersOnly_ && !drawable->IsOccluder())
  188. continue;
  189. if (query.shadowCastersOnly_ && !drawable->GetCastShadows())
  190. continue;
  191. float drawableDist = drawable->GetWorldBoundingBox().Distance(query.ray_);
  192. // The drawable will possibly do more accurate collision testing, then store the result(s)
  193. if (drawableDist < query.maxDistance_)
  194. drawable->ProcessRayQuery(query, drawableDist);
  195. }
  196. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  197. {
  198. if (children_[i])
  199. children_[i]->GetDrawablesInternal(query);
  200. }
  201. }
  202. void Octant::Release()
  203. {
  204. if (root_ && this != root_)
  205. {
  206. // Remove the drawables (if any) from this octant to the root octant
  207. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  208. {
  209. (*i)->SetOctant(root_);
  210. root_->drawables_.Push(*i);
  211. root_->QueueReinsertion(*i);
  212. }
  213. drawables_.Clear();
  214. numDrawables_ = 0;
  215. }
  216. else if (!root_)
  217. {
  218. // If the whole octree is being destroyed, just detach the drawables
  219. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  220. (*i)->SetOctant(0);
  221. }
  222. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  223. DeleteChild(i);
  224. }
  225. OBJECTTYPESTATIC(Octree);
  226. Octree::Octree(Context* context) :
  227. Component(context),
  228. Octant(BoundingBox(-DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE), 0, 0, this),
  229. numLevels_(DEFAULT_OCTREE_LEVELS)
  230. {
  231. }
  232. Octree::~Octree()
  233. {
  234. // Reset root pointer from all child octants now so that they do not move their drawables to root
  235. ResetRoot();
  236. }
  237. void Octree::RegisterObject(Context* context)
  238. {
  239. context->RegisterFactory<Octree>();
  240. ATTRIBUTE(Octree, VAR_VECTOR3, "Bounding Box Min", worldBoundingBox_.min_, Vector3(-DEFAULT_OCTREE_SIZE, -DEFAULT_OCTREE_SIZE, -DEFAULT_OCTREE_SIZE), AM_DEFAULT);
  241. ATTRIBUTE(Octree, VAR_VECTOR3, "Bounding Box Max", worldBoundingBox_.max_, Vector3(DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE), AM_DEFAULT);
  242. ATTRIBUTE(Octree, VAR_INT, "Number of Levels", numLevels_, DEFAULT_OCTREE_LEVELS, AM_DEFAULT);
  243. }
  244. void Octree::OnSetAttribute(const AttributeInfo& attr, const Variant& value)
  245. {
  246. // If any of the (size) attributes changes, resize the octree
  247. Serializable::OnSetAttribute(attr, value);
  248. Resize(worldBoundingBox_, numLevels_);
  249. }
  250. void Octree::Resize(const BoundingBox& box, unsigned numLevels)
  251. {
  252. PROFILE(ResizeOctree);
  253. numLevels = Max((int)numLevels, 1);
  254. // If drawables exist, they are temporarily moved to the root
  255. Release();
  256. Vector3 halfSize = box.Size() * 0.5f;
  257. worldBoundingBox_ = box;
  258. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize, worldBoundingBox_.max_ + halfSize);
  259. numDrawables_ = drawables_.Size();
  260. numLevels_ = numLevels;
  261. }
  262. void Octree::Update(const FrameInfo& frame)
  263. {
  264. {
  265. PROFILE(UpdateDrawables);
  266. // Let drawables update themselves before reinsertion
  267. for (HashSet<Drawable*>::Iterator i = drawableUpdates_.Begin(); i != drawableUpdates_.End(); ++i)
  268. (*i)->Update(frame);
  269. }
  270. {
  271. PROFILE(ReinsertDrawables);
  272. // Reinsert drawables into the octree
  273. for (HashSet<Drawable*>::Iterator i = drawableReinsertions_.Begin(); i != drawableReinsertions_.End(); ++i)
  274. {
  275. Drawable* drawable = *i;
  276. Octant* octant = drawable->GetOctant();
  277. if (octant)
  278. {
  279. bool reinsert = false;
  280. if (octant == this)
  281. {
  282. // Handle root octant as special case: if outside the root, do not reinsert
  283. if (GetCullingBox().IsInside(drawable->GetWorldBoundingBox()) == INSIDE && !CheckDrawableSize(drawable))
  284. reinsert = true;
  285. }
  286. else
  287. {
  288. // Otherwise reinsert if outside current octant or if size does not fit octant size
  289. if (octant->GetCullingBox().IsInside(drawable->GetWorldBoundingBox()) != INSIDE ||
  290. !octant->CheckDrawableSize(drawable))
  291. reinsert = true;
  292. }
  293. if (reinsert)
  294. InsertDrawable(drawable);
  295. }
  296. else
  297. InsertDrawable(drawable);
  298. }
  299. }
  300. drawableUpdates_.Clear();
  301. drawableReinsertions_.Clear();
  302. }
  303. void Octree::GetDrawables(OctreeQuery& query) const
  304. {
  305. PROFILE(OctreeQuery);
  306. query.result_.Clear();
  307. GetDrawablesInternal(query, false);
  308. }
  309. void Octree::GetDrawables(RayOctreeQuery& query) const
  310. {
  311. PROFILE(Raycast);
  312. query.result_.Clear();
  313. GetDrawablesInternal(query);
  314. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  315. }
  316. void Octree::QueueUpdate(Drawable* drawable)
  317. {
  318. drawableUpdates_.Insert(drawable);
  319. }
  320. void Octree::QueueReinsertion(Drawable* drawable)
  321. {
  322. drawableReinsertions_.Insert(drawable);
  323. }
  324. void Octree::CancelUpdate(Drawable* drawable)
  325. {
  326. drawableUpdates_.Erase(drawable);
  327. }
  328. void Octree::CancelReinsertion(Drawable* drawable)
  329. {
  330. drawableReinsertions_.Erase(drawable);
  331. }
  332. void Octree::DrawDebugGeometry(bool depthTest)
  333. {
  334. PROFILE(OctreeDrawDebug);
  335. DebugRenderer* debug = GetComponent<DebugRenderer>();
  336. if (!debug)
  337. return;
  338. Octant::DrawDebugGeometry(debug, depthTest);
  339. }