ModelNode.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright (C) 2009-2021, 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/ModelNode.h>
  6. #include <AnKi/Scene/SceneGraph.h>
  7. #include <AnKi/Scene/DebugDrawer.h>
  8. #include <AnKi/Scene/Components/MoveComponent.h>
  9. #include <AnKi/Scene/Components/SkinComponent.h>
  10. #include <AnKi/Scene/Components/SpatialComponent.h>
  11. #include <AnKi/Scene/Components/RenderComponent.h>
  12. #include <AnKi/Scene/Components/ModelComponent.h>
  13. #include <AnKi/Resource/ModelResource.h>
  14. #include <AnKi/Resource/ResourceManager.h>
  15. #include <AnKi/Resource/SkeletonResource.h>
  16. #include <AnKi/Physics/PhysicsWorld.h>
  17. namespace anki {
  18. /// Feedback component.
  19. class ModelNode::FeedbackComponent : public SceneComponent
  20. {
  21. ANKI_SCENE_COMPONENT(ModelNode::FeedbackComponent)
  22. public:
  23. FeedbackComponent(SceneNode* node)
  24. : SceneComponent(node, getStaticClassId(), true)
  25. {
  26. }
  27. ANKI_USE_RESULT Error update(SceneNode& node, Second prevTime, Second crntTime, Bool& updated) override
  28. {
  29. updated = false;
  30. static_cast<ModelNode&>(node).feedbackUpdate();
  31. return Error::NONE;
  32. }
  33. };
  34. ANKI_SCENE_COMPONENT_STATICS(ModelNode::FeedbackComponent)
  35. class ModelNode::RenderProxy
  36. {
  37. public:
  38. ModelNode* m_node = nullptr;
  39. };
  40. ModelNode::ModelNode(SceneGraph* scene, CString name)
  41. : SceneNode(scene, name)
  42. {
  43. newComponent<ModelComponent>();
  44. newComponent<SkinComponent>();
  45. newComponent<MoveComponent>();
  46. newComponent<FeedbackComponent>();
  47. newComponent<SpatialComponent>();
  48. newComponent<RenderComponent>(); // One of many
  49. m_renderProxies.create(getAllocator(), 1);
  50. }
  51. ModelNode::~ModelNode()
  52. {
  53. m_renderProxies.destroy(getAllocator());
  54. }
  55. void ModelNode::feedbackUpdate()
  56. {
  57. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  58. const SkinComponent& skinc = getFirstComponentOfType<SkinComponent>();
  59. const MoveComponent& movec = getFirstComponentOfType<MoveComponent>();
  60. if(!modelc.isEnabled())
  61. {
  62. // Disable everything
  63. ANKI_ASSERT(!"TODO");
  64. return;
  65. }
  66. const Timestamp globTimestamp = getGlobalTimestamp();
  67. Bool updateSpatial = false;
  68. // Model update
  69. if(modelc.getTimestamp() == globTimestamp)
  70. {
  71. m_aabbLocal = modelc.getModelResource()->getBoundingVolume();
  72. updateSpatial = true;
  73. if(modelc.getModelResource()->getModelPatches().getSize() == countComponentsOfType<RenderComponent>())
  74. {
  75. // Easy, just re-init the render components
  76. initRenderComponents();
  77. }
  78. else
  79. {
  80. // Need to create more render components, can't do it at the moment, deffer it
  81. m_deferredRenderComponentUpdate = true;
  82. }
  83. }
  84. // Skin update
  85. if(skinc.isEnabled() && skinc.getTimestamp() == globTimestamp)
  86. {
  87. m_aabbLocal = skinc.getBoneBoundingVolumeLocalSpace();
  88. updateSpatial = true;
  89. }
  90. // Move update
  91. if(movec.getTimestamp() == globTimestamp)
  92. {
  93. getFirstComponentOfType<SpatialComponent>().setSpatialOrigin(movec.getWorldTransform().getOrigin().xyz());
  94. updateSpatial = true;
  95. }
  96. // Spatial update
  97. if(updateSpatial)
  98. {
  99. const Aabb aabbWorld = m_aabbLocal.getTransformed(movec.getWorldTransform());
  100. getFirstComponentOfType<SpatialComponent>().setAabbWorldSpace(aabbWorld);
  101. }
  102. }
  103. Error ModelNode::frameUpdate(Second prevUpdateTime, Second crntTime)
  104. {
  105. if(ANKI_LIKELY(!m_deferredRenderComponentUpdate))
  106. {
  107. return Error::NONE;
  108. }
  109. m_deferredRenderComponentUpdate = false;
  110. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  111. const U32 modelPatchCount = modelc.getModelResource()->getModelPatches().getSize();
  112. const U32 renderComponentCount = countComponentsOfType<RenderComponent>();
  113. if(modelPatchCount > renderComponentCount)
  114. {
  115. const U32 diff = modelPatchCount - renderComponentCount;
  116. for(U32 i = 0; i < diff; ++i)
  117. {
  118. newComponent<RenderComponent>();
  119. }
  120. m_renderProxies.resize(getAllocator(), modelPatchCount);
  121. }
  122. else
  123. {
  124. ANKI_ASSERT(!"TODO");
  125. }
  126. ANKI_ASSERT(countComponentsOfType<RenderComponent>() == modelPatchCount);
  127. // Now you can init the render components
  128. initRenderComponents();
  129. return Error::NONE;
  130. }
  131. void ModelNode::initRenderComponents()
  132. {
  133. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  134. const ModelResourcePtr& model = modelc.getModelResource();
  135. ANKI_ASSERT(modelc.getModelResource()->getModelPatches().getSize() == countComponentsOfType<RenderComponent>());
  136. ANKI_ASSERT(modelc.getModelResource()->getModelPatches().getSize() == m_renderProxies.getSize());
  137. for(U32 patchIdx = 0; patchIdx < model->getModelPatches().getSize(); ++patchIdx)
  138. {
  139. RenderComponent& rc = getNthComponentOfType<RenderComponent>(patchIdx);
  140. rc.initRaster(
  141. [](RenderQueueDrawContext& ctx, ConstWeakArray<void*> userData) {
  142. const RenderProxy& proxy = *static_cast<const RenderProxy*>(userData[0]);
  143. const U32 modelPatchIdx = U32(&proxy - &proxy.m_node->m_renderProxies[0]);
  144. proxy.m_node->draw(ctx, userData, modelPatchIdx);
  145. },
  146. &m_renderProxies[patchIdx], modelc.getRenderMergeKeys()[patchIdx]);
  147. rc.setFlagsFromMaterial(model->getModelPatches()[patchIdx].getMaterial());
  148. if(model->getModelPatches()[patchIdx].getSupportedRayTracingTypes() != RayTypeBit::NONE)
  149. {
  150. rc.initRayTracing(
  151. [](U32 lod, const void* userData, RayTracingInstanceQueueElement& el) {
  152. const RenderProxy& proxy = *static_cast<const RenderProxy*>(userData);
  153. const U32 modelPatchIdx = U32(&proxy - &proxy.m_node->m_renderProxies[0]);
  154. proxy.m_node->setupRayTracingInstanceQueueElement(lod, modelPatchIdx, el);
  155. },
  156. &m_renderProxies[patchIdx]);
  157. }
  158. m_renderProxies[patchIdx].m_node = this;
  159. }
  160. }
  161. void ModelNode::draw(RenderQueueDrawContext& ctx, ConstWeakArray<void*> userData, U32 modelPatchIdx) const
  162. {
  163. const U32 instanceCount = userData.getSize();
  164. ANKI_ASSERT(instanceCount > 0 && instanceCount <= MAX_INSTANCE_COUNT);
  165. ANKI_ASSERT(ctx.m_key.getInstanceCount() == instanceCount);
  166. CommandBufferPtr& cmdb = ctx.m_commandBuffer;
  167. if(ANKI_LIKELY(!ctx.m_debugDraw))
  168. {
  169. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  170. const ModelPatch& patch = modelc.getModelResource()->getModelPatches()[modelPatchIdx];
  171. const SkinComponent& skinc = getFirstComponentOfType<SkinComponent>();
  172. // Transforms
  173. Array<Mat4, MAX_INSTANCE_COUNT> trfs;
  174. Array<Mat4, MAX_INSTANCE_COUNT> prevTrfs;
  175. const MoveComponent& movec = getFirstComponentOfType<MoveComponent>();
  176. trfs[0] = Mat4(movec.getWorldTransform());
  177. prevTrfs[0] = Mat4(movec.getPreviousWorldTransform());
  178. Bool moved = trfs[0] != prevTrfs[0];
  179. for(U32 i = 1; i < instanceCount; ++i)
  180. {
  181. const ModelNode& otherNode = *static_cast<const RenderProxy*>(userData[i])->m_node;
  182. const U32 otherNodeModelPatchIdx =
  183. U32(static_cast<const RenderProxy*>(userData[i]) - &otherNode.m_renderProxies[0]);
  184. (void)otherNodeModelPatchIdx;
  185. ANKI_ASSERT(otherNodeModelPatchIdx == modelPatchIdx);
  186. const MoveComponent& otherNodeMovec = otherNode.getFirstComponentOfType<MoveComponent>();
  187. trfs[i] = Mat4(otherNodeMovec.getWorldTransform());
  188. prevTrfs[i] = Mat4(otherNodeMovec.getPreviousWorldTransform());
  189. moved = moved || (trfs[i] != prevTrfs[i]);
  190. }
  191. ctx.m_key.setVelocity(moved && ctx.m_key.getPass() == Pass::GB);
  192. ctx.m_key.setSkinned(skinc.isEnabled());
  193. ModelRenderingInfo modelInf;
  194. patch.getRenderingInfo(ctx.m_key, modelInf);
  195. // Bones storage
  196. if(skinc.isEnabled())
  197. {
  198. const U32 boneCount = skinc.getBoneTransforms().getSize();
  199. StagingGpuMemoryToken token, tokenPrev;
  200. void* trfs = ctx.m_stagingGpuAllocator->allocateFrame(boneCount * sizeof(Mat4),
  201. StagingGpuMemoryType::STORAGE, token);
  202. memcpy(trfs, &skinc.getBoneTransforms()[0], boneCount * sizeof(Mat4));
  203. trfs = ctx.m_stagingGpuAllocator->allocateFrame(boneCount * sizeof(Mat4), StagingGpuMemoryType::STORAGE,
  204. tokenPrev);
  205. memcpy(trfs, &skinc.getPreviousFrameBoneTransforms()[0], boneCount * sizeof(Mat4));
  206. ANKI_ASSERT(modelInf.m_boneTransformsBinding < MAX_U32);
  207. cmdb->bindStorageBuffer(patch.getMaterial()->getDescriptorSetIndex(), modelInf.m_boneTransformsBinding,
  208. token.m_buffer, token.m_offset, token.m_range);
  209. ANKI_ASSERT(modelInf.m_prevFrameBoneTransformsBinding < MAX_U32);
  210. cmdb->bindStorageBuffer(patch.getMaterial()->getDescriptorSetIndex(),
  211. modelInf.m_prevFrameBoneTransformsBinding, tokenPrev.m_buffer, tokenPrev.m_offset,
  212. tokenPrev.m_range);
  213. }
  214. // Program
  215. cmdb->bindShaderProgram(modelInf.m_program);
  216. // Uniforms
  217. RenderComponent::allocateAndSetupUniforms(
  218. modelc.getModelResource()->getModelPatches()[modelPatchIdx].getMaterial(), ctx,
  219. ConstWeakArray<Mat4>(&trfs[0], instanceCount), ConstWeakArray<Mat4>(&prevTrfs[0], instanceCount),
  220. *ctx.m_stagingGpuAllocator);
  221. // Set attributes
  222. for(U i = 0; i < modelInf.m_vertexAttributeCount; ++i)
  223. {
  224. const ModelVertexAttribute& attrib = modelInf.m_vertexAttributes[i];
  225. ANKI_ASSERT(attrib.m_format != Format::NONE);
  226. cmdb->setVertexAttribute(U32(attrib.m_location), attrib.m_bufferBinding, attrib.m_format,
  227. attrib.m_relativeOffset);
  228. }
  229. // Set vertex buffers
  230. for(U32 i = 0; i < modelInf.m_vertexBufferBindingCount; ++i)
  231. {
  232. const ModelVertexBufferBinding& binding = modelInf.m_vertexBufferBindings[i];
  233. cmdb->bindVertexBuffer(i, binding.m_buffer, binding.m_offset, binding.m_stride, VertexStepRate::VERTEX);
  234. }
  235. // Index buffer
  236. cmdb->bindIndexBuffer(modelInf.m_indexBuffer, modelInf.m_indexBufferOffset, IndexType::U16);
  237. // Draw
  238. cmdb->drawElements(PrimitiveTopology::TRIANGLES, modelInf.m_indexCount, instanceCount, modelInf.m_firstIndex, 0,
  239. 0);
  240. }
  241. else
  242. {
  243. // Draw the bounding volumes
  244. Mat4* const mvps = ctx.m_frameAllocator.newArray<Mat4>(instanceCount);
  245. for(U32 i = 0; i < instanceCount; ++i)
  246. {
  247. const ModelNode& otherNode = *static_cast<const RenderProxy*>(userData[i])->m_node;
  248. const Aabb& box = otherNode.getFirstComponentOfType<SpatialComponent>().getAabbWorldSpace();
  249. const Vec4 tsl = (box.getMin() + box.getMax()) / 2.0f;
  250. const Vec3 scale = (box.getMax().xyz() - box.getMin().xyz()) / 2.0f;
  251. // Set non uniform scale. Add a margin to avoid flickering
  252. Mat3 nonUniScale = Mat3::getZero();
  253. constexpr F32 MARGIN = 1.02f;
  254. nonUniScale(0, 0) = scale.x() * MARGIN;
  255. nonUniScale(1, 1) = scale.y() * MARGIN;
  256. nonUniScale(2, 2) = scale.z() * MARGIN;
  257. mvps[i] = ctx.m_viewProjectionMatrix * Mat4(tsl.xyz1(), Mat3::getIdentity() * nonUniScale, 1.0f);
  258. }
  259. const Bool enableDepthTest = ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DEPTH_TEST_ON);
  260. if(enableDepthTest)
  261. {
  262. cmdb->setDepthCompareOperation(CompareOperation::LESS);
  263. }
  264. else
  265. {
  266. cmdb->setDepthCompareOperation(CompareOperation::ALWAYS);
  267. }
  268. getSceneGraph().getDebugDrawer().drawCubes(
  269. ConstWeakArray<Mat4>(mvps, instanceCount), Vec4(1.0f, 0.0f, 1.0f, 1.0f), 2.0f,
  270. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), 2.0f,
  271. *ctx.m_stagingGpuAllocator, cmdb);
  272. ctx.m_frameAllocator.deleteArray(mvps, instanceCount);
  273. // Bones
  274. const SkinComponent& skinc = getFirstComponentOfType<SkinComponent>();
  275. if(skinc.isEnabled())
  276. {
  277. const SkinComponent& skinc = getComponentAt<SkinComponent>(0);
  278. SkeletonResourcePtr skeleton = skinc.getSkeleronResource();
  279. const U32 boneCount = skinc.getBoneTransforms().getSize();
  280. DynamicArrayAuto<Vec3> lines(ctx.m_frameAllocator);
  281. lines.resizeStorage(boneCount * 2);
  282. DynamicArrayAuto<Vec3> chidlessLines(ctx.m_frameAllocator);
  283. for(U32 i = 0; i < boneCount; ++i)
  284. {
  285. const Bone& bone = skeleton->getBones()[i];
  286. ANKI_ASSERT(bone.getIndex() == i);
  287. const Vec4 point(0.0f, 0.0f, 0.0f, 1.0f);
  288. const Bone* parent = bone.getParent();
  289. Mat4 m = (parent)
  290. ? skinc.getBoneTransforms()[parent->getIndex()] * parent->getVertexTransform().getInverse()
  291. : Mat4::getIdentity();
  292. const Vec3 a = (m * point).xyz();
  293. m = skinc.getBoneTransforms()[i] * bone.getVertexTransform().getInverse();
  294. const Vec3 b = (m * point).xyz();
  295. lines.emplaceBack(a);
  296. lines.emplaceBack(b);
  297. if(bone.getChildren().getSize() == 0)
  298. {
  299. // If there are not children try to draw something for that bone as well
  300. chidlessLines.emplaceBack(b);
  301. const F32 len = (b - a).getLength();
  302. const Vec3 c = b + (b - a).getNormalized() * len;
  303. chidlessLines.emplaceBack(c);
  304. }
  305. }
  306. const Mat4 mvp =
  307. ctx.m_viewProjectionMatrix * Mat4(getFirstComponentOfType<MoveComponent>().getWorldTransform());
  308. getSceneGraph().getDebugDrawer().drawLines(
  309. ConstWeakArray<Mat4>(&mvp, 1), Vec4(1.0f), 20.0f,
  310. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), lines,
  311. *ctx.m_stagingGpuAllocator, cmdb);
  312. getSceneGraph().getDebugDrawer().drawLines(
  313. ConstWeakArray<Mat4>(&mvp, 1), Vec4(0.7f, 0.7f, 0.7f, 1.0f), 5.0f,
  314. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), chidlessLines,
  315. *ctx.m_stagingGpuAllocator, cmdb);
  316. }
  317. // Restore state
  318. if(!enableDepthTest)
  319. {
  320. cmdb->setDepthCompareOperation(CompareOperation::LESS);
  321. }
  322. }
  323. }
  324. void ModelNode::setupRayTracingInstanceQueueElement(U32 lod, U32 modelPatchIdx,
  325. RayTracingInstanceQueueElement& el) const
  326. {
  327. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  328. const ModelPatch& patch = modelc.getModelResource()->getModelPatches()[modelPatchIdx];
  329. ModelRayTracingInfo info;
  330. patch.getRayTracingInfo(lod, info);
  331. memset(&el, 0, sizeof(el));
  332. // AS
  333. el.m_bottomLevelAccelerationStructure = info.m_bottomLevelAccelerationStructure.get();
  334. // Set the descriptor
  335. el.m_modelDescriptor = info.m_descriptor;
  336. const MoveComponent& movec = getFirstComponentOfType<MoveComponent>();
  337. const Mat3x4 worldTrf(movec.getWorldTransform());
  338. memcpy(&el.m_modelDescriptor.m_worldTransform, &worldTrf, sizeof(worldTrf));
  339. el.m_modelDescriptor.m_worldRotation = movec.getWorldTransform().getRotation().getRotationPart();
  340. // Handles
  341. for(RayType type : EnumIterable<RayType>())
  342. {
  343. if(!!(patch.getMaterial()->getSupportedRayTracingTypes() & RayTypeBit(1 << type)))
  344. {
  345. el.m_shaderGroupHandleIndices[type] = info.m_shaderGroupHandleIndices[type];
  346. }
  347. else
  348. {
  349. el.m_shaderGroupHandleIndices[type] = MAX_U32;
  350. }
  351. }
  352. // References
  353. ANKI_ASSERT(info.m_grObjectReferenceCount <= el.m_grObjects.getSize());
  354. el.m_grObjectCount = info.m_grObjectReferenceCount;
  355. for(U32 i = 0; i < info.m_grObjectReferenceCount; ++i)
  356. {
  357. el.m_grObjects[i] = info.m_grObjectReferences[i].get();
  358. }
  359. }
  360. } // end namespace anki