Octree.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/Thread.h"
  27. #include "../Core/WorkQueue.h"
  28. #include "../Graphics/DebugRenderer.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/Octree.h"
  31. #include "../IO/Log.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/SceneEvents.h"
  34. #include "../DebugNew.h"
  35. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. namespace Urho3D
  39. {
  40. static const float DEFAULT_OCTREE_SIZE = 1000.0f;
  41. static const int DEFAULT_OCTREE_LEVELS = 8;
  42. extern const char* SUBSYSTEM_CATEGORY;
  43. void UpdateDrawablesWork(const WorkItem* item, unsigned threadIndex)
  44. {
  45. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  46. auto** start = reinterpret_cast<Drawable**>(item->start_);
  47. auto** end = reinterpret_cast<Drawable**>(item->end_);
  48. while (start != end)
  49. {
  50. Drawable* drawable = *start;
  51. if (drawable)
  52. drawable->Update(frame);
  53. ++start;
  54. }
  55. }
  56. inline bool CompareRayQueryResults(const RayQueryResult& lhs, const RayQueryResult& rhs)
  57. {
  58. return lhs.distance_ < rhs.distance_;
  59. }
  60. Octant::Octant(const BoundingBox& box, unsigned level, Octant* parent, Octree* root, unsigned index) :
  61. level_(level),
  62. parent_(parent),
  63. root_(root),
  64. index_(index)
  65. {
  66. Initialize(box);
  67. }
  68. Octant::~Octant()
  69. {
  70. if (root_)
  71. {
  72. // Remove the drawables (if any) from this octant to the root octant
  73. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  74. {
  75. (*i)->SetOctant(root_);
  76. root_->drawables_.Push(*i);
  77. root_->QueueUpdate(*i);
  78. }
  79. drawables_.Clear();
  80. numDrawables_ = 0;
  81. }
  82. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  83. DeleteChild(i);
  84. }
  85. Octant* Octant::GetOrCreateChild(unsigned index)
  86. {
  87. if (children_[index])
  88. return children_[index];
  89. Vector3 newMin = worldBoundingBox_.min_;
  90. Vector3 newMax = worldBoundingBox_.max_;
  91. Vector3 oldCenter = worldBoundingBox_.Center();
  92. if (index & 1u)
  93. newMin.x_ = oldCenter.x_;
  94. else
  95. newMax.x_ = oldCenter.x_;
  96. if (index & 2u)
  97. newMin.y_ = oldCenter.y_;
  98. else
  99. newMax.y_ = oldCenter.y_;
  100. if (index & 4u)
  101. newMin.z_ = oldCenter.z_;
  102. else
  103. newMax.z_ = oldCenter.z_;
  104. children_[index] = new Octant(BoundingBox(newMin, newMax), level_ + 1, this, root_, index);
  105. return children_[index];
  106. }
  107. void Octant::DeleteChild(unsigned index)
  108. {
  109. assert(index < NUM_OCTANTS);
  110. delete children_[index];
  111. children_[index] = nullptr;
  112. }
  113. void Octant::InsertDrawable(Drawable* drawable)
  114. {
  115. const BoundingBox& box = drawable->GetWorldBoundingBox();
  116. // If root octant, insert all non-occludees here, so that octant occlusion does not hide the drawable.
  117. // Also if drawable is outside the root octant bounds, insert to root
  118. bool insertHere;
  119. if (this == root_)
  120. insertHere = !drawable->IsOccludee() || cullingBox_.IsInside(box) != INSIDE || CheckDrawableFit(box);
  121. else
  122. insertHere = CheckDrawableFit(box);
  123. if (insertHere)
  124. {
  125. Octant* oldOctant = drawable->octant_;
  126. if (oldOctant != this)
  127. {
  128. // Add first, then remove, because drawable count going to zero deletes the octree branch in question
  129. AddDrawable(drawable);
  130. if (oldOctant)
  131. oldOctant->RemoveDrawable(drawable, false);
  132. }
  133. }
  134. else
  135. {
  136. Vector3 boxCenter = box.Center();
  137. unsigned x = boxCenter.x_ < center_.x_ ? 0 : 1;
  138. unsigned y = boxCenter.y_ < center_.y_ ? 0 : 2;
  139. unsigned z = boxCenter.z_ < center_.z_ ? 0 : 4;
  140. GetOrCreateChild(x + y + z)->InsertDrawable(drawable);
  141. }
  142. }
  143. bool Octant::CheckDrawableFit(const BoundingBox& box) const
  144. {
  145. Vector3 boxSize = box.Size();
  146. // If max split level, size always OK, otherwise check that box is at least half size of octant
  147. if (level_ >= root_->GetNumLevels() || boxSize.x_ >= halfSize_.x_ || boxSize.y_ >= halfSize_.y_ ||
  148. boxSize.z_ >= halfSize_.z_)
  149. return true;
  150. // Also check if the box can not fit a child octant's culling box, in that case size OK (must insert here)
  151. else
  152. {
  153. if (box.min_.x_ <= worldBoundingBox_.min_.x_ - 0.5f * halfSize_.x_ ||
  154. box.max_.x_ >= worldBoundingBox_.max_.x_ + 0.5f * halfSize_.x_ ||
  155. box.min_.y_ <= worldBoundingBox_.min_.y_ - 0.5f * halfSize_.y_ ||
  156. box.max_.y_ >= worldBoundingBox_.max_.y_ + 0.5f * halfSize_.y_ ||
  157. box.min_.z_ <= worldBoundingBox_.min_.z_ - 0.5f * halfSize_.z_ ||
  158. box.max_.z_ >= worldBoundingBox_.max_.z_ + 0.5f * halfSize_.z_)
  159. return true;
  160. }
  161. // Bounding box too small, should create a child octant
  162. return false;
  163. }
  164. void Octant::ResetRoot()
  165. {
  166. root_ = nullptr;
  167. // The whole octree is being destroyed, just detach the drawables
  168. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  169. (*i)->SetOctant(nullptr);
  170. for (auto& child : children_)
  171. {
  172. if (child)
  173. child->ResetRoot();
  174. }
  175. }
  176. void Octant::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  177. {
  178. if (debug && debug->IsInside(worldBoundingBox_))
  179. {
  180. debug->AddBoundingBox(worldBoundingBox_, Color(0.25f, 0.25f, 0.25f), depthTest);
  181. for (auto& child : children_)
  182. {
  183. if (child)
  184. child->DrawDebugGeometry(debug, depthTest);
  185. }
  186. }
  187. }
  188. void Octant::Initialize(const BoundingBox& box)
  189. {
  190. worldBoundingBox_ = box;
  191. center_ = box.Center();
  192. halfSize_ = 0.5f * box.Size();
  193. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize_, worldBoundingBox_.max_ + halfSize_);
  194. }
  195. void Octant::GetDrawablesInternal(OctreeQuery& query, bool inside) const
  196. {
  197. if (this != root_)
  198. {
  199. Intersection res = query.TestOctant(cullingBox_, inside);
  200. if (res == INSIDE)
  201. inside = true;
  202. else if (res == OUTSIDE)
  203. {
  204. // Fully outside, so cull this octant, its children & drawables
  205. return;
  206. }
  207. }
  208. if (drawables_.Size())
  209. {
  210. auto** start = const_cast<Drawable**>(&drawables_[0]);
  211. Drawable** end = start + drawables_.Size();
  212. query.TestDrawables(start, end, inside);
  213. }
  214. for (auto child : children_)
  215. {
  216. if (child)
  217. child->GetDrawablesInternal(query, inside);
  218. }
  219. }
  220. void Octant::GetDrawablesInternal(RayOctreeQuery& query) const
  221. {
  222. float octantDist = query.ray_.HitDistance(cullingBox_);
  223. if (octantDist >= query.maxDistance_)
  224. return;
  225. if (drawables_.Size())
  226. {
  227. auto** start = const_cast<Drawable**>(&drawables_[0]);
  228. Drawable** end = start + drawables_.Size();
  229. while (start != end)
  230. {
  231. Drawable* drawable = *start++;
  232. if ((drawable->GetDrawableFlags() & query.drawableFlags_) && (drawable->GetViewMask() & query.viewMask_))
  233. drawable->ProcessRayQuery(query, query.result_);
  234. }
  235. }
  236. for (auto child : children_)
  237. {
  238. if (child)
  239. child->GetDrawablesInternal(query);
  240. }
  241. }
  242. void Octant::GetDrawablesOnlyInternal(RayOctreeQuery& query, PODVector<Drawable*>& drawables) const
  243. {
  244. float octantDist = query.ray_.HitDistance(cullingBox_);
  245. if (octantDist >= query.maxDistance_)
  246. return;
  247. if (drawables_.Size())
  248. {
  249. auto** start = const_cast<Drawable**>(&drawables_[0]);
  250. Drawable** end = start + drawables_.Size();
  251. while (start != end)
  252. {
  253. Drawable* drawable = *start++;
  254. if ((drawable->GetDrawableFlags() & query.drawableFlags_) && (drawable->GetViewMask() & query.viewMask_))
  255. drawables.Push(drawable);
  256. }
  257. }
  258. for (auto child : children_)
  259. {
  260. if (child)
  261. child->GetDrawablesOnlyInternal(query, drawables);
  262. }
  263. }
  264. Octree::Octree(Context* context) :
  265. Component(context),
  266. Octant(BoundingBox(-DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE), 0, nullptr, this),
  267. numLevels_(DEFAULT_OCTREE_LEVELS)
  268. {
  269. // If the engine is running headless, subscribe to RenderUpdate events for manually updating the octree
  270. // to allow raycasts and animation update
  271. if (!GetSubsystem<Graphics>())
  272. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(Octree, HandleRenderUpdate));
  273. }
  274. Octree::~Octree()
  275. {
  276. // Reset root pointer from all child octants now so that they do not move their drawables to root
  277. drawableUpdates_.Clear();
  278. ResetRoot();
  279. }
  280. void Octree::RegisterObject(Context* context)
  281. {
  282. context->RegisterFactory<Octree>(SUBSYSTEM_CATEGORY);
  283. Vector3 defaultBoundsMin = -Vector3::ONE * DEFAULT_OCTREE_SIZE;
  284. Vector3 defaultBoundsMax = Vector3::ONE * DEFAULT_OCTREE_SIZE;
  285. URHO3D_ATTRIBUTE_EX("Bounding Box Min", Vector3, worldBoundingBox_.min_, UpdateOctreeSize, defaultBoundsMin, AM_DEFAULT);
  286. URHO3D_ATTRIBUTE_EX("Bounding Box Max", Vector3, worldBoundingBox_.max_, UpdateOctreeSize, defaultBoundsMax, AM_DEFAULT);
  287. URHO3D_ATTRIBUTE_EX("Number of Levels", int, numLevels_, UpdateOctreeSize, DEFAULT_OCTREE_LEVELS, AM_DEFAULT);
  288. }
  289. void Octree::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  290. {
  291. if (debug)
  292. {
  293. URHO3D_PROFILE(OctreeDrawDebug);
  294. Octant::DrawDebugGeometry(debug, depthTest);
  295. }
  296. }
  297. void Octree::SetSize(const BoundingBox& box, unsigned numLevels)
  298. {
  299. URHO3D_PROFILE(ResizeOctree);
  300. // If drawables exist, they are temporarily moved to the root
  301. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  302. DeleteChild(i);
  303. Initialize(box);
  304. numDrawables_ = drawables_.Size();
  305. numLevels_ = Max(numLevels, 1U);
  306. }
  307. void Octree::Update(const FrameInfo& frame)
  308. {
  309. if (!Thread::IsMainThread())
  310. {
  311. URHO3D_LOGERROR("Octree::Update() can not be called from worker threads");
  312. return;
  313. }
  314. // Let drawables update themselves before reinsertion. This can be used for animation
  315. if (!drawableUpdates_.Empty())
  316. {
  317. URHO3D_PROFILE(UpdateDrawables);
  318. // Perform updates in worker threads. Notify the scene that a threaded update is going on and components
  319. // (for example physics objects) should not perform non-threadsafe work when marked dirty
  320. Scene* scene = GetScene();
  321. auto* queue = GetSubsystem<WorkQueue>();
  322. scene->BeginThreadedUpdate();
  323. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  324. int drawablesPerItem = Max((int)(drawableUpdates_.Size() / numWorkItems), 1);
  325. PODVector<Drawable*>::Iterator start = drawableUpdates_.Begin();
  326. // Create a work item for each thread
  327. for (int i = 0; i < numWorkItems; ++i)
  328. {
  329. SharedPtr<WorkItem> item = queue->GetFreeItem();
  330. item->priority_ = M_MAX_UNSIGNED;
  331. item->workFunction_ = UpdateDrawablesWork;
  332. item->aux_ = const_cast<FrameInfo*>(&frame);
  333. PODVector<Drawable*>::Iterator end = drawableUpdates_.End();
  334. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  335. end = start + drawablesPerItem;
  336. item->start_ = &(*start);
  337. item->end_ = &(*end);
  338. queue->AddWorkItem(item);
  339. start = end;
  340. }
  341. queue->Complete(M_MAX_UNSIGNED);
  342. scene->EndThreadedUpdate();
  343. }
  344. // If any drawables were inserted during threaded update, update them now from the main thread
  345. if (!threadedDrawableUpdates_.Empty())
  346. {
  347. URHO3D_PROFILE(UpdateDrawablesQueuedDuringUpdate);
  348. for (PODVector<Drawable*>::ConstIterator i = threadedDrawableUpdates_.Begin(); i != threadedDrawableUpdates_.End(); ++i)
  349. {
  350. Drawable* drawable = *i;
  351. if (drawable)
  352. {
  353. drawable->Update(frame);
  354. drawableUpdates_.Push(drawable);
  355. }
  356. }
  357. threadedDrawableUpdates_.Clear();
  358. }
  359. // Notify drawable update being finished. Custom animation (eg. IK) can be done at this point
  360. Scene* scene = GetScene();
  361. if (scene)
  362. {
  363. using namespace SceneDrawableUpdateFinished;
  364. VariantMap& eventData = GetEventDataMap();
  365. eventData[P_SCENE] = scene;
  366. eventData[P_TIMESTEP] = frame.timeStep_;
  367. scene->SendEvent(E_SCENEDRAWABLEUPDATEFINISHED, eventData);
  368. }
  369. // Reinsert drawables that have been moved or resized, or that have been newly added to the octree and do not sit inside
  370. // the proper octant yet
  371. if (!drawableUpdates_.Empty())
  372. {
  373. URHO3D_PROFILE(ReinsertToOctree);
  374. for (PODVector<Drawable*>::Iterator i = drawableUpdates_.Begin(); i != drawableUpdates_.End(); ++i)
  375. {
  376. Drawable* drawable = *i;
  377. drawable->updateQueued_ = false;
  378. Octant* octant = drawable->GetOctant();
  379. const BoundingBox& box = drawable->GetWorldBoundingBox();
  380. // Skip if no octant or does not belong to this octree anymore
  381. if (!octant || octant->GetRoot() != this)
  382. continue;
  383. // Skip if still fits the current octant
  384. if (drawable->IsOccludee() && octant->GetCullingBox().IsInside(box) == INSIDE && octant->CheckDrawableFit(box))
  385. continue;
  386. InsertDrawable(drawable);
  387. #ifdef _DEBUG
  388. // Verify that the drawable will be culled correctly
  389. octant = drawable->GetOctant();
  390. if (octant != this && octant->GetCullingBox().IsInside(box) != INSIDE)
  391. {
  392. URHO3D_LOGERROR("Drawable is not fully inside its octant's culling bounds: drawable box " + box.ToString() +
  393. " octant box " + octant->GetCullingBox().ToString());
  394. }
  395. #endif
  396. }
  397. }
  398. drawableUpdates_.Clear();
  399. }
  400. void Octree::AddManualDrawable(Drawable* drawable)
  401. {
  402. if (!drawable || drawable->GetOctant())
  403. return;
  404. AddDrawable(drawable);
  405. }
  406. void Octree::RemoveManualDrawable(Drawable* drawable)
  407. {
  408. if (!drawable)
  409. return;
  410. Octant* octant = drawable->GetOctant();
  411. if (octant && octant->GetRoot() == this)
  412. octant->RemoveDrawable(drawable);
  413. }
  414. void Octree::GetDrawables(OctreeQuery& query) const
  415. {
  416. query.result_.Clear();
  417. GetDrawablesInternal(query, false);
  418. }
  419. void Octree::Raycast(RayOctreeQuery& query) const
  420. {
  421. URHO3D_PROFILE(Raycast);
  422. query.result_.Clear();
  423. GetDrawablesInternal(query);
  424. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  425. }
  426. void Octree::RaycastSingle(RayOctreeQuery& query) const
  427. {
  428. URHO3D_PROFILE(Raycast);
  429. query.result_.Clear();
  430. rayQueryDrawables_.Clear();
  431. GetDrawablesOnlyInternal(query, rayQueryDrawables_);
  432. // Sort by increasing hit distance to AABB
  433. for (PODVector<Drawable*>::Iterator i = rayQueryDrawables_.Begin(); i != rayQueryDrawables_.End(); ++i)
  434. {
  435. Drawable* drawable = *i;
  436. drawable->SetSortValue(query.ray_.HitDistance(drawable->GetWorldBoundingBox()));
  437. }
  438. Sort(rayQueryDrawables_.Begin(), rayQueryDrawables_.End(), CompareDrawables);
  439. // Then do the actual test according to the query, and early-out as possible
  440. float closestHit = M_INFINITY;
  441. for (PODVector<Drawable*>::Iterator i = rayQueryDrawables_.Begin(); i != rayQueryDrawables_.End(); ++i)
  442. {
  443. Drawable* drawable = *i;
  444. if (drawable->GetSortValue() < Min(closestHit, query.maxDistance_))
  445. {
  446. unsigned oldSize = query.result_.Size();
  447. drawable->ProcessRayQuery(query, query.result_);
  448. if (query.result_.Size() > oldSize)
  449. closestHit = Min(closestHit, query.result_.Back().distance_);
  450. }
  451. else
  452. break;
  453. }
  454. if (query.result_.Size() > 1)
  455. {
  456. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  457. query.result_.Resize(1);
  458. }
  459. }
  460. void Octree::QueueUpdate(Drawable* drawable)
  461. {
  462. Scene* scene = GetScene();
  463. if (scene && scene->IsThreadedUpdate())
  464. {
  465. MutexLock lock(octreeMutex_);
  466. threadedDrawableUpdates_.Push(drawable);
  467. }
  468. else
  469. drawableUpdates_.Push(drawable);
  470. drawable->updateQueued_ = true;
  471. }
  472. void Octree::CancelUpdate(Drawable* drawable)
  473. {
  474. // This doesn't have to take into account scene being in threaded update, because it is called only
  475. // when removing a drawable from octree, which should only ever happen from the main thread.
  476. drawableUpdates_.Remove(drawable);
  477. drawable->updateQueued_ = false;
  478. }
  479. void Octree::DrawDebugGeometry(bool depthTest)
  480. {
  481. auto* debug = GetComponent<DebugRenderer>();
  482. DrawDebugGeometry(debug, depthTest);
  483. }
  484. void Octree::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  485. {
  486. // When running in headless mode, update the Octree manually during the RenderUpdate event
  487. Scene* scene = GetScene();
  488. if (!scene || !scene->IsUpdateEnabled())
  489. return;
  490. using namespace RenderUpdate;
  491. FrameInfo frame;
  492. frame.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  493. frame.timeStep_ = eventData[P_TIMESTEP].GetFloat();
  494. frame.camera_ = nullptr;
  495. Update(frame);
  496. }
  497. }