Sector.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. // Copyright (C) 2009-2016, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <anki/scene/Sector.h>
  6. #include <anki/scene/SpatialComponent.h>
  7. #include <anki/scene/FrustumComponent.h>
  8. #include <anki/scene/MoveComponent.h>
  9. #include <anki/scene/SceneGraph.h>
  10. #include <anki/scene/SoftwareRasterizer.h>
  11. #include <anki/util/Logger.h>
  12. #include <anki/resource/ResourceManager.h>
  13. #include <anki/resource/MeshLoader.h>
  14. #include <anki/renderer/Renderer.h>
  15. namespace anki
  16. {
  17. //==============================================================================
  18. // Misc =
  19. //==============================================================================
  20. //==============================================================================
  21. template<typename TFunc>
  22. static void iterateSceneSectors(SceneGraph& scene, TFunc func)
  23. {
  24. scene.getSceneComponentLists().iterateComponents<SectorComponent>(
  25. [&](SectorComponent& comp) {
  26. Sector& s = static_cast<Sector&>(comp.getSceneNode());
  27. if(func(s))
  28. {
  29. return;
  30. }
  31. });
  32. }
  33. //==============================================================================
  34. template<typename TFunc>
  35. static void iterateScenePortals(SceneGraph& scene, TFunc func)
  36. {
  37. scene.getSceneComponentLists().iterateComponents<PortalComponent>(
  38. [&](PortalComponent& comp) {
  39. Portal& s = static_cast<Portal&>(comp.getSceneNode());
  40. if(func(s))
  41. {
  42. return;
  43. }
  44. });
  45. }
  46. //==============================================================================
  47. // PortalSectorBase =
  48. //==============================================================================
  49. //==============================================================================
  50. PortalSectorBase::~PortalSectorBase()
  51. {
  52. auto alloc = getSceneAllocator();
  53. if(m_shape)
  54. {
  55. alloc.deleteInstance(m_shape);
  56. m_shape = nullptr;
  57. }
  58. m_shapeStorageLSpace.destroy(alloc);
  59. m_shapeStorageWSpace.destroy(alloc);
  60. m_vertIndices.destroy(alloc);
  61. }
  62. //==============================================================================
  63. Error PortalSectorBase::init(
  64. const CString& name, const CString& meshFname, Bool isSector)
  65. {
  66. ANKI_CHECK(SceneNode::init(name));
  67. // Create move component
  68. SceneComponent* comp = getSceneAllocator().newInstance<MoveComponent>(this);
  69. addComponent(comp, true);
  70. // Create portal or sector component
  71. if(isSector)
  72. {
  73. comp = getSceneAllocator().newInstance<SectorComponent>(this);
  74. }
  75. else
  76. {
  77. comp = getSceneAllocator().newInstance<PortalComponent>(this);
  78. }
  79. addComponent(comp, true);
  80. // Load mesh
  81. MeshLoader loader(&getSceneGraph()._getResourceManager());
  82. ANKI_CHECK(loader.load(meshFname));
  83. // Convert Vec3 positions to Vec4
  84. const MeshLoader::Header& header = loader.getHeader();
  85. U vertsCount = header.m_totalVerticesCount;
  86. PtrSize vertSize = loader.getVertexSize();
  87. auto alloc = getSceneAllocator();
  88. m_shapeStorageLSpace.create(alloc, vertsCount);
  89. m_shapeStorageWSpace.create(alloc, vertsCount);
  90. for(U i = 0; i < vertsCount; ++i)
  91. {
  92. const Vec3& pos = *reinterpret_cast<const Vec3*>(
  93. loader.getVertexData() + vertSize * i);
  94. m_shapeStorageLSpace[i] = Vec4(pos, 0.0);
  95. }
  96. // Create shape
  97. ConvexHullShape* hull = alloc.newInstance<ConvexHullShape>();
  98. m_shape = hull;
  99. hull->initStorage(&m_shapeStorageWSpace[0], vertsCount);
  100. updateTransform(Transform::getIdentity());
  101. // Store indices
  102. ANKI_ASSERT(
  103. header.m_totalIndicesCount * sizeof(U16) == loader.getIndexDataSize());
  104. m_vertIndices.create(alloc, header.m_totalIndicesCount);
  105. const U16* indicesIn = reinterpret_cast<const U16*>(loader.getIndexData());
  106. for(U i = 0; i < header.m_totalIndicesCount; ++i)
  107. {
  108. m_vertIndices[i] = indicesIn[i];
  109. }
  110. return ErrorCode::NONE;
  111. }
  112. //==============================================================================
  113. void PortalSectorBase::updateTransform(const Transform& trf)
  114. {
  115. const U count = m_shapeStorageWSpace.getSize();
  116. for(U i = 0; i < count; ++i)
  117. {
  118. m_shapeStorageWSpace[i] = trf.transform(m_shapeStorageLSpace[i]);
  119. }
  120. m_shape->computeAabb(m_aabb);
  121. }
  122. //==============================================================================
  123. // Portal =
  124. //==============================================================================
  125. //==============================================================================
  126. Portal::~Portal()
  127. {
  128. auto alloc = getSceneAllocator();
  129. // Remove from sectors
  130. for(Sector* s : m_sectors)
  131. {
  132. s->tryRemovePortal(this);
  133. }
  134. m_sectors.destroy(getSceneAllocator());
  135. }
  136. //==============================================================================
  137. Error Portal::init(const CString& name, const CString& meshFname)
  138. {
  139. ANKI_CHECK(Base::init(name, meshFname, false));
  140. return ErrorCode::NONE;
  141. }
  142. //==============================================================================
  143. Error Portal::frameUpdate(F32 prevUpdateTime, F32 crntTime)
  144. {
  145. MoveComponent& move = getComponent<MoveComponent>();
  146. if(move.getTimestamp() == getGlobalTimestamp())
  147. {
  148. // Move comp updated
  149. updateTransform(move.getWorldTransform());
  150. getSceneGraph().getSectorGroup().portalUpdated(this);
  151. }
  152. return ErrorCode::NONE;
  153. }
  154. //==============================================================================
  155. void Portal::deferredUpdate()
  156. {
  157. // Gather the sectors it collides
  158. iterateSceneSectors(getSceneGraph(), [&](Sector& sector) -> Bool {
  159. Bool collide = testCollisionShapes(m_aabb, sector.m_aabb);
  160. // Perform a more detailed test
  161. if(collide)
  162. {
  163. collide = testCollisionShapes(*m_shape, sector.getBoundingShape());
  164. }
  165. // Update graphs
  166. if(collide)
  167. {
  168. tryAddSector(&sector);
  169. sector.tryAddPortal(this);
  170. }
  171. else
  172. {
  173. tryRemoveSector(&sector);
  174. sector.tryRemovePortal(this);
  175. }
  176. return false;
  177. });
  178. }
  179. //==============================================================================
  180. void Portal::tryAddSector(Sector* sector)
  181. {
  182. ANKI_ASSERT(sector);
  183. auto it = m_sectors.getBegin();
  184. auto end = m_sectors.getEnd();
  185. for(; it != end; ++it)
  186. {
  187. if(*it == sector)
  188. {
  189. // Already there, return
  190. return;
  191. }
  192. }
  193. m_sectors.pushBack(getSceneAllocator(), sector);
  194. }
  195. //==============================================================================
  196. void Portal::tryRemoveSector(Sector* sector)
  197. {
  198. ANKI_ASSERT(sector);
  199. auto it = m_sectors.getBegin();
  200. auto end = m_sectors.getEnd();
  201. for(; it != end; ++it)
  202. {
  203. if(*it == sector)
  204. {
  205. m_sectors.erase(getSceneAllocator(), it);
  206. break;
  207. }
  208. }
  209. }
  210. //==============================================================================
  211. // Sector =
  212. //==============================================================================
  213. //==============================================================================
  214. Sector::~Sector()
  215. {
  216. auto alloc = getSceneAllocator();
  217. // Remove portals
  218. for(Portal* p : m_portals)
  219. {
  220. p->tryRemoveSector(this);
  221. }
  222. m_portals.destroy(alloc);
  223. // Remove spatials
  224. U spatialsCount = m_spatials.getSize();
  225. while(spatialsCount-- != 0) // Use counter
  226. {
  227. tryRemoveSpatialComponent(m_spatials.getFront());
  228. }
  229. }
  230. //==============================================================================
  231. Error Sector::init(const CString& name, const CString& meshFname)
  232. {
  233. ANKI_CHECK(PortalSectorBase::init(name, meshFname, true));
  234. return ErrorCode::NONE;
  235. }
  236. //==============================================================================
  237. void Sector::tryAddPortal(Portal* portal)
  238. {
  239. ANKI_ASSERT(portal);
  240. auto it = m_portals.getBegin();
  241. auto end = m_portals.getEnd();
  242. for(; it != end; ++it)
  243. {
  244. if(*it == portal)
  245. {
  246. // Already there, return
  247. return;
  248. }
  249. }
  250. m_portals.pushBack(getSceneAllocator(), portal);
  251. }
  252. //==============================================================================
  253. void Sector::tryRemovePortal(Portal* portal)
  254. {
  255. ANKI_ASSERT(portal);
  256. auto it = m_portals.getBegin();
  257. auto end = m_portals.getEnd();
  258. for(; it != end; ++it)
  259. {
  260. if(*it == portal)
  261. {
  262. m_portals.erase(getSceneAllocator(), it);
  263. break;
  264. }
  265. }
  266. }
  267. //==============================================================================
  268. void Sector::tryAddSpatialComponent(SpatialComponent* sp)
  269. {
  270. ANKI_ASSERT(sp);
  271. // Find sector in spatial
  272. auto itsp = sp->getSectorInfo().getBegin();
  273. auto endsp = sp->getSectorInfo().getEnd();
  274. for(; itsp != endsp; ++itsp)
  275. {
  276. if(*itsp == this)
  277. {
  278. // Found, return
  279. ANKI_ASSERT(findSpatialComponent(sp) != m_spatials.getEnd()
  280. && "Spatial has reference to sector but sector not");
  281. return;
  282. }
  283. }
  284. ANKI_ASSERT(findSpatialComponent(sp) == m_spatials.getEnd());
  285. m_spatials.pushBack(getSceneAllocator(), sp);
  286. sp->getSectorInfo().pushBack(getSceneAllocator(), this);
  287. }
  288. //==============================================================================
  289. void Sector::tryRemoveSpatialComponent(SpatialComponent* sp)
  290. {
  291. ANKI_ASSERT(sp);
  292. // Find sector in spatial
  293. auto itsp = sp->getSectorInfo().getBegin();
  294. auto endsp = sp->getSectorInfo().getEnd();
  295. for(; itsp != endsp; ++itsp)
  296. {
  297. if(*itsp == this)
  298. {
  299. break;
  300. }
  301. }
  302. if(itsp != endsp)
  303. {
  304. // Found, remove
  305. sp->getSectorInfo().erase(getSceneAllocator(), itsp);
  306. auto it = findSpatialComponent(sp);
  307. ANKI_ASSERT(it != m_spatials.getEnd());
  308. m_spatials.erase(getSceneAllocator(), it);
  309. }
  310. else
  311. {
  312. #if ANKI_ASSERTIONS
  313. ANKI_ASSERT(findSpatialComponent(sp) == m_spatials.getEnd());
  314. #endif
  315. }
  316. }
  317. //==============================================================================
  318. List<SpatialComponent*>::Iterator Sector::findSpatialComponent(
  319. SpatialComponent* sp)
  320. {
  321. ANKI_ASSERT(sp);
  322. auto it = m_spatials.getBegin();
  323. auto end = m_spatials.getEnd();
  324. for(; it != end; ++it)
  325. {
  326. if(*it == sp)
  327. {
  328. break;
  329. }
  330. }
  331. return it;
  332. }
  333. //==============================================================================
  334. Error Sector::frameUpdate(F32 prevUpdateTime, F32 crntTime)
  335. {
  336. MoveComponent& move = getComponent<MoveComponent>();
  337. if(move.getTimestamp() == getGlobalTimestamp())
  338. {
  339. // Move comp updated.
  340. updateTransform(move.getWorldTransform());
  341. getSceneGraph().getSectorGroup().sectorUpdated(this);
  342. }
  343. return ErrorCode::NONE;
  344. }
  345. //==============================================================================
  346. void Sector::deferredUpdate()
  347. {
  348. // Spatials should get updated
  349. for(SpatialComponent* sp : m_spatials)
  350. {
  351. sp->markForUpdate();
  352. }
  353. iterateScenePortals(getSceneGraph(), [&](Portal& portal) -> Bool {
  354. Bool collide = testCollisionShapes(m_aabb, portal.m_aabb);
  355. if(collide)
  356. {
  357. collide = testCollisionShapes(*m_shape, portal.getBoundingShape());
  358. }
  359. if(collide)
  360. {
  361. portal.tryAddSector(this);
  362. tryAddPortal(&portal);
  363. }
  364. else
  365. {
  366. portal.tryRemoveSector(this);
  367. tryRemovePortal(&portal);
  368. }
  369. return false;
  370. });
  371. }
  372. //==============================================================================
  373. // SectorGroup =
  374. //==============================================================================
  375. //==============================================================================
  376. SectorGroup::~SectorGroup()
  377. {
  378. }
  379. //==============================================================================
  380. void SectorGroup::spatialUpdated(SpatialComponent* sp)
  381. {
  382. ANKI_ASSERT(sp);
  383. LockGuard<SpinLock> lock(m_mtx);
  384. m_spatialsDeferredBinning.pushBack(m_scene->getFrameAllocator(), sp);
  385. }
  386. //==============================================================================
  387. void SectorGroup::portalUpdated(Portal* portal)
  388. {
  389. ANKI_ASSERT(portal);
  390. LockGuard<SpinLock> lock(m_portalsUpdatedLock);
  391. m_portalsUpdated.pushBack(m_scene->getFrameAllocator(), portal);
  392. }
  393. //==============================================================================
  394. void SectorGroup::sectorUpdated(Sector* sector)
  395. {
  396. ANKI_ASSERT(sector);
  397. LockGuard<SpinLock> lock(m_sectorsUpdatedLock);
  398. m_sectorsUpdated.pushBack(m_scene->getFrameAllocator(), sector);
  399. }
  400. //==============================================================================
  401. void SectorGroup::binSpatial(SpatialComponent* sp)
  402. {
  403. ANKI_ASSERT(sp);
  404. // Iterate all sectors and bin the spatial
  405. iterateSceneSectors(*m_scene, [&](Sector& sector) -> Bool {
  406. Bool collide = false;
  407. if(!sp->getSingleSector())
  408. {
  409. // Spatial can belong to multiple sectors
  410. // Fast test
  411. collide = testCollisionShapes(sector.m_aabb, sp->getAabb());
  412. // Detailed test
  413. if(collide)
  414. {
  415. collide = testCollisionShapes(
  416. sector.getBoundingShape(), sp->getSpatialCollisionShape());
  417. }
  418. }
  419. else
  420. {
  421. // Spatial can belong to one sector
  422. // Make sure the origin of the spatial is inside the sector
  423. const Vec4& center = sp->getSpatialOrigin();
  424. if(center >= sector.m_aabb.getMin()
  425. && center <= sector.m_aabb.getMax())
  426. {
  427. collide = true;
  428. }
  429. // Detailed test
  430. const F32 smallf = getEpsilon<F32>() * 10.0;
  431. Aabb smallBox(center, center + Vec4(smallf, smallf, smallf, 0.0));
  432. if(collide)
  433. {
  434. collide =
  435. testCollisionShapes(sector.getBoundingShape(), smallBox);
  436. }
  437. }
  438. if(collide)
  439. {
  440. sector.tryAddSpatialComponent(sp);
  441. }
  442. else
  443. {
  444. sector.tryRemoveSpatialComponent(sp);
  445. }
  446. return false;
  447. });
  448. }
  449. //==============================================================================
  450. void SectorGroup::spatialDeleted(SpatialComponent* sp)
  451. {
  452. auto it = sp->getSectorInfo().getBegin();
  453. auto end = sp->getSectorInfo().getEnd();
  454. while(it != end)
  455. {
  456. (*it)->tryRemoveSpatialComponent(sp);
  457. ++it;
  458. }
  459. }
  460. //==============================================================================
  461. void SectorGroup::findVisibleSectors(const FrustumComponent& frc,
  462. const SoftwareRasterizer* r,
  463. List<const Sector*>& visibleSectors,
  464. U& spatialsCount) const
  465. {
  466. // Find the sector the eye is in
  467. Sphere eye(frc.getFrustumOrigin(), frc.getFrustum().getNear());
  468. Bool eyeInsideASector = false;
  469. Sector* sectorEyeIsInside = nullptr;
  470. iterateSceneSectors(*m_scene, [&](Sector& sector) -> Bool {
  471. Bool collide = testCollisionShapes(eye, sector.m_aabb);
  472. if(collide)
  473. {
  474. collide = testCollisionShapes(eye, sector.getBoundingShape());
  475. }
  476. if(collide)
  477. {
  478. eyeInsideASector = true;
  479. sectorEyeIsInside = &sector;
  480. return true;
  481. }
  482. return false;
  483. });
  484. if(!eyeInsideASector)
  485. {
  486. // eye outside all sectors, find those the frustum collides
  487. iterateSceneSectors(*m_scene, [&](Sector& sector) -> Bool {
  488. if(frc.insideFrustum(sector.getBoundingShape()))
  489. {
  490. findVisibleSectorsInternal(
  491. frc, sector, r, visibleSectors, spatialsCount);
  492. }
  493. return false;
  494. });
  495. }
  496. else
  497. {
  498. // eye inside a sector
  499. findVisibleSectorsInternal(
  500. frc, *sectorEyeIsInside, r, visibleSectors, spatialsCount);
  501. }
  502. }
  503. //==============================================================================
  504. void SectorGroup::findVisibleSectorsInternal(const FrustumComponent& frc,
  505. const Sector& s,
  506. const SoftwareRasterizer* r,
  507. List<const Sector*>& visibleSectors,
  508. U& spatialsCount) const
  509. {
  510. auto alloc = m_scene->getFrameAllocator();
  511. // Check if "s" is already there
  512. auto it = visibleSectors.getBegin();
  513. auto end = visibleSectors.getEnd();
  514. for(; it != end; ++it)
  515. {
  516. if(*it == &s)
  517. {
  518. // Sector already there, skip
  519. return;
  520. }
  521. }
  522. // Sector not in the list, push it
  523. visibleSectors.pushBack(alloc, &s);
  524. spatialsCount += s.m_spatials.getSize();
  525. // Check visible portals
  526. auto itp = s.m_portals.getBegin();
  527. auto itend = s.m_portals.getEnd();
  528. for(; itp != itend; ++itp)
  529. {
  530. const Portal& p = *(*itp);
  531. if(frc.insideFrustum(p.getBoundingShape())
  532. && (r == nullptr
  533. || r->visibilityTest(p.getBoundingShape(), p.m_aabb)))
  534. {
  535. auto it = p.m_sectors.getBegin();
  536. auto end = p.m_sectors.getEnd();
  537. for(; it != end; ++it)
  538. {
  539. if(*it != &s)
  540. {
  541. findVisibleSectorsInternal(
  542. frc, *(*it), r, visibleSectors, spatialsCount);
  543. }
  544. }
  545. }
  546. }
  547. }
  548. //==============================================================================
  549. void SectorGroup::prepareForVisibilityTests()
  550. {
  551. // Update portals
  552. Error err = m_portalsUpdated.iterateForward([](Portal* portal) {
  553. portal->deferredUpdate();
  554. return ErrorCode::NONE;
  555. });
  556. (void)err;
  557. m_portalsUpdated.destroy(m_scene->getFrameAllocator());
  558. // Update sectors
  559. err = m_sectorsUpdated.iterateForward([](Sector* portal) {
  560. portal->deferredUpdate();
  561. return ErrorCode::NONE;
  562. });
  563. (void)err;
  564. m_sectorsUpdated.destroy(m_scene->getFrameAllocator());
  565. // Bin spatials
  566. err =
  567. m_spatialsDeferredBinning.iterateForward([this](SpatialComponent* spc) {
  568. binSpatial(spc);
  569. return ErrorCode::NONE;
  570. });
  571. (void)err;
  572. m_spatialsDeferredBinning.destroy(m_scene->getFrameAllocator());
  573. }
  574. //==============================================================================
  575. void SectorGroup::findVisibleNodes(const FrustumComponent& frc,
  576. U testId,
  577. const SoftwareRasterizer* r,
  578. SectorGroupVisibilityTestsContext& ctx) const
  579. {
  580. auto alloc = m_scene->getFrameAllocator();
  581. // Find visible sectors
  582. ListAuto<const Sector*> visSectors(alloc);
  583. U spatialsCount = 0;
  584. findVisibleSectors(frc, r, visSectors, spatialsCount);
  585. if(ANKI_UNLIKELY(spatialsCount == 0))
  586. {
  587. return;
  588. }
  589. // Initiate storage of nodes
  590. SceneNode** visibleNodesMem = reinterpret_cast<SceneNode**>(
  591. alloc.allocate(spatialsCount * sizeof(void*)));
  592. WeakArray<SceneNode*> visibleNodes(visibleNodesMem, spatialsCount);
  593. // Iterate visible sectors and get the scene nodes. The array will contain
  594. // duplicates
  595. U nodesCount = 0;
  596. auto it = visSectors.getBegin();
  597. auto end = visSectors.getEnd();
  598. for(; it != end; ++it)
  599. {
  600. const Sector& s = *(*it);
  601. for(auto itsp : s.m_spatials)
  602. {
  603. const SpatialComponent& spc = *itsp;
  604. SceneNode& node = const_cast<SceneNode&>(spc.getSceneNode());
  605. // Check if alrady visited
  606. if(!node.fetchSetSectorVisited(testId, true))
  607. {
  608. visibleNodes[nodesCount++] = &node;
  609. }
  610. }
  611. }
  612. // Update the context
  613. ctx.m_visibleNodes = WeakArray<SceneNode*>(visibleNodesMem, nodesCount);
  614. }
  615. } // end namespace anki