SceneGraph.cpp 12 KB

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