SceneGraph.cpp 12 KB

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