SceneGraph.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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/MoveComponent.h>
  25. #include <AnKi/Scene/Components/ParticleEmitterComponent.h>
  26. #include <AnKi/Scene/Components/PlayerControllerComponent.h>
  27. #include <AnKi/Scene/Components/ReflectionProbeComponent.h>
  28. #include <AnKi/Scene/Components/ScriptComponent.h>
  29. #include <AnKi/Scene/Components/SkinComponent.h>
  30. #include <AnKi/Scene/Components/SkyboxComponent.h>
  31. #include <AnKi/Scene/Components/TriggerComponent.h>
  32. #include <AnKi/Scene/Components/UiComponent.h>
  33. #include <AnKi/Scene/Components/MeshComponent.h>
  34. #include <AnKi/Scene/Components/MaterialComponent.h>
  35. namespace anki {
  36. ANKI_SVAR(SceneUpdateTime, StatCategory::kTime, "All scene update", StatFlag::kMilisecond | StatFlag::kShowAverage | StatFlag::kMainThreadUpdates)
  37. ANKI_SVAR(SceneComponentsUpdated, StatCategory::kScene, "Scene components updated per frame", StatFlag::kZeroEveryFrame)
  38. ANKI_SVAR(SceneNodesUpdated, StatCategory::kScene, "Scene nodes updated per frame", StatFlag::kZeroEveryFrame)
  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. DynamicArray<SceneNode*, MemoryPoolPtrWrapper<StackMemoryPool>> m_nodesForDeletion;
  48. Vec3 m_sceneMin = Vec3(kMaxF32);
  49. Vec3 m_sceneMax = Vec3(kMinF32);
  50. SpinLock m_sceneBoundsLock;
  51. UpdateSceneNodesCtx()
  52. : m_nodesForDeletion(&SceneGraph::getSingleton().m_framePool)
  53. {
  54. }
  55. };
  56. SceneGraph::SceneGraph()
  57. {
  58. }
  59. SceneGraph::~SceneGraph()
  60. {
  61. while(!m_nodesForRegistration.isEmpty())
  62. {
  63. deleteInstance(SceneMemoryPool::getSingleton(), m_nodesForRegistration.popBack());
  64. }
  65. while(!m_nodes.isEmpty())
  66. {
  67. deleteInstance(SceneMemoryPool::getSingleton(), m_nodes.popBack());
  68. }
  69. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::freeSingleton();
  70. #include <AnKi/Scene/GpuSceneArrays.def.h>
  71. RenderStateBucketContainer::freeSingleton();
  72. }
  73. Error SceneGraph::init(AllocAlignedCallback allocCallback, void* allocCallbackData)
  74. {
  75. SceneMemoryPool::allocateSingleton(allocCallback, allocCallbackData);
  76. m_framePool.init(allocCallback, allocCallbackData, 1_MB, 2.0, 0, true, "SceneGraphFramePool");
  77. // Init the default main camera
  78. m_defaultMainCam = newSceneNode<SceneNode>("mainCamera");
  79. CameraComponent* camc = m_defaultMainCam->newComponent<CameraComponent>();
  80. camc->setPerspective(0.1f, 1000.0f, toRad(60.0f), (1080.0f / 1920.0f) * toRad(60.0f));
  81. m_mainCam = m_defaultMainCam;
  82. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::allocateSingleton(U32(cvarName));
  83. #include <AnKi/Scene/GpuSceneArrays.def.h>
  84. RenderStateBucketContainer::allocateSingleton();
  85. // Construct a few common nodex
  86. if(g_cvarCoreDisplayStats > 0)
  87. {
  88. StatsUiNode* statsNode = newSceneNode<StatsUiNode>("_StatsUi");
  89. statsNode->setFpsOnly(g_cvarCoreDisplayStats == 1);
  90. }
  91. newSceneNode<DeveloperConsoleUiNode>("_DevConsole");
  92. return Error::kNone;
  93. }
  94. SceneNode& SceneGraph::findSceneNode(const CString& name)
  95. {
  96. SceneNode* node = tryFindSceneNode(name);
  97. ANKI_ASSERT(node);
  98. return *node;
  99. }
  100. SceneNode* SceneGraph::tryFindSceneNode(const CString& name)
  101. {
  102. // Search registered nodes
  103. auto it = m_nodesDict.find(name);
  104. if(it != m_nodesDict.getEnd())
  105. {
  106. return *it;
  107. }
  108. // Didn't found it, search those up for registration
  109. LockGuard lock(m_nodesForRegistrationMtx);
  110. for(SceneNode& node : m_nodesForRegistration)
  111. {
  112. if(node.getName() == name)
  113. {
  114. return &node;
  115. }
  116. }
  117. return nullptr;
  118. }
  119. void SceneGraph::update(Second prevUpdateTime, Second crntTime)
  120. {
  121. ANKI_ASSERT(m_mainCam);
  122. ANKI_TRACE_SCOPED_EVENT(SceneUpdate);
  123. const Second startUpdateTime = HighRezTimer::getCurrentTime();
  124. // Reset the framepool
  125. m_framePool.reset();
  126. // Register new nodes
  127. while(!m_nodesForRegistration.isEmpty())
  128. {
  129. SceneNode* node = m_nodesForRegistration.popFront();
  130. // Add to dict if it has a name
  131. if(node->getName() != "Unnamed")
  132. {
  133. if(tryFindSceneNode(node->getName()))
  134. {
  135. ANKI_SCENE_LOGE("Node with the same name already exists. New node will not be searchable: %s", node->getName().cstr());
  136. }
  137. else
  138. {
  139. m_nodesDict.emplace(node->getName(), node);
  140. }
  141. }
  142. // Add to list
  143. m_nodes.pushBack(node);
  144. ++m_nodesCount;
  145. }
  146. // Update physics
  147. PhysicsWorld::getSingleton().update(crntTime - prevUpdateTime);
  148. // Before the update wake some threads with dummy work
  149. for(U i = 0; i < 2; i++)
  150. {
  151. CoreThreadJobManager::getSingleton().dispatchTask([]([[maybe_unused]] U32 tid) {});
  152. }
  153. // Update events and scene nodes
  154. UpdateSceneNodesCtx updateCtx;
  155. {
  156. ANKI_TRACE_SCOPED_EVENT(SceneNodesUpdate);
  157. m_events.updateAllEvents(prevUpdateTime, crntTime);
  158. updateCtx.m_crntNode = m_nodes.getBegin();
  159. updateCtx.m_prevUpdateTime = prevUpdateTime;
  160. updateCtx.m_crntTime = crntTime;
  161. for(U i = 0; i < CoreThreadJobManager::getSingleton().getThreadCount(); i++)
  162. {
  163. CoreThreadJobManager::getSingleton().dispatchTask([this, &updateCtx]([[maybe_unused]] U32 tid) {
  164. updateNodes(updateCtx);
  165. });
  166. }
  167. CoreThreadJobManager::getSingleton().waitForAllTasksToFinish();
  168. if(updateCtx.m_sceneMin != Vec3(kMaxF32))
  169. {
  170. const Bool forceUpdateSceneBounds = (m_frame % kForceSetSceneBoundsFrameCount) == 0;
  171. if(forceUpdateSceneBounds)
  172. {
  173. m_sceneMin = updateCtx.m_sceneMin;
  174. m_sceneMax = updateCtx.m_sceneMax;
  175. }
  176. else
  177. {
  178. m_sceneMin = m_sceneMin.min(updateCtx.m_sceneMin);
  179. m_sceneMax = m_sceneMax.max(updateCtx.m_sceneMax);
  180. }
  181. }
  182. }
  183. // Cleanup
  184. for(SceneNode* node : updateCtx.m_nodesForDeletion)
  185. {
  186. // Remove from the graph
  187. m_nodes.erase(node);
  188. ANKI_ASSERT(m_nodesCount > 0);
  189. --m_nodesCount;
  190. if(m_mainCam != m_defaultMainCam && m_mainCam == node)
  191. {
  192. m_mainCam = m_defaultMainCam;
  193. }
  194. // Remove from dict
  195. if(node->getName() != "Unnamed")
  196. {
  197. auto it = m_nodesDict.find(node->getName());
  198. ANKI_ASSERT(it != m_nodesDict.getEnd());
  199. if(*it == node)
  200. {
  201. m_nodesDict.erase(it);
  202. }
  203. }
  204. deleteInstance(SceneMemoryPool::getSingleton(), node);
  205. }
  206. updateCtx.m_nodesForDeletion.destroy();
  207. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::getSingleton().flush();
  208. #include <AnKi/Scene/GpuSceneArrays.def.h>
  209. g_svarSceneUpdateTime.set((HighRezTimer::getCurrentTime() - startUpdateTime) * 1000.0);
  210. ++m_frame;
  211. }
  212. void SceneGraph::updateNode(SceneNode& node, SceneComponentUpdateInfo& componentUpdateInfo)
  213. {
  214. ANKI_TRACE_INC_COUNTER(SceneNodeUpdated, 1);
  215. // Components update
  216. U32 sceneComponentUpdatedCount = 0;
  217. node.iterateComponents([&](SceneComponent& comp) {
  218. componentUpdateInfo.m_node = &node;
  219. Bool updated = false;
  220. comp.update(componentUpdateInfo, updated);
  221. if(updated)
  222. {
  223. ANKI_TRACE_INC_COUNTER(SceneComponentUpdated, 1);
  224. comp.setTimestamp(GlobalFrameIndex::getSingleton().m_value);
  225. ++sceneComponentUpdatedCount;
  226. }
  227. });
  228. // Frame update
  229. {
  230. if(sceneComponentUpdatedCount)
  231. {
  232. node.setComponentMaxTimestamp(GlobalFrameIndex::getSingleton().m_value);
  233. g_svarSceneComponentsUpdated.increment(sceneComponentUpdatedCount);
  234. g_svarSceneNodesUpdated.increment(1);
  235. }
  236. else
  237. {
  238. // No components or nothing updated, don't change the timestamp
  239. }
  240. node.frameUpdate(componentUpdateInfo.m_previousTime, componentUpdateInfo.m_currentTime);
  241. }
  242. // Update children
  243. node.visitChildrenMaxDepth(0, [&](SceneNode& child) {
  244. updateNode(child, componentUpdateInfo);
  245. return true;
  246. });
  247. }
  248. void SceneGraph::updateNodes(UpdateSceneNodesCtx& ctx)
  249. {
  250. ANKI_TRACE_SCOPED_EVENT(SceneNodeUpdate);
  251. IntrusiveList<SceneNode>::ConstIterator end = m_nodes.getEnd();
  252. const Bool forceUpdateSceneBounds = (m_frame % kForceSetSceneBoundsFrameCount) == 0;
  253. SceneComponentUpdateInfo componentUpdateInfo(ctx.m_prevUpdateTime, ctx.m_crntTime, forceUpdateSceneBounds);
  254. componentUpdateInfo.m_framePool = &m_framePool;
  255. Bool quit = false;
  256. while(!quit)
  257. {
  258. // Fetch a batch of scene nodes that don't have parent
  259. Array<SceneNode*, kUpdateNodeBatchSize> batch;
  260. U batchSize = 0;
  261. {
  262. LockGuard<SpinLock> lock(ctx.m_crntNodeLock);
  263. while(1)
  264. {
  265. if(batchSize == batch.getSize())
  266. {
  267. break;
  268. }
  269. if(ctx.m_crntNode == end)
  270. {
  271. quit = true;
  272. break;
  273. }
  274. SceneNode& node = *ctx.m_crntNode;
  275. if(node.isMarkedForDeletion())
  276. {
  277. ctx.m_nodesForDeletion.emplaceBack(&node);
  278. }
  279. else if(node.getParent() == nullptr)
  280. {
  281. batch[batchSize++] = &node;
  282. }
  283. else
  284. {
  285. // Ignore
  286. }
  287. ++ctx.m_crntNode;
  288. }
  289. }
  290. // Process nodes
  291. for(U i = 0; i < batchSize; ++i)
  292. {
  293. updateNode(*batch[i], componentUpdateInfo);
  294. }
  295. }
  296. if(componentUpdateInfo.m_sceneMin != Vec3(kMaxF32))
  297. {
  298. LockGuard lock(ctx.m_sceneBoundsLock);
  299. ctx.m_sceneMin = ctx.m_sceneMin.min(componentUpdateInfo.m_sceneMin);
  300. ctx.m_sceneMax = ctx.m_sceneMax.max(componentUpdateInfo.m_sceneMax);
  301. }
  302. }
  303. LightComponent* SceneGraph::getDirectionalLight() const
  304. {
  305. LightComponent* out = (m_dirLights.getSize()) ? m_dirLights[0] : nullptr;
  306. if(out)
  307. {
  308. ANKI_ASSERT(out->getLightComponentType() == LightComponentType::kDirectional);
  309. }
  310. return out;
  311. }
  312. const SceneNode& SceneGraph::getActiveCameraNode() const
  313. {
  314. ANKI_ASSERT(m_mainCam);
  315. if(ANKI_EXPECT(m_mainCam->hasComponent<CameraComponent>()))
  316. {
  317. return *m_mainCam;
  318. }
  319. else
  320. {
  321. return *m_defaultMainCam;
  322. }
  323. }
  324. void SceneGraph::setActiveCameraNode(SceneNode* cam)
  325. {
  326. if(cam)
  327. {
  328. m_mainCam = cam;
  329. }
  330. else
  331. {
  332. m_mainCam = m_defaultMainCam;
  333. }
  334. }
  335. } // end namespace anki