Octree.cpp 17 KB

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