Octree.cpp 21 KB

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