MaterialComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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/Components/MaterialComponent.h>
  6. #include <AnKi/Scene/Components/SkinComponent.h>
  7. #include <AnKi/Scene/Components/MeshComponent.h>
  8. #include <AnKi/Resource/MeshResource.h>
  9. #include <AnKi/Resource/MaterialResource.h>
  10. #include <AnKi/Resource/ResourceManager.h>
  11. #include <AnKi/Core/App.h>
  12. #include <AnKi/Shaders/Include/GpuSceneFunctions.h>
  13. namespace anki {
  14. MaterialComponent::MaterialComponent(SceneNode* node)
  15. : SceneComponent(node, kClassType)
  16. {
  17. m_gpuSceneTransforms.allocate();
  18. m_gpuSceneRenderable.allocate();
  19. m_gpuSceneMeshLods.allocate();
  20. }
  21. MaterialComponent::~MaterialComponent()
  22. {
  23. m_gpuSceneTransforms.free();
  24. m_gpuSceneRenderable.free();
  25. m_gpuSceneMeshLods.free();
  26. }
  27. MaterialComponent& MaterialComponent::setMaterialFilename(CString fname)
  28. {
  29. MaterialResourcePtr newRsrc;
  30. const Error err = ResourceManager::getSingleton().loadResource(fname, newRsrc);
  31. if(err)
  32. {
  33. ANKI_SCENE_LOGE("Failed to load resource: %s", fname.cstr());
  34. }
  35. else
  36. {
  37. m_resource = std::move(newRsrc);
  38. m_castsShadow = m_resource->castsShadow();
  39. m_resourceDirty = true;
  40. }
  41. return *this;
  42. }
  43. MaterialComponent& MaterialComponent::setSubmeshIndex(U32 submeshIdx)
  44. {
  45. if(m_submeshIdx != submeshIdx)
  46. {
  47. m_submeshIdx = submeshIdx;
  48. m_submeshIdxDirty = true;
  49. }
  50. return *this;
  51. }
  52. void MaterialComponent::onOtherComponentRemovedOrAdded(SceneComponent* other, Bool added)
  53. {
  54. ANKI_ASSERT(other);
  55. if(other->getType() == SceneComponentType::kSkin)
  56. {
  57. const Bool alreadyHasSkinComponent = m_skinComponent != nullptr;
  58. if(added && !alreadyHasSkinComponent)
  59. {
  60. m_skinComponent = static_cast<SkinComponent*>(other);
  61. m_skinDirty = true;
  62. }
  63. else if(!added && other == m_skinComponent)
  64. {
  65. m_skinComponent = nullptr;
  66. m_skinDirty = true;
  67. }
  68. }
  69. if(other->getType() == SceneComponentType::kMesh)
  70. {
  71. const Bool alreadyHasMeshComponent = m_meshComponent != nullptr;
  72. if(added && !alreadyHasMeshComponent)
  73. {
  74. m_meshComponent = static_cast<MeshComponent*>(other);
  75. m_meshComponentDirty = true;
  76. }
  77. else if(!added && other == m_meshComponent)
  78. {
  79. m_meshComponent = nullptr;
  80. m_meshComponentDirty = true;
  81. }
  82. }
  83. }
  84. Aabb MaterialComponent::computeAabb(U32 submeshIndex, const SceneNode& node) const
  85. {
  86. U32 firstIndex, indexCount, firstMeshlet, meshletCount;
  87. Aabb aabbLocal;
  88. m_meshComponent->getMeshResource().getSubMeshInfo(0, submeshIndex, firstIndex, indexCount, firstMeshlet, meshletCount, aabbLocal);
  89. if(m_skinComponent)
  90. {
  91. aabbLocal = m_skinComponent->getBoneBoundingVolumeLocalSpace().getCompoundShape(aabbLocal);
  92. }
  93. const Aabb aabbWorld = aabbLocal.getTransformed(node.getWorldTransform());
  94. return aabbWorld;
  95. }
  96. void MaterialComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  97. {
  98. const Bool mtlUpdated = m_resourceDirty;
  99. const Bool meshUpdated = m_meshComponentDirty || (m_meshComponent && m_meshComponent->updatedThisFrame());
  100. const Bool moved = info.m_node->movedThisFrame() || m_firstTimeUpdate;
  101. const Bool movedLastFrame = m_movedLastFrame || m_firstTimeUpdate;
  102. const Bool skinUpdated = m_skinDirty;
  103. const Bool submeshUpdated = m_submeshIdxDirty;
  104. const Bool hasSkin = m_skinComponent && m_skinComponent->isEnabled();
  105. const Bool isValid = m_resource.isCreated() && m_meshComponent && m_meshComponent->isEnabled();
  106. m_resourceDirty = false;
  107. m_firstTimeUpdate = false;
  108. m_meshComponentDirty = false;
  109. m_movedLastFrame = moved;
  110. m_skinDirty = false;
  111. m_submeshIdxDirty = false;
  112. updated = mtlUpdated || meshUpdated || moved || skinUpdated || submeshUpdated;
  113. if(!isValid) [[unlikely]]
  114. {
  115. m_gpuSceneRenderableAabbGBuffer.free();
  116. m_gpuSceneRenderableAabbDepth.free();
  117. m_gpuSceneRenderableAabbForward.free();
  118. m_gpuSceneRenderableAabbRt.free();
  119. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  120. {
  121. RenderStateBucketContainer::getSingleton().removeUser(m_renderStateBucketIndices[t]);
  122. }
  123. return;
  124. }
  125. // From now on the component is considered valid
  126. const MaterialResource& mtl = *m_resource;
  127. const MeshResource& mesh = m_meshComponent->getMeshResource();
  128. const U32 submeshIdx = min(mesh.getSubMeshCount() - 1, m_submeshIdx);
  129. // Upload transforms
  130. if(moved || movedLastFrame) [[unlikely]]
  131. {
  132. Array<Mat3x4, 2> trfs;
  133. trfs[0] = Mat3x4(info.m_node->getWorldTransform());
  134. trfs[1] = Mat3x4(info.m_node->getPreviousWorldTransform());
  135. m_gpuSceneTransforms.uploadToGpuScene(trfs);
  136. }
  137. // Update mesh lods
  138. const Bool meshLodsNeedUpdate = meshUpdated || submeshUpdated;
  139. if(meshLodsNeedUpdate) [[unlikely]]
  140. {
  141. Array<GpuSceneMeshLod, kMaxLodCount> meshLods;
  142. for(U32 l = 0; l < mesh.getLodCount(); ++l)
  143. {
  144. GpuSceneMeshLod& meshLod = meshLods[l];
  145. meshLod = {};
  146. meshLod.m_positionScale = mesh.getPositionsScale();
  147. meshLod.m_positionTranslation = mesh.getPositionsTranslation();
  148. U32 firstIndex, indexCount, firstMeshlet, meshletCount;
  149. Aabb aabb;
  150. mesh.getSubMeshInfo(l, submeshIdx, firstIndex, indexCount, firstMeshlet, meshletCount, aabb);
  151. U32 totalIndexCount;
  152. IndexType indexType;
  153. PtrSize indexUgbOffset;
  154. mesh.getIndexBufferInfo(l, indexUgbOffset, totalIndexCount, indexType);
  155. for(VertexStreamId stream = VertexStreamId::kMeshRelatedFirst; stream < VertexStreamId::kMeshRelatedCount; ++stream)
  156. {
  157. if(mesh.isVertexStreamPresent(stream))
  158. {
  159. U32 vertCount;
  160. PtrSize ugbOffset;
  161. mesh.getVertexBufferInfo(l, stream, ugbOffset, vertCount);
  162. const PtrSize elementSize = getFormatInfo(kMeshRelatedVertexStreamFormats[stream]).m_texelSize;
  163. ANKI_ASSERT(ugbOffset % elementSize == 0);
  164. meshLod.m_vertexOffsets[U32(stream)] = U32(ugbOffset / elementSize);
  165. }
  166. else
  167. {
  168. meshLod.m_vertexOffsets[U32(stream)] = kMaxU32;
  169. }
  170. }
  171. meshLod.m_indexCount = indexCount;
  172. ANKI_ASSERT(indexUgbOffset % getIndexSize(indexType) == 0);
  173. meshLod.m_firstIndex = U32(indexUgbOffset / getIndexSize(indexType)) + firstIndex;
  174. meshLod.m_renderableIndex = m_gpuSceneRenderable.getIndex();
  175. if(GrManager::getSingleton().getDeviceCapabilities().m_meshShaders || g_cvarCoreMeshletRendering)
  176. {
  177. U32 dummy;
  178. PtrSize meshletBoundingVolumesUgbOffset, meshletGometryDescriptorsUgbOffset;
  179. mesh.getMeshletBufferInfo(l, meshletBoundingVolumesUgbOffset, meshletGometryDescriptorsUgbOffset, dummy);
  180. meshLod.m_firstMeshletBoundingVolume = firstMeshlet + U32(meshletBoundingVolumesUgbOffset / sizeof(MeshletBoundingVolume));
  181. meshLod.m_firstMeshletGeometryDescriptor = firstMeshlet + U32(meshletGometryDescriptorsUgbOffset / sizeof(MeshletGeometryDescriptor));
  182. meshLod.m_meshletCount = meshletCount;
  183. }
  184. meshLod.m_lod = l;
  185. if(!!(mtl.getRenderingTechniques() & RenderingTechniqueBit::kAllRt))
  186. {
  187. const U64 address = mesh.getBottomLevelAccelerationStructure(l, submeshIdx)->getGpuAddress();
  188. memcpy(&meshLod.m_blasAddress, &address, sizeof(meshLod.m_blasAddress));
  189. meshLod.m_tlasInstanceMask = 0xFFFFFFFF;
  190. }
  191. }
  192. // Copy the last LOD to the rest just in case
  193. for(U32 l = mesh.getLodCount(); l < kMaxLodCount; ++l)
  194. {
  195. meshLods[l] = meshLods[l - 1];
  196. }
  197. m_gpuSceneMeshLods.uploadToGpuScene(meshLods);
  198. }
  199. // Update the constants
  200. const Bool constantsNeedUpdate = mtlUpdated;
  201. if(mtlUpdated) [[unlikely]]
  202. {
  203. ConstWeakArray<U8> preallocatedConsts = mtl.getPrefilledLocalConstants();
  204. if(!m_gpuSceneConstants.isValid() || m_gpuSceneConstants.getAllocatedSize() != preallocatedConsts.getSizeInBytes())
  205. {
  206. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneConstants);
  207. m_gpuSceneConstants = GpuSceneBuffer::getSingleton().allocate(preallocatedConsts.getSizeInBytes(), 4);
  208. }
  209. GpuSceneMicroPatcher::getSingleton().newCopy(*info.m_framePool, m_gpuSceneConstants.getOffset(), m_gpuSceneConstants.getAllocatedSize(),
  210. preallocatedConsts.getBegin());
  211. }
  212. // Update renderable
  213. if(constantsNeedUpdate || skinUpdated) [[unlikely]]
  214. {
  215. GpuSceneRenderable gpuRenderable = {};
  216. gpuRenderable.m_worldTransformsIndex = m_gpuSceneTransforms.getIndex() * 2;
  217. gpuRenderable.m_constantsOffset = m_gpuSceneConstants.getOffset();
  218. gpuRenderable.m_meshLodsIndex = m_gpuSceneMeshLods.getIndex() * kMaxLodCount;
  219. gpuRenderable.m_boneTransformsOffset = (hasSkin) ? m_skinComponent->getBoneTransformsGpuSceneOffset() : 0;
  220. gpuRenderable.m_particleEmitterIndex = kMaxU32;
  221. if(!!(mtl.getRenderingTechniques() & RenderingTechniqueBit::kRtShadow))
  222. {
  223. const RenderingKey key(RenderingTechnique::kRtShadow, 0, false, false, false);
  224. const MaterialVariant& variant = mtl.getOrCreateVariant(key);
  225. gpuRenderable.m_rtShadowsShaderHandleIndex = variant.getRtShaderGroupHandleIndex();
  226. }
  227. if(!!(mtl.getRenderingTechniques() & RenderingTechniqueBit::kRtMaterialFetch))
  228. {
  229. const RenderingKey key(RenderingTechnique::kRtMaterialFetch, 0, false, false, false);
  230. const MaterialVariant& variant = mtl.getOrCreateVariant(key);
  231. gpuRenderable.m_rtMaterialFetchShaderHandleIndex = variant.getRtShaderGroupHandleIndex();
  232. }
  233. gpuRenderable.m_uuid = SceneGraph::getSingleton().getNewUuid();
  234. m_gpuSceneRenderable.uploadToGpuScene(gpuRenderable);
  235. }
  236. // Scene bounds update
  237. const Bool aabbUpdated = moved || meshUpdated || submeshUpdated || hasSkin;
  238. if(aabbUpdated) [[unlikely]]
  239. {
  240. const Aabb aabbWorld = computeAabb(submeshIdx, *info.m_node);
  241. SceneGraph::getSingleton().updateSceneBounds(aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz());
  242. }
  243. // Update the buckets
  244. const Bool bucketsNeedUpdate = mtlUpdated || submeshUpdated || moved != movedLastFrame;
  245. if(bucketsNeedUpdate) [[unlikely]]
  246. {
  247. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  248. {
  249. RenderStateBucketContainer::getSingleton().removeUser(m_renderStateBucketIndices[t]);
  250. if(!(RenderingTechniqueBit(1 << t) & mtl.getRenderingTechniques()))
  251. {
  252. continue;
  253. }
  254. // Fill the state
  255. RenderingKey key;
  256. key.setLod(0); // Materials don't care
  257. key.setRenderingTechnique(t);
  258. key.setSkinned(hasSkin);
  259. key.setVelocity(moved);
  260. key.setMeshletRendering(GrManager::getSingleton().getDeviceCapabilities().m_meshShaders || g_cvarCoreMeshletRendering);
  261. const MaterialVariant& mvariant = mtl.getOrCreateVariant(key);
  262. RenderStateInfo state;
  263. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  264. state.m_indexedDrawcall = true;
  265. state.m_program = mvariant.getShaderProgram();
  266. U32 firstIndex, indexCount, firstMeshlet, meshletCount;
  267. Aabb aabb;
  268. mesh.getSubMeshInfo(0, submeshIdx, firstIndex, indexCount, firstMeshlet, meshletCount, aabb);
  269. const Bool wantsMesletCount = key.getMeshletRendering() && !(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt);
  270. m_renderStateBucketIndices[t] = RenderStateBucketContainer::getSingleton().addUser(state, t, (wantsMesletCount) ? meshletCount : 0);
  271. }
  272. }
  273. // Upload the AABBs to the GPU scene
  274. const Bool gpuSceneAabbsNeedUpdate = aabbUpdated || bucketsNeedUpdate;
  275. if(gpuSceneAabbsNeedUpdate) [[unlikely]]
  276. {
  277. const Aabb aabbWorld = computeAabb(submeshIdx, *info.m_node);
  278. // Raster
  279. for(RenderingTechnique t : EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(RenderingTechniqueBit::kAllRaster))
  280. {
  281. const RenderingTechniqueBit bit = RenderingTechniqueBit(1 << t);
  282. if(!(mtl.getRenderingTechniques() & bit))
  283. {
  284. switch(t)
  285. {
  286. case RenderingTechnique::kGBuffer:
  287. m_gpuSceneRenderableAabbGBuffer.free();
  288. break;
  289. case RenderingTechnique::kDepth:
  290. m_gpuSceneRenderableAabbDepth.free();
  291. break;
  292. case RenderingTechnique::kForward:
  293. m_gpuSceneRenderableAabbForward.free();
  294. break;
  295. default:
  296. ANKI_ASSERT(0);
  297. }
  298. }
  299. else
  300. {
  301. const GpuSceneRenderableBoundingVolume gpuVolume = initGpuSceneRenderableBoundingVolume(
  302. aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz(), m_gpuSceneRenderable.getIndex(), m_renderStateBucketIndices[t].get());
  303. switch(t)
  304. {
  305. case RenderingTechnique::kGBuffer:
  306. if(!m_gpuSceneRenderableAabbGBuffer.isValid())
  307. {
  308. m_gpuSceneRenderableAabbGBuffer.allocate();
  309. }
  310. m_gpuSceneRenderableAabbGBuffer.uploadToGpuScene(gpuVolume);
  311. break;
  312. case RenderingTechnique::kDepth:
  313. if(!m_gpuSceneRenderableAabbDepth.isValid())
  314. {
  315. m_gpuSceneRenderableAabbDepth.allocate();
  316. }
  317. m_gpuSceneRenderableAabbDepth.uploadToGpuScene(gpuVolume);
  318. break;
  319. case RenderingTechnique::kForward:
  320. if(!m_gpuSceneRenderableAabbForward.isValid())
  321. {
  322. m_gpuSceneRenderableAabbForward.allocate();
  323. }
  324. m_gpuSceneRenderableAabbForward.uploadToGpuScene(gpuVolume);
  325. break;
  326. default:
  327. ANKI_ASSERT(0);
  328. }
  329. }
  330. }
  331. // RT
  332. if(!!(mtl.getRenderingTechniques() & RenderingTechniqueBit::kAllRt))
  333. {
  334. if(!m_gpuSceneRenderableAabbRt.isValid())
  335. {
  336. m_gpuSceneRenderableAabbRt.allocate();
  337. }
  338. const U32 bucketIdx = 0;
  339. const GpuSceneRenderableBoundingVolume gpuVolume =
  340. initGpuSceneRenderableBoundingVolume(aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz(), m_gpuSceneRenderable.getIndex(), bucketIdx);
  341. m_gpuSceneRenderableAabbRt.uploadToGpuScene(gpuVolume);
  342. }
  343. else
  344. {
  345. m_gpuSceneRenderableAabbRt.free();
  346. }
  347. }
  348. }
  349. } // end namespace anki