SceneGraph.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright (C) 2009-present, 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/RenderStateBucket.h>
  7. #include <AnKi/Physics/PhysicsWorld.h>
  8. #include <AnKi/Resource/ResourceManager.h>
  9. #include <AnKi/Util/CVarSet.h>
  10. #include <AnKi/Core/StatsSet.h>
  11. #include <AnKi/Util/Tracer.h>
  12. #include <AnKi/Util/HighRezTimer.h>
  13. #include <AnKi/Core/App.h>
  14. #include <AnKi/Scene/StatsUiNode.h>
  15. #include <AnKi/Scene/DeveloperConsoleUiNode.h>
  16. #include <AnKi/Scene/Components/BodyComponent.h>
  17. #include <AnKi/Scene/Components/CameraComponent.h>
  18. #include <AnKi/Scene/Components/DecalComponent.h>
  19. #include <AnKi/Scene/Components/FogDensityComponent.h>
  20. #include <AnKi/Scene/Components/GlobalIlluminationProbeComponent.h>
  21. #include <AnKi/Scene/Components/JointComponent.h>
  22. #include <AnKi/Scene/Components/LensFlareComponent.h>
  23. #include <AnKi/Scene/Components/LightComponent.h>
  24. #include <AnKi/Scene/Components/ModelComponent.h>
  25. #include <AnKi/Scene/Components/MoveComponent.h>
  26. #include <AnKi/Scene/Components/ParticleEmitterComponent.h>
  27. #include <AnKi/Scene/Components/PlayerControllerComponent.h>
  28. #include <AnKi/Scene/Components/ReflectionProbeComponent.h>
  29. #include <AnKi/Scene/Components/ScriptComponent.h>
  30. #include <AnKi/Scene/Components/SkinComponent.h>
  31. #include <AnKi/Scene/Components/SkyboxComponent.h>
  32. #include <AnKi/Scene/Components/TriggerComponent.h>
  33. #include <AnKi/Scene/Components/UiComponent.h>
  34. namespace anki {
  35. static StatCounter g_sceneUpdateTimeStatVar(StatCategory::kTime, "All scene update",
  36. StatFlag::kMilisecond | StatFlag::kShowAverage | StatFlag::kMainThreadUpdates);
  37. static StatCounter g_scenePhysicsTimeStatVar(StatCategory::kTime, "Physics",
  38. StatFlag::kMilisecond | StatFlag::kShowAverage | StatFlag::kMainThreadUpdates);
  39. constexpr U32 kUpdateNodeBatchSize = 10;
  40. class SceneGraph::UpdateSceneNodesCtx
  41. {
  42. public:
  43. IntrusiveList<SceneNode>::Iterator m_crntNode;
  44. SpinLock m_crntNodeLock;
  45. Second m_prevUpdateTime;
  46. Second m_crntTime;
  47. };
  48. SceneGraph::SceneGraph()
  49. {
  50. }
  51. SceneGraph::~SceneGraph()
  52. {
  53. [[maybe_unused]] const Error err = iterateSceneNodes([&](SceneNode& s) -> Error {
  54. s.setMarkedForDeletion();
  55. return Error::kNone;
  56. });
  57. deleteNodesMarkedForDeletion();
  58. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::freeSingleton();
  59. #include <AnKi/Scene/GpuSceneArrays.def.h>
  60. RenderStateBucketContainer::freeSingleton();
  61. }
  62. Error SceneGraph::init(AllocAlignedCallback allocCallback, void* allocCallbackData)
  63. {
  64. SceneMemoryPool::allocateSingleton(allocCallback, allocCallbackData);
  65. m_framePool.init(allocCallback, allocCallbackData, 1_MB, 2.0, 0, true, "SceneGraphFramePool");
  66. // Init the default main camera
  67. ANKI_CHECK(newSceneNode<SceneNode>("mainCamera", m_defaultMainCam));
  68. CameraComponent* camc = m_defaultMainCam->newComponent<CameraComponent>();
  69. camc->setPerspective(0.1f, 1000.0f, toRad(60.0f), (1080.0f / 1920.0f) * toRad(60.0f));
  70. m_mainCam = m_defaultMainCam;
  71. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::allocateSingleton(U32(cvarName));
  72. #include <AnKi/Scene/GpuSceneArrays.def.h>
  73. RenderStateBucketContainer::allocateSingleton();
  74. // Construct a few common nodex
  75. if(g_displayStatsCVar > 0)
  76. {
  77. StatsUiNode* statsNode;
  78. ANKI_CHECK(newSceneNode("_StatsUi", statsNode));
  79. statsNode->setFpsOnly(g_displayStatsCVar == 1);
  80. }
  81. DeveloperConsoleUiNode* consoleNode;
  82. ANKI_CHECK(newSceneNode("_DevConsole", consoleNode));
  83. return Error::kNone;
  84. }
  85. Error SceneGraph::registerNode(SceneNode* node)
  86. {
  87. ANKI_ASSERT(node);
  88. // Add to dict if it has a name
  89. if(node->getName())
  90. {
  91. if(tryFindSceneNode(node->getName()))
  92. {
  93. ANKI_SCENE_LOGE("Node with the same name already exists");
  94. return Error::kUserData;
  95. }
  96. m_nodesDict.emplace(node->getName(), node);
  97. }
  98. // Add to vector
  99. m_nodes.pushBack(node);
  100. ++m_nodesCount;
  101. return Error::kNone;
  102. }
  103. void SceneGraph::unregisterNode(SceneNode* node)
  104. {
  105. // Remove from the graph
  106. m_nodes.erase(node);
  107. --m_nodesCount;
  108. if(m_mainCam != m_defaultMainCam && m_mainCam == node)
  109. {
  110. m_mainCam = m_defaultMainCam;
  111. }
  112. // Remove from dict
  113. if(node->getName())
  114. {
  115. auto it = m_nodesDict.find(node->getName());
  116. ANKI_ASSERT(it != m_nodesDict.getEnd());
  117. m_nodesDict.erase(it);
  118. }
  119. }
  120. SceneNode& SceneGraph::findSceneNode(const CString& name)
  121. {
  122. SceneNode* node = tryFindSceneNode(name);
  123. ANKI_ASSERT(node);
  124. return *node;
  125. }
  126. SceneNode* SceneGraph::tryFindSceneNode(const CString& name)
  127. {
  128. auto it = m_nodesDict.find(name);
  129. return (it == m_nodesDict.getEnd()) ? nullptr : (*it);
  130. }
  131. void SceneGraph::deleteNodesMarkedForDeletion()
  132. {
  133. /// Delete all nodes pending deletion. At this point all scene threads
  134. /// should have finished their tasks
  135. while(m_objectsMarkedForDeletionCount.load() > 0)
  136. {
  137. [[maybe_unused]] Bool found = false;
  138. auto it = m_nodes.begin();
  139. auto end = m_nodes.end();
  140. for(; it != end; ++it)
  141. {
  142. SceneNode& node = *it;
  143. if(node.getMarkedForDeletion())
  144. {
  145. // Delete node
  146. unregisterNode(&node);
  147. deleteInstance(SceneMemoryPool::getSingleton(), &node);
  148. m_objectsMarkedForDeletionCount.fetchSub(1);
  149. found = true;
  150. break;
  151. }
  152. }
  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(SceneUpdate);
  160. const Second startUpdateTime = HighRezTimer::getCurrentTime();
  161. // Reset the framepool
  162. m_framePool.reset();
  163. // Delete stuff
  164. {
  165. ANKI_TRACE_SCOPED_EVENT(SceneRemoveMarkedForDeletion);
  166. const Bool fullCleanup = m_objectsMarkedForDeletionCount.load() != 0;
  167. m_events.deleteEventsMarkedForDeletion(fullCleanup);
  168. deleteNodesMarkedForDeletion();
  169. }
  170. // Update
  171. {
  172. ANKI_TRACE_SCOPED_EVENT(ScenePhysics);
  173. const Second physicsUpdate = HighRezTimer::getCurrentTime();
  174. PhysicsWorld::getSingleton().update(crntTime - prevUpdateTime);
  175. g_scenePhysicsTimeStatVar.set((HighRezTimer::getCurrentTime() - physicsUpdate) * 1000.0);
  176. }
  177. {
  178. ANKI_TRACE_SCOPED_EVENT(SceneNodesUpdate);
  179. ANKI_CHECK(m_events.updateAllEvents(prevUpdateTime, crntTime));
  180. UpdateSceneNodesCtx updateCtx;
  181. updateCtx.m_crntNode = m_nodes.getBegin();
  182. updateCtx.m_prevUpdateTime = prevUpdateTime;
  183. updateCtx.m_crntTime = crntTime;
  184. for(U i = 0; i < CoreThreadJobManager::getSingleton().getThreadCount(); i++)
  185. {
  186. CoreThreadJobManager::getSingleton().dispatchTask([this, &updateCtx]([[maybe_unused]] U32 tid) {
  187. if(updateNodes(updateCtx))
  188. {
  189. ANKI_SCENE_LOGF("Will not recover");
  190. }
  191. });
  192. }
  193. CoreThreadJobManager::getSingleton().waitForAllTasksToFinish();
  194. }
  195. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::getSingleton().flush();
  196. #include <AnKi/Scene/GpuSceneArrays.def.h>
  197. g_sceneUpdateTimeStatVar.set((HighRezTimer::getCurrentTime() - startUpdateTime) * 1000.0);
  198. return Error::kNone;
  199. }
  200. Error SceneGraph::updateNode(Second prevTime, Second crntTime, SceneNode& node)
  201. {
  202. ANKI_TRACE_INC_COUNTER(SceneNodeUpdated, 1);
  203. Error err = Error::kNone;
  204. // Components update
  205. SceneComponentUpdateInfo componentUpdateInfo(prevTime, crntTime);
  206. componentUpdateInfo.m_framePool = &m_framePool;
  207. Bool atLeastOneComponentUpdated = false;
  208. node.iterateComponents([&](SceneComponent& comp) {
  209. if(err)
  210. {
  211. return;
  212. }
  213. componentUpdateInfo.m_node = &node;
  214. Bool updated = false;
  215. err = comp.update(componentUpdateInfo, updated);
  216. if(updated)
  217. {
  218. ANKI_TRACE_INC_COUNTER(SceneComponentUpdated, 1);
  219. comp.setTimestamp(GlobalFrameIndex::getSingleton().m_value);
  220. atLeastOneComponentUpdated = true;
  221. }
  222. });
  223. // Update children
  224. if(!err)
  225. {
  226. err = node.visitChildrenMaxDepth(0, [&](SceneNode& child) -> Error {
  227. return updateNode(prevTime, crntTime, child);
  228. });
  229. }
  230. // Frame update
  231. if(!err)
  232. {
  233. if(atLeastOneComponentUpdated)
  234. {
  235. node.setComponentMaxTimestamp(GlobalFrameIndex::getSingleton().m_value);
  236. }
  237. else
  238. {
  239. // No components or nothing updated, don't change the timestamp
  240. }
  241. err = node.frameUpdate(prevTime, crntTime);
  242. }
  243. return err;
  244. }
  245. Error SceneGraph::updateNodes(UpdateSceneNodesCtx& ctx)
  246. {
  247. ANKI_TRACE_SCOPED_EVENT(SceneNodeUpdate);
  248. IntrusiveList<SceneNode>::ConstIterator end = m_nodes.getEnd();
  249. Bool quit = false;
  250. Error err = Error::kNone;
  251. while(!quit && !err)
  252. {
  253. // Fetch a batch of scene nodes that don't have parent
  254. Array<SceneNode*, kUpdateNodeBatchSize> batch;
  255. U batchSize = 0;
  256. {
  257. LockGuard<SpinLock> lock(ctx.m_crntNodeLock);
  258. while(1)
  259. {
  260. if(batchSize == batch.getSize())
  261. {
  262. break;
  263. }
  264. if(ctx.m_crntNode == end)
  265. {
  266. quit = true;
  267. break;
  268. }
  269. SceneNode& node = *ctx.m_crntNode;
  270. if(node.getParent() == nullptr)
  271. {
  272. batch[batchSize++] = &node;
  273. }
  274. ++ctx.m_crntNode;
  275. }
  276. }
  277. // Process nodes
  278. for(U i = 0; i < batchSize && !err; ++i)
  279. {
  280. err = updateNode(ctx.m_prevUpdateTime, ctx.m_crntTime, *batch[i]);
  281. }
  282. }
  283. return err;
  284. }
  285. LightComponent* SceneGraph::getDirectionalLight() const
  286. {
  287. LightComponent* out = (m_dirLights.getSize()) ? m_dirLights[0] : nullptr;
  288. if(out)
  289. {
  290. ANKI_ASSERT(out->getLightComponentType() == LightComponentType::kDirectional);
  291. }
  292. return out;
  293. }
  294. } // end namespace anki