ModelComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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/Components/ModelComponent.h>
  6. #include <AnKi/Scene/SceneNode.h>
  7. #include <AnKi/Scene/SceneGraph.h>
  8. #include <AnKi/Scene/Components/MoveComponent.h>
  9. #include <AnKi/Scene/Components/SkinComponent.h>
  10. #include <AnKi/Resource/ModelResource.h>
  11. #include <AnKi/Resource/ResourceManager.h>
  12. #include <AnKi/Shaders/Include/GpuSceneFunctions.h>
  13. namespace anki {
  14. ModelComponent::ModelComponent(SceneNode* node)
  15. : SceneComponent(node, kClassType)
  16. , m_node(node)
  17. {
  18. m_gpuSceneTransforms.allocate();
  19. }
  20. ModelComponent::~ModelComponent()
  21. {
  22. }
  23. void ModelComponent::freeGpuScene()
  24. {
  25. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneUniforms);
  26. for(PatchInfo& patch : m_patchInfos)
  27. {
  28. patch.m_gpuSceneMeshLods.free();
  29. patch.m_gpuSceneRenderable.free();
  30. patch.m_gpuSceneRenderableAabbDepth.free();
  31. patch.m_gpuSceneRenderableAabbForward.free();
  32. patch.m_gpuSceneRenderableAabbGBuffer.free();
  33. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  34. {
  35. RenderStateBucketContainer::getSingleton().removeUser(patch.m_renderStateBucketIndices[t]);
  36. }
  37. }
  38. }
  39. void ModelComponent::loadModelResource(CString filename)
  40. {
  41. ModelResourcePtr rsrc;
  42. const Error err = ResourceManager::getSingleton().loadResource(filename, rsrc);
  43. if(err)
  44. {
  45. ANKI_SCENE_LOGE("Failed to load model resource");
  46. return;
  47. }
  48. m_resourceChanged = true;
  49. m_model = std::move(rsrc);
  50. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  51. // Init
  52. freeGpuScene();
  53. m_patchInfos.resize(modelPatchCount);
  54. m_presentRenderingTechniques = RenderingTechniqueBit::kNone;
  55. // Allocate all uniforms so you can make one allocation
  56. U32 uniformsSize = 0;
  57. for(U32 i = 0; i < modelPatchCount; ++i)
  58. {
  59. const U32 size = U32(m_model->getModelPatches()[i].getMaterial()->getPrefilledLocalUniforms().getSizeInBytes());
  60. ANKI_ASSERT((size % 4) == 0);
  61. uniformsSize += size;
  62. }
  63. m_gpuSceneUniforms = GpuSceneBuffer::getSingleton().allocate(uniformsSize, 4);
  64. uniformsSize = 0;
  65. // Init the patches
  66. for(U32 i = 0; i < modelPatchCount; ++i)
  67. {
  68. PatchInfo& out = m_patchInfos[i];
  69. const ModelPatch& in = m_model->getModelPatches()[i];
  70. out.m_techniques = in.getMaterial()->getRenderingTechniques();
  71. m_castsShadow = m_castsShadow || in.getMaterial()->castsShadow();
  72. m_presentRenderingTechniques |= in.getMaterial()->getRenderingTechniques();
  73. out.m_gpuSceneUniformsOffset = m_gpuSceneUniforms.getOffset() + uniformsSize;
  74. uniformsSize += U32(in.getMaterial()->getPrefilledLocalUniforms().getSizeInBytes());
  75. out.m_gpuSceneMeshLods.allocate();
  76. out.m_gpuSceneRenderable.allocate();
  77. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  78. {
  79. if(!(RenderingTechniqueBit(1 << t) & out.m_techniques) || !!(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt))
  80. {
  81. continue;
  82. }
  83. switch(t)
  84. {
  85. case RenderingTechnique::kGBuffer:
  86. out.m_gpuSceneRenderableAabbGBuffer.allocate();
  87. break;
  88. case RenderingTechnique::kForward:
  89. out.m_gpuSceneRenderableAabbForward.allocate();
  90. break;
  91. case RenderingTechnique::kDepth:
  92. out.m_gpuSceneRenderableAabbDepth.allocate();
  93. break;
  94. default:
  95. ANKI_ASSERT(0);
  96. }
  97. }
  98. }
  99. }
  100. Error ModelComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  101. {
  102. if(!isEnabled()) [[unlikely]]
  103. {
  104. updated = false;
  105. return Error::kNone;
  106. }
  107. const Bool resourceUpdated = m_resourceChanged;
  108. m_resourceChanged = false;
  109. const Bool moved = info.m_node->movedThisFrame() || m_firstTimeUpdate;
  110. const Bool movedLastFrame = m_movedLastFrame || m_firstTimeUpdate;
  111. m_firstTimeUpdate = false;
  112. m_movedLastFrame = moved;
  113. const Bool hasSkin = m_skinComponent != nullptr && m_skinComponent->isEnabled();
  114. updated = resourceUpdated || moved || movedLastFrame;
  115. // Upload GpuSceneMeshLod, uniforms and GpuSceneRenderable
  116. if(resourceUpdated) [[unlikely]]
  117. {
  118. // Upload the mesh views
  119. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  120. for(U32 i = 0; i < modelPatchCount; ++i)
  121. {
  122. const ModelPatch& patch = m_model->getModelPatches()[i];
  123. const MeshResource& mesh = *patch.getMesh();
  124. Array<GpuSceneMeshLod, kMaxLodCount> meshLods;
  125. for(U32 l = 0; l < mesh.getLodCount(); ++l)
  126. {
  127. GpuSceneMeshLod& meshLod = meshLods[l];
  128. meshLod = {};
  129. meshLod.m_positionScale = mesh.getPositionsScale();
  130. meshLod.m_positionTranslation = mesh.getPositionsTranslation();
  131. ModelPatchGeometryInfo inf;
  132. patch.getGeometryInfo(l, inf);
  133. ANKI_ASSERT((inf.m_indexBufferOffset % getIndexSize(inf.m_indexType)) == 0);
  134. meshLod.m_firstIndex = U32(inf.m_indexBufferOffset / getIndexSize(inf.m_indexType));
  135. meshLod.m_indexCount = inf.m_indexCount;
  136. for(VertexStreamId stream = VertexStreamId::kMeshRelatedFirst; stream < VertexStreamId::kMeshRelatedCount; ++stream)
  137. {
  138. if(mesh.isVertexStreamPresent(stream))
  139. {
  140. const PtrSize elementSize = getFormatInfo(kMeshRelatedVertexStreamFormats[stream]).m_texelSize;
  141. ANKI_ASSERT((inf.m_vertexBufferOffsets[stream] % elementSize) == 0);
  142. meshLod.m_vertexOffsets[U32(stream)] = U32(inf.m_vertexBufferOffsets[stream] / elementSize);
  143. }
  144. else
  145. {
  146. meshLod.m_vertexOffsets[U32(stream)] = kMaxU32;
  147. }
  148. }
  149. }
  150. // Copy the last LOD to the rest just in case
  151. for(U32 l = mesh.getLodCount(); l < kMaxLodCount; ++l)
  152. {
  153. meshLods[l] = meshLods[l - 1];
  154. }
  155. m_patchInfos[i].m_gpuSceneMeshLods.uploadToGpuScene(meshLods);
  156. // Upload the GpuSceneRenderable
  157. GpuSceneRenderable gpuRenderable = {};
  158. gpuRenderable.m_worldTransformsOffset = m_gpuSceneTransforms.getGpuSceneOffset();
  159. gpuRenderable.m_uniformsOffset = m_patchInfos[i].m_gpuSceneUniformsOffset;
  160. gpuRenderable.m_meshLodsOffset = m_patchInfos[i].m_gpuSceneMeshLods.getGpuSceneOffset();
  161. gpuRenderable.m_boneTransformsOffset = (hasSkin) ? m_skinComponent->getBoneTransformsGpuSceneOffset() : 0;
  162. m_patchInfos[i].m_gpuSceneRenderable.uploadToGpuScene(gpuRenderable);
  163. }
  164. // Upload the uniforms
  165. DynamicArray<U32, MemoryPoolPtrWrapper<StackMemoryPool>> allUniforms(info.m_framePool);
  166. allUniforms.resize(m_gpuSceneUniforms.getAllocatedSize() / 4);
  167. U32 count = 0;
  168. for(U32 i = 0; i < modelPatchCount; ++i)
  169. {
  170. const ModelPatch& patch = m_model->getModelPatches()[i];
  171. const MaterialResource& mtl = *patch.getMaterial();
  172. memcpy(&allUniforms[count], mtl.getPrefilledLocalUniforms().getBegin(), mtl.getPrefilledLocalUniforms().getSizeInBytes());
  173. count += U32(mtl.getPrefilledLocalUniforms().getSizeInBytes() / 4);
  174. }
  175. ANKI_ASSERT(count * 4 == m_gpuSceneUniforms.getAllocatedSize());
  176. GpuSceneMicroPatcher::getSingleton().newCopy(*info.m_framePool, m_gpuSceneUniforms.getOffset(), m_gpuSceneUniforms.getAllocatedSize(),
  177. &allUniforms[0]);
  178. }
  179. // Upload transforms
  180. if(moved || movedLastFrame) [[unlikely]]
  181. {
  182. Array<Mat3x4, 2> trfs;
  183. trfs[0] = Mat3x4(info.m_node->getWorldTransform());
  184. trfs[1] = Mat3x4(info.m_node->getPreviousWorldTransform());
  185. m_gpuSceneTransforms.uploadToGpuScene(trfs);
  186. }
  187. // Scene bounds update
  188. const Bool aabbUpdated = moved || resourceUpdated || m_skinComponent;
  189. if(aabbUpdated) [[unlikely]]
  190. {
  191. const Aabb aabbWorld = computeAabbWorldSpace(info.m_node->getWorldTransform());
  192. SceneGraph::getSingleton().updateSceneBounds(aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz());
  193. }
  194. // Update the buckets
  195. const Bool bucketsNeedUpdate = resourceUpdated || moved != movedLastFrame;
  196. if(bucketsNeedUpdate)
  197. {
  198. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  199. for(U32 i = 0; i < modelPatchCount; ++i)
  200. {
  201. // Refresh the render state buckets
  202. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  203. {
  204. RenderStateBucketContainer::getSingleton().removeUser(m_patchInfos[i].m_renderStateBucketIndices[t]);
  205. if(!(RenderingTechniqueBit(1 << t) & m_patchInfos[i].m_techniques))
  206. {
  207. continue;
  208. }
  209. // Fill the state
  210. RenderingKey key;
  211. key.setLod(0); // Materials don't care
  212. key.setRenderingTechnique(t);
  213. key.setSkinned(hasSkin);
  214. key.setVelocity(moved);
  215. const MaterialVariant& mvariant = m_model->getModelPatches()[i].getMaterial()->getOrCreateVariant(key);
  216. RenderStateInfo state;
  217. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  218. state.m_indexedDrawcall = true;
  219. state.m_program = mvariant.getShaderProgram();
  220. m_patchInfos[i].m_renderStateBucketIndices[t] = RenderStateBucketContainer::getSingleton().addUser(state, t);
  221. }
  222. }
  223. }
  224. // Upload the AABBs to the GPU scene
  225. const Bool gpuSceneAabbsNeedUpdate = aabbUpdated || bucketsNeedUpdate;
  226. if(gpuSceneAabbsNeedUpdate)
  227. {
  228. const Aabb aabbWorld = computeAabbWorldSpace(info.m_node->getWorldTransform());
  229. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  230. for(U32 i = 0; i < modelPatchCount; ++i)
  231. {
  232. for(RenderingTechnique t :
  233. EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(m_patchInfos[i].m_techniques & ~RenderingTechniqueBit::kAllRt))
  234. {
  235. const GpuSceneRenderableAabb gpuVolume =
  236. initGpuSceneRenderableAabb(aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz(), m_patchInfos[i].m_gpuSceneRenderable.getIndex(),
  237. m_patchInfos[i].m_renderStateBucketIndices[t].get());
  238. switch(t)
  239. {
  240. case RenderingTechnique::kGBuffer:
  241. m_patchInfos[i].m_gpuSceneRenderableAabbGBuffer.uploadToGpuScene(gpuVolume);
  242. break;
  243. case RenderingTechnique::kDepth:
  244. m_patchInfos[i].m_gpuSceneRenderableAabbDepth.uploadToGpuScene(gpuVolume);
  245. break;
  246. case RenderingTechnique::kForward:
  247. m_patchInfos[i].m_gpuSceneRenderableAabbForward.uploadToGpuScene(gpuVolume);
  248. break;
  249. default:
  250. ANKI_ASSERT(0);
  251. }
  252. }
  253. }
  254. }
  255. return Error::kNone;
  256. }
  257. void ModelComponent::setupRayTracingInstanceQueueElements(U32 lod, RenderingTechnique technique,
  258. WeakArray<RayTracingInstanceQueueElement>& outInstances) const
  259. {
  260. ANKI_ASSERT(isEnabled());
  261. outInstances.setArray(nullptr, 0);
  262. const RenderingTechniqueBit requestedRenderingTechniqueMask = RenderingTechniqueBit(1 << technique);
  263. if(!(m_presentRenderingTechniques & requestedRenderingTechniqueMask))
  264. {
  265. return;
  266. }
  267. // Allocate instances
  268. U32 instanceCount = 0;
  269. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  270. {
  271. instanceCount += !!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask);
  272. }
  273. if(instanceCount == 0)
  274. {
  275. return;
  276. }
  277. RayTracingInstanceQueueElement* instances = static_cast<RayTracingInstanceQueueElement*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(
  278. sizeof(RayTracingInstanceQueueElement) * instanceCount, alignof(RayTracingInstanceQueueElement)));
  279. outInstances.setArray(instances, instanceCount);
  280. RenderingKey key;
  281. key.setLod(lod);
  282. key.setRenderingTechnique(technique);
  283. instanceCount = 0;
  284. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  285. {
  286. if(!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask))
  287. {
  288. continue;
  289. }
  290. RayTracingInstanceQueueElement& queueElem = instances[instanceCount];
  291. const ModelPatch& patch = m_model->getModelPatches()[i];
  292. ModelRayTracingInfo modelInf;
  293. patch.getRayTracingInfo(key, modelInf);
  294. queueElem.m_bottomLevelAccelerationStructure = modelInf.m_bottomLevelAccelerationStructure.get();
  295. queueElem.m_shaderGroupHandleIndex = modelInf.m_shaderGroupHandleIndex;
  296. queueElem.m_worldTransformsOffset = m_gpuSceneTransforms.getGpuSceneOffset();
  297. queueElem.m_uniformsOffset = m_patchInfos[i].m_gpuSceneUniformsOffset;
  298. queueElem.m_geometryOffset =
  299. U32(m_patchInfos[i].m_gpuSceneMeshLods.getIndex() * sizeof(GpuSceneMeshLod) * kMaxLodCount + lod * sizeof(GpuSceneMeshLod));
  300. queueElem.m_geometryOffset += U32(GpuSceneArrays::MeshLod::getSingleton().getGpuSceneOffsetOfArrayBase());
  301. queueElem.m_indexBufferOffset = U32(modelInf.m_indexBufferOffset);
  302. const Transform positionTransform(patch.getMesh()->getPositionsTranslation().xyz0(), Mat3x4::getIdentity(),
  303. patch.getMesh()->getPositionsScale());
  304. queueElem.m_transform = Mat3x4(m_node->getWorldTransform()).combineTransformations(Mat3x4(positionTransform));
  305. ++instanceCount;
  306. }
  307. }
  308. void ModelComponent::onOtherComponentRemovedOrAdded(SceneComponent* other, Bool added)
  309. {
  310. ANKI_ASSERT(other);
  311. if(other->getType() != SceneComponentType::kSkin)
  312. {
  313. return;
  314. }
  315. const Bool alreadyHasSkinComponent = m_skinComponent != nullptr;
  316. if(added && !alreadyHasSkinComponent)
  317. {
  318. m_skinComponent = static_cast<SkinComponent*>(other);
  319. m_resourceChanged = true;
  320. }
  321. else if(!added && other == m_skinComponent)
  322. {
  323. m_skinComponent = nullptr;
  324. m_resourceChanged = true;
  325. }
  326. }
  327. Aabb ModelComponent::computeAabbWorldSpace(const Transform& worldTransform) const
  328. {
  329. Aabb aabbLocal;
  330. if(m_skinComponent == nullptr) [[likely]]
  331. {
  332. aabbLocal = m_model->getBoundingVolume();
  333. }
  334. else
  335. {
  336. aabbLocal = m_skinComponent->getBoneBoundingVolumeLocalSpace().getCompoundShape(m_model->getBoundingVolume());
  337. }
  338. return aabbLocal.getTransformed(worldTransform);
  339. }
  340. } // end namespace anki