SceneGraph.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // Copyright (C) 2009-2021, 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/SceneGraph.h>
  6. #include <AnKi/Scene/CameraNode.h>
  7. #include <AnKi/Scene/PhysicsDebugNode.h>
  8. #include <AnKi/Scene/ModelNode.h>
  9. #include <AnKi/Scene/Octree.h>
  10. #include <AnKi/Scene/Components/FrustumComponent.h>
  11. #include <AnKi/Physics/PhysicsWorld.h>
  12. #include <AnKi/Resource/ResourceManager.h>
  13. #include <AnKi/Renderer/MainRenderer.h>
  14. #include <AnKi/Core/ConfigSet.h>
  15. #include <AnKi/Util/ThreadHive.h>
  16. #include <AnKi/Util/Tracer.h>
  17. #include <AnKi/Util/HighRezTimer.h>
  18. namespace anki {
  19. const U NODE_UPDATE_BATCH = 10;
  20. class SceneGraph::UpdateSceneNodesCtx
  21. {
  22. public:
  23. SceneGraph* m_scene = nullptr;
  24. IntrusiveList<SceneNode>::Iterator m_crntNode;
  25. SpinLock m_crntNodeLock;
  26. Second m_prevUpdateTime;
  27. Second m_crntTime;
  28. };
  29. SceneGraph::SceneGraph()
  30. {
  31. }
  32. SceneGraph::~SceneGraph()
  33. {
  34. Error err = iterateSceneNodes([&](SceneNode& s) -> Error {
  35. s.setMarkedForDeletion();
  36. return Error::NONE;
  37. });
  38. (void)err;
  39. deleteNodesMarkedForDeletion();
  40. if(m_octree)
  41. {
  42. m_alloc.deleteInstance(m_octree);
  43. }
  44. }
  45. Error SceneGraph::init(AllocAlignedCallback allocCb, void* allocCbData, ThreadHive* threadHive,
  46. ResourceManager* resources, Input* input, ScriptManager* scriptManager, UiManager* uiManager,
  47. const Timestamp* globalTimestamp, const ConfigSet& config)
  48. {
  49. m_globalTimestamp = globalTimestamp;
  50. m_threadHive = threadHive;
  51. m_resources = resources;
  52. m_gr = &m_resources->getGrManager();
  53. m_physics = &m_resources->getPhysicsWorld();
  54. m_input = input;
  55. m_scriptManager = scriptManager;
  56. m_uiManager = uiManager;
  57. m_alloc = SceneAllocator<U8>(allocCb, allocCbData);
  58. m_frameAlloc = SceneFrameAllocator<U8>(allocCb, allocCbData, 1 * 1024 * 1024);
  59. // Limits & stuff
  60. m_config.m_earlyZDistance = config.getNumberF32("scene_earlyZDistance");
  61. m_config.m_reflectionProbeEffectiveDistance = config.getNumberF32("scene_reflectionProbeEffectiveDistance");
  62. m_config.m_reflectionProbeShadowEffectiveDistance =
  63. config.getNumberF32("scene_reflectionProbeShadowEffectiveDistance");
  64. m_config.m_rayTracedShadows =
  65. config.getBool("scene_rayTracedShadows") && m_gr->getDeviceCapabilities().m_rayTracingEnabled;
  66. m_config.m_rayTracingExtendedFrustumDistance = config.getNumberF32("scene_rayTracingExtendedFrustumDistance");
  67. m_config.m_maxLodDistances[0] = config.getNumberF32("lod0MaxDistance");
  68. m_config.m_maxLodDistances[1] = config.getNumberF32("lod1MaxDistance");
  69. ANKI_CHECK(m_events.init(this));
  70. m_octree = m_alloc.newInstance<Octree>(m_alloc);
  71. m_octree->init(m_sceneMin, m_sceneMax, config.getNumberU32("scene_octreeMaxDepth"));
  72. // Init the default main camera
  73. ANKI_CHECK(newSceneNode<PerspectiveCameraNode>("mainCamera", m_defaultMainCam));
  74. m_defaultMainCam->getFirstComponentOfType<FrustumComponent>().setPerspective(0.1f, 1000.0f, toRad(60.0f),
  75. (1080.0f / 1920.0f) * toRad(60.0f));
  76. m_mainCam = m_defaultMainCam;
  77. // Create a special node for debugging the physics world
  78. PhysicsDebugNode* pnode;
  79. ANKI_CHECK(newSceneNode<PhysicsDebugNode>("_physicsDebugNode", pnode));
  80. // Other
  81. ANKI_CHECK(m_debugDrawer.init(&getResourceManager()));
  82. return Error::NONE;
  83. }
  84. Error SceneGraph::registerNode(SceneNode* node)
  85. {
  86. ANKI_ASSERT(node);
  87. // Add to dict if it has a name
  88. if(node->getName())
  89. {
  90. if(tryFindSceneNode(node->getName()))
  91. {
  92. ANKI_SCENE_LOGE("Node with the same name already exists");
  93. return Error::USER_DATA;
  94. }
  95. m_nodesDict.emplace(m_alloc, node->getName(), node);
  96. }
  97. // Add to vector
  98. m_nodes.pushBack(node);
  99. ++m_nodesCount;
  100. return Error::NONE;
  101. }
  102. void SceneGraph::unregisterNode(SceneNode* node)
  103. {
  104. // Remove from the graph
  105. m_nodes.erase(node);
  106. --m_nodesCount;
  107. if(m_mainCam != m_defaultMainCam && m_mainCam == node)
  108. {
  109. m_mainCam = m_defaultMainCam;
  110. }
  111. // Remove from dict
  112. if(node->getName())
  113. {
  114. auto it = m_nodesDict.find(node->getName());
  115. ANKI_ASSERT(it != m_nodesDict.getEnd());
  116. m_nodesDict.erase(m_alloc, it);
  117. }
  118. }
  119. SceneNode& SceneGraph::findSceneNode(const CString& name)
  120. {
  121. SceneNode* node = tryFindSceneNode(name);
  122. ANKI_ASSERT(node);
  123. return *node;
  124. }
  125. SceneNode* SceneGraph::tryFindSceneNode(const CString& name)
  126. {
  127. auto it = m_nodesDict.find(name);
  128. return (it == m_nodesDict.getEnd()) ? nullptr : (*it);
  129. }
  130. void SceneGraph::deleteNodesMarkedForDeletion()
  131. {
  132. /// Delete all nodes pending deletion. At this point all scene threads
  133. /// should have finished their tasks
  134. while(m_objectsMarkedForDeletionCount.load() > 0)
  135. {
  136. Bool found = false;
  137. auto it = m_nodes.begin();
  138. auto end = m_nodes.end();
  139. for(; it != end; ++it)
  140. {
  141. SceneNode& node = *it;
  142. if(node.getMarkedForDeletion())
  143. {
  144. // Delete node
  145. unregisterNode(&node);
  146. m_alloc.deleteInstance(&node);
  147. m_objectsMarkedForDeletionCount.fetchSub(1);
  148. found = true;
  149. break;
  150. }
  151. }
  152. (void)found;
  153. ANKI_ASSERT(found && "Something is wrong with marked for deletion");
  154. }
  155. }
  156. Error SceneGraph::update(Second prevUpdateTime, Second crntTime)
  157. {
  158. ANKI_ASSERT(m_mainCam);
  159. ANKI_TRACE_SCOPED_EVENT(SCENE_UPDATE);
  160. m_stats.m_updateTime = HighRezTimer::getCurrentTime();
  161. m_timestamp = *m_globalTimestamp;
  162. ANKI_ASSERT(m_timestamp > 0);
  163. // Reset the framepool
  164. m_frameAlloc.getMemoryPool().reset();
  165. // Delete stuff
  166. {
  167. ANKI_TRACE_SCOPED_EVENT(SCENE_MARKED_FOR_DELETION);
  168. const Bool fullCleanup = m_objectsMarkedForDeletionCount.load() != 0;
  169. m_events.deleteEventsMarkedForDeletion(fullCleanup);
  170. deleteNodesMarkedForDeletion();
  171. }
  172. // Update
  173. {
  174. ANKI_TRACE_SCOPED_EVENT(SCENE_PHYSICS_UPDATE);
  175. m_stats.m_physicsUpdate = HighRezTimer::getCurrentTime();
  176. m_physics->update(crntTime - prevUpdateTime);
  177. m_stats.m_physicsUpdate = HighRezTimer::getCurrentTime() - m_stats.m_physicsUpdate;
  178. }
  179. {
  180. ANKI_TRACE_SCOPED_EVENT(SCENE_NODES_UPDATE);
  181. ANKI_CHECK(m_events.updateAllEvents(prevUpdateTime, crntTime));
  182. // Then the rest
  183. Array<ThreadHiveTask, ThreadHive::MAX_THREADS> tasks;
  184. UpdateSceneNodesCtx updateCtx;
  185. updateCtx.m_scene = this;
  186. updateCtx.m_crntNode = m_nodes.getBegin();
  187. updateCtx.m_prevUpdateTime = prevUpdateTime;
  188. updateCtx.m_crntTime = crntTime;
  189. for(U i = 0; i < m_threadHive->getThreadCount(); i++)
  190. {
  191. tasks[i] = ANKI_THREAD_HIVE_TASK(
  192. {
  193. if(self->m_scene->updateNodes(*self))
  194. {
  195. ANKI_SCENE_LOGF("Will not recover");
  196. }
  197. },
  198. &updateCtx, nullptr, nullptr);
  199. }
  200. m_threadHive->submitTasks(&tasks[0], m_threadHive->getThreadCount());
  201. m_threadHive->waitAllTasks();
  202. }
  203. m_stats.m_updateTime = HighRezTimer::getCurrentTime() - m_stats.m_updateTime;
  204. return Error::NONE;
  205. }
  206. void SceneGraph::doVisibilityTests(RenderQueue& rqueue)
  207. {
  208. m_stats.m_visibilityTestsTime = HighRezTimer::getCurrentTime();
  209. doVisibilityTests(*m_mainCam, *this, rqueue);
  210. m_stats.m_visibilityTestsTime = HighRezTimer::getCurrentTime() - m_stats.m_visibilityTestsTime;
  211. }
  212. Error SceneGraph::updateNode(Second prevTime, Second crntTime, SceneNode& node)
  213. {
  214. ANKI_TRACE_INC_COUNTER(SCENE_NODES_UPDATED, 1);
  215. Error err = Error::NONE;
  216. // Components update
  217. Timestamp componentTimestamp = 0;
  218. Bool atLeastOneComponentUpdated = false;
  219. err = node.iterateComponents([&](SceneComponent& comp, Bool isFeedbackComponent) -> Error {
  220. Bool updated = false;
  221. Error e = Error::NONE;
  222. if(!atLeastOneComponentUpdated && isFeedbackComponent)
  223. {
  224. // Skip feedback component if prior components didn't got updated
  225. }
  226. else
  227. {
  228. e = comp.update(node, prevTime, crntTime, updated);
  229. }
  230. if(updated)
  231. {
  232. ANKI_TRACE_INC_COUNTER(SCENE_COMPONENTS_UPDATED, 1);
  233. comp.setTimestamp(node.getSceneGraph().m_timestamp);
  234. componentTimestamp = max(componentTimestamp, node.getSceneGraph().m_timestamp);
  235. ANKI_ASSERT(componentTimestamp > 0);
  236. atLeastOneComponentUpdated = true;
  237. }
  238. return e;
  239. });
  240. // Update children
  241. if(!err)
  242. {
  243. err = node.visitChildrenMaxDepth(0, [&](SceneNode& child) -> Error {
  244. return updateNode(prevTime, crntTime, child);
  245. });
  246. }
  247. // Frame update
  248. if(!err)
  249. {
  250. if(componentTimestamp != 0)
  251. {
  252. node.setComponentMaxTimestamp(componentTimestamp);
  253. }
  254. else
  255. {
  256. // No components or nothing updated, don't change the timestamp
  257. }
  258. err = node.frameUpdate(prevTime, crntTime);
  259. }
  260. return err;
  261. }
  262. Error SceneGraph::updateNodes(UpdateSceneNodesCtx& ctx) const
  263. {
  264. ANKI_TRACE_SCOPED_EVENT(SCENE_NODES_UPDATE);
  265. IntrusiveList<SceneNode>::ConstIterator end = m_nodes.getEnd();
  266. Bool quit = false;
  267. Error err = Error::NONE;
  268. while(!quit && !err)
  269. {
  270. // Fetch a batch of scene nodes that don't have parent
  271. Array<SceneNode*, NODE_UPDATE_BATCH> batch;
  272. U batchSize = 0;
  273. {
  274. LockGuard<SpinLock> lock(ctx.m_crntNodeLock);
  275. while(1)
  276. {
  277. if(batchSize == batch.getSize())
  278. {
  279. break;
  280. }
  281. if(ctx.m_crntNode == end)
  282. {
  283. quit = true;
  284. break;
  285. }
  286. SceneNode& node = *ctx.m_crntNode;
  287. if(node.getParent() == nullptr)
  288. {
  289. batch[batchSize++] = &node;
  290. }
  291. ++ctx.m_crntNode;
  292. }
  293. }
  294. // Process nodes
  295. for(U i = 0; i < batchSize && !err; ++i)
  296. {
  297. err = updateNode(ctx.m_prevUpdateTime, ctx.m_crntTime, *batch[i]);
  298. }
  299. }
  300. return err;
  301. }
  302. } // end namespace anki