Octree.cpp 21 KB

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