SceneGraph.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // Copyright (C) 2009-2020, 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. namespace anki
  18. {
  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,
  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_alloc = SceneAllocator<U8>(allocCb, allocCbData);
  57. m_frameAlloc = SceneFrameAllocator<U8>(allocCb, allocCbData, 1 * 1024 * 1024);
  58. // Limits & stuff
  59. m_config.m_earlyZDistance = config.getNumberF32("scene_earlyZDistance");
  60. m_config.m_reflectionProbeEffectiveDistance = config.getNumberF32("scene_reflectionProbeEffectiveDistance");
  61. m_config.m_reflectionProbeShadowEffectiveDistance =
  62. config.getNumberF32("scene_reflectionProbeShadowEffectiveDistance");
  63. m_config.m_rayTracedShadows =
  64. config.getBool("scene_rayTracedShadows") && m_gr->getDeviceCapabilities().m_rayTracingEnabled;
  65. m_config.m_rayTracingExtendedFrustumDistance = config.getNumberF32("scene_rayTracingExtendedFrustumDistance");
  66. ANKI_CHECK(m_events.init(this));
  67. m_octree = m_alloc.newInstance<Octree>(m_alloc);
  68. m_octree->init(m_sceneMin, m_sceneMax, config.getNumberU32("scene_octreeMaxDepth"));
  69. // Init the default main camera
  70. ANKI_CHECK(newSceneNode<PerspectiveCameraNode>("mainCamera", m_defaultMainCam));
  71. m_defaultMainCam->getFirstComponentOfType<FrustumComponent>().setPerspective(0.1f, 1000.0f, toRad(60.0f),
  72. (1080.0f / 1920.0f) * toRad(60.0f));
  73. m_mainCam = m_defaultMainCam;
  74. // Create a special node for debugging the physics world
  75. PhysicsDebugNode* pnode;
  76. ANKI_CHECK(newSceneNode<PhysicsDebugNode>("_physicsDebugNode", pnode));
  77. return Error::NONE;
  78. }
  79. Error SceneGraph::registerNode(SceneNode* node)
  80. {
  81. ANKI_ASSERT(node);
  82. // Add to dict if it has a name
  83. if(node->getName())
  84. {
  85. if(tryFindSceneNode(node->getName()))
  86. {
  87. ANKI_SCENE_LOGE("Node with the same name already exists");
  88. return Error::USER_DATA;
  89. }
  90. m_nodesDict.emplace(m_alloc, node->getName(), node);
  91. }
  92. // Add to vector
  93. m_nodes.pushBack(node);
  94. ++m_nodesCount;
  95. return Error::NONE;
  96. }
  97. void SceneGraph::unregisterNode(SceneNode* node)
  98. {
  99. // Remove from the graph
  100. m_nodes.erase(node);
  101. --m_nodesCount;
  102. if(m_mainCam != m_defaultMainCam && m_mainCam == node)
  103. {
  104. m_mainCam = m_defaultMainCam;
  105. }
  106. // Remove from dict
  107. if(node->getName())
  108. {
  109. auto it = m_nodesDict.find(node->getName());
  110. ANKI_ASSERT(it != m_nodesDict.getEnd());
  111. m_nodesDict.erase(m_alloc, it);
  112. }
  113. }
  114. SceneNode& SceneGraph::findSceneNode(const CString& name)
  115. {
  116. SceneNode* node = tryFindSceneNode(name);
  117. ANKI_ASSERT(node);
  118. return *node;
  119. }
  120. SceneNode* SceneGraph::tryFindSceneNode(const CString& name)
  121. {
  122. auto it = m_nodesDict.find(name);
  123. return (it == m_nodesDict.getEnd()) ? nullptr : (*it);
  124. }
  125. void SceneGraph::deleteNodesMarkedForDeletion()
  126. {
  127. /// Delete all nodes pending deletion. At this point all scene threads
  128. /// should have finished their tasks
  129. while(m_objectsMarkedForDeletionCount.load() > 0)
  130. {
  131. Bool found = false;
  132. auto it = m_nodes.begin();
  133. auto end = m_nodes.end();
  134. for(; it != end; ++it)
  135. {
  136. SceneNode& node = *it;
  137. if(node.getMarkedForDeletion())
  138. {
  139. // Delete node
  140. unregisterNode(&node);
  141. m_alloc.deleteInstance(&node);
  142. m_objectsMarkedForDeletionCount.fetchSub(1);
  143. found = true;
  144. break;
  145. }
  146. }
  147. (void)found;
  148. ANKI_ASSERT(found && "Something is wrong with marked for deletion");
  149. }
  150. }
  151. Error SceneGraph::update(Second prevUpdateTime, Second crntTime)
  152. {
  153. ANKI_ASSERT(m_mainCam);
  154. ANKI_TRACE_SCOPED_EVENT(SCENE_UPDATE);
  155. m_stats.m_updateTime = HighRezTimer::getCurrentTime();
  156. m_timestamp = *m_globalTimestamp;
  157. ANKI_ASSERT(m_timestamp > 0);
  158. // Reset the framepool
  159. m_frameAlloc.getMemoryPool().reset();
  160. // Delete stuff
  161. {
  162. ANKI_TRACE_SCOPED_EVENT(SCENE_MARKED_FOR_DELETION);
  163. m_events.deleteEventsMarkedForDeletion();
  164. deleteNodesMarkedForDeletion();
  165. }
  166. // Update
  167. {
  168. ANKI_TRACE_SCOPED_EVENT(SCENE_PHYSICS_UPDATE);
  169. m_stats.m_physicsUpdate = HighRezTimer::getCurrentTime();
  170. m_physics->update(crntTime - prevUpdateTime);
  171. m_stats.m_physicsUpdate = HighRezTimer::getCurrentTime() - m_stats.m_physicsUpdate;
  172. }
  173. {
  174. ANKI_TRACE_SCOPED_EVENT(SCENE_NODES_UPDATE);
  175. ANKI_CHECK(m_events.updateAllEvents(prevUpdateTime, crntTime));
  176. // Then the rest
  177. Array<ThreadHiveTask, ThreadHive::MAX_THREADS> tasks;
  178. UpdateSceneNodesCtx updateCtx;
  179. updateCtx.m_scene = this;
  180. updateCtx.m_crntNode = m_nodes.getBegin();
  181. updateCtx.m_prevUpdateTime = prevUpdateTime;
  182. updateCtx.m_crntTime = crntTime;
  183. for(U i = 0; i < m_threadHive->getThreadCount(); i++)
  184. {
  185. tasks[i] = ANKI_THREAD_HIVE_TASK(
  186. {
  187. if(self->m_scene->updateNodes(*self))
  188. {
  189. ANKI_SCENE_LOGF("Will not recover");
  190. }
  191. },
  192. &updateCtx, nullptr, nullptr);
  193. }
  194. m_threadHive->submitTasks(&tasks[0], m_threadHive->getThreadCount());
  195. m_threadHive->waitAllTasks();
  196. }
  197. m_stats.m_updateTime = HighRezTimer::getCurrentTime() - m_stats.m_updateTime;
  198. return Error::NONE;
  199. }
  200. void SceneGraph::doVisibilityTests(RenderQueue& rqueue)
  201. {
  202. m_stats.m_visibilityTestsTime = HighRezTimer::getCurrentTime();
  203. doVisibilityTests(*m_mainCam, *this, rqueue);
  204. m_stats.m_visibilityTestsTime = HighRezTimer::getCurrentTime() - m_stats.m_visibilityTestsTime;
  205. }
  206. Error SceneGraph::updateNode(Second prevTime, Second crntTime, SceneNode& node)
  207. {
  208. ANKI_TRACE_INC_COUNTER(SCENE_NODES_UPDATED, 1);
  209. Error err = Error::NONE;
  210. // Components update
  211. Timestamp componentTimestamp = 0;
  212. err = node.iterateComponents([&](SceneComponent& comp) -> Error {
  213. Bool updated = false;
  214. Error e = comp.update(node, prevTime, crntTime, updated);
  215. if(updated)
  216. {
  217. comp.setTimestamp(node.getSceneGraph().m_timestamp);
  218. componentTimestamp = max(componentTimestamp, node.getSceneGraph().m_timestamp);
  219. ANKI_ASSERT(componentTimestamp > 0);
  220. }
  221. return e;
  222. });
  223. // Update children
  224. if(!err)
  225. {
  226. err = node.visitChildrenMaxDepth(
  227. 0, [&](SceneNode& child) -> Error { return updateNode(prevTime, crntTime, child); });
  228. }
  229. // Frame update
  230. if(!err)
  231. {
  232. if(componentTimestamp != 0)
  233. {
  234. node.setComponentMaxTimestamp(componentTimestamp);
  235. }
  236. else
  237. {
  238. // No components or nothing updated, don't change the timestamp
  239. }
  240. err = node.frameUpdate(prevTime, crntTime);
  241. }
  242. return err;
  243. }
  244. Error SceneGraph::updateNodes(UpdateSceneNodesCtx& ctx) const
  245. {
  246. ANKI_TRACE_SCOPED_EVENT(SCENE_NODES_UPDATE);
  247. IntrusiveList<SceneNode>::ConstIterator end = m_nodes.getEnd();
  248. Bool quit = false;
  249. Error err = Error::NONE;
  250. while(!quit && !err)
  251. {
  252. // Fetch a batch of scene nodes that don't have parent
  253. Array<SceneNode*, NODE_UPDATE_BATCH> batch;
  254. U batchSize = 0;
  255. {
  256. LockGuard<SpinLock> lock(ctx.m_crntNodeLock);
  257. while(1)
  258. {
  259. if(batchSize == batch.getSize())
  260. {
  261. break;
  262. }
  263. if(ctx.m_crntNode == end)
  264. {
  265. quit = true;
  266. break;
  267. }
  268. SceneNode& node = *ctx.m_crntNode;
  269. if(node.getParent() == nullptr)
  270. {
  271. batch[batchSize++] = &node;
  272. }
  273. ++ctx.m_crntNode;
  274. }
  275. }
  276. // Process nodes
  277. for(U i = 0; i < batchSize && !err; ++i)
  278. {
  279. err = updateNode(ctx.m_prevUpdateTime, ctx.m_crntTime, *batch[i]);
  280. }
  281. }
  282. return err;
  283. }
  284. } // end namespace anki