DebugRendererImp.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Renderer/DebugRendererImp.h>
  5. #include <Renderer/Renderer.h>
  6. #include <Renderer/RenderPrimitive.h>
  7. #include <Renderer/Texture.h>
  8. #include <Renderer/Font.h>
  9. #ifndef JPH_DEBUG_RENDERER
  10. // Hack to still compile DebugRenderer inside the test framework when Jolt is compiled without
  11. #define JPH_DEBUG_RENDERER
  12. #include <Jolt/Renderer/DebugRenderer.cpp>
  13. #undef JPH_DEBUG_RENDERER
  14. #endif // !JPH_DEBUG_RENDERER
  15. DebugRendererImp::DebugRendererImp(Renderer *inRenderer, const Font *inFont) :
  16. mRenderer(inRenderer),
  17. mFont(inFont)
  18. {
  19. // Create input layout for lines
  20. const D3D12_INPUT_ELEMENT_DESC line_vertex_desc[] =
  21. {
  22. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  23. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  24. };
  25. // Lines
  26. ComPtr<ID3DBlob> vtx_line = mRenderer->CreateVertexShader("Assets/Shaders/LineVertexShader.hlsl");
  27. ComPtr<ID3DBlob> pix_line = mRenderer->CreatePixelShader("Assets/Shaders/LinePixelShader.hlsl");
  28. mLineState = mRenderer->CreatePipelineState(vtx_line.Get(), line_vertex_desc, ARRAYSIZE(line_vertex_desc), pix_line.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  29. // Create input layout for triangles
  30. const D3D12_INPUT_ELEMENT_DESC triangles_vertex_desc[] =
  31. {
  32. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  33. { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  34. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  35. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 32, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  36. { "INSTANCE_TRANSFORM", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  37. { "INSTANCE_TRANSFORM", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  38. { "INSTANCE_TRANSFORM", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  39. { "INSTANCE_TRANSFORM", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 48, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  40. { "INSTANCE_INV_TRANSFORM", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 64, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  41. { "INSTANCE_INV_TRANSFORM", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 80, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  42. { "INSTANCE_INV_TRANSFORM", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 96, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  43. { "INSTANCE_INV_TRANSFORM", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 112, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  44. { "INSTANCE_COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 128, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  45. };
  46. // Triangles
  47. ComPtr<ID3DBlob> vtx_triangle = mRenderer->CreateVertexShader("Assets/Shaders/TriangleVertexShader.hlsl");
  48. ComPtr<ID3DBlob> pix_triangle = mRenderer->CreatePixelShader("Assets/Shaders/TrianglePixelShader.hlsl");
  49. mTriangleStateBF = mRenderer->CreatePipelineState(vtx_triangle.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_triangle.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  50. mTriangleStateFF = mRenderer->CreatePipelineState(vtx_triangle.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_triangle.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::FrontFace);
  51. mTriangleStateWire = mRenderer->CreatePipelineState(vtx_triangle.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_triangle.Get(), D3D12_FILL_MODE_WIREFRAME, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  52. // Shadow pass
  53. ComPtr<ID3DBlob> vtx_shadow = mRenderer->CreateVertexShader("Assets/Shaders/TriangleDepthVertexShader.hlsl");
  54. ComPtr<ID3DBlob> pix_shadow = mRenderer->CreatePixelShader("Assets/Shaders/TriangleDepthPixelShader.hlsl");
  55. mShadowStateBF = mRenderer->CreatePipelineState(vtx_shadow.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_shadow.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  56. mShadowStateFF = mRenderer->CreatePipelineState(vtx_shadow.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_shadow.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::FrontFace);
  57. mShadowStateWire = mRenderer->CreatePipelineState(vtx_shadow.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_shadow.Get(), D3D12_FILL_MODE_WIREFRAME, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  58. // Create depth only texture (no color buffer, as seen from light)
  59. mDepthTexture = mRenderer->CreateRenderTarget(4096, 4096);
  60. // Create instances buffer
  61. for (uint n = 0; n < Renderer::cFrameCount; ++n)
  62. mInstancesBuffer[n] = new RenderInstances(mRenderer);
  63. // Create empty batch
  64. Vertex empty_vertex { Float3(0, 0, 0), Float3(1, 0, 0), Float2(0, 0), Color::sWhite };
  65. uint32 empty_indices[] = { 0, 0, 0 };
  66. mEmptyBatch = CreateTriangleBatch(&empty_vertex, 1, empty_indices, 3);
  67. // Initialize base class
  68. DebugRenderer::Initialize();
  69. }
  70. void DebugRendererImp::DrawLine(RVec3Arg inFrom, RVec3Arg inTo, ColorArg inColor)
  71. {
  72. RVec3 offset = mRenderer->GetBaseOffset();
  73. Line line;
  74. Vec3(inFrom - offset).StoreFloat3(&line.mFrom);
  75. line.mFromColor = inColor;
  76. Vec3(inTo - offset).StoreFloat3(&line.mTo);
  77. line.mToColor = inColor;
  78. lock_guard lock(mLinesLock);
  79. mLines.push_back(line);
  80. }
  81. DebugRenderer::Batch DebugRendererImp::CreateTriangleBatch(const Triangle *inTriangles, int inTriangleCount)
  82. {
  83. if (inTriangles == nullptr || inTriangleCount == 0)
  84. return mEmptyBatch;
  85. BatchImpl *primitive = new BatchImpl(mRenderer, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  86. primitive->CreateVertexBuffer(3 * inTriangleCount, sizeof(Vertex), inTriangles);
  87. return primitive;
  88. }
  89. DebugRenderer::Batch DebugRendererImp::CreateTriangleBatch(const Vertex *inVertices, int inVertexCount, const uint32 *inIndices, int inIndexCount)
  90. {
  91. if (inVertices == nullptr || inVertexCount == 0 || inIndices == nullptr || inIndexCount == 0)
  92. return mEmptyBatch;
  93. BatchImpl *primitive = new BatchImpl(mRenderer, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  94. primitive->CreateVertexBuffer(inVertexCount, sizeof(Vertex), inVertices);
  95. primitive->CreateIndexBuffer(inIndexCount, inIndices);
  96. return primitive;
  97. }
  98. void DebugRendererImp::DrawGeometry(RMat44Arg inModelMatrix, const AABox &inWorldSpaceBounds, float inLODScaleSq, ColorArg inModelColor, const GeometryRef &inGeometry, ECullMode inCullMode, ECastShadow inCastShadow, EDrawMode inDrawMode)
  99. {
  100. lock_guard lock(mPrimitivesLock);
  101. RVec3 offset = mRenderer->GetBaseOffset();
  102. Mat44 model_matrix = inModelMatrix.PostTranslated(-offset).ToMat44();
  103. AABox world_space_bounds = inWorldSpaceBounds;
  104. world_space_bounds.Translate(Vec3(-offset));
  105. // Our pixel shader uses alpha only to turn on/off shadows
  106. Color color = inCastShadow == ECastShadow::On? Color(inModelColor, 255) : Color(inModelColor, 0);
  107. if (inDrawMode == EDrawMode::Wireframe)
  108. {
  109. mWireframePrimitives[inGeometry].mInstances.push_back({ model_matrix, model_matrix.GetDirectionPreservingMatrix(), color, world_space_bounds, inLODScaleSq });
  110. ++mNumInstances;
  111. }
  112. else
  113. {
  114. if (inCullMode != ECullMode::CullFrontFace)
  115. {
  116. mPrimitives[inGeometry].mInstances.push_back({ model_matrix, model_matrix.GetDirectionPreservingMatrix(), color, world_space_bounds, inLODScaleSq });
  117. ++mNumInstances;
  118. }
  119. if (inCullMode != ECullMode::CullBackFace)
  120. {
  121. mPrimitivesBackFacing[inGeometry].mInstances.push_back({ model_matrix, model_matrix.GetDirectionPreservingMatrix(), color, world_space_bounds, inLODScaleSq });
  122. ++mNumInstances;
  123. }
  124. }
  125. }
  126. void DebugRendererImp::FinalizePrimitive()
  127. {
  128. JPH_PROFILE_FUNCTION();
  129. if (mLockedPrimitive != nullptr)
  130. {
  131. BatchImpl *primitive = static_cast<BatchImpl *>(mLockedPrimitive.GetPtr());
  132. // Unlock the primitive
  133. primitive->UnlockVertexBuffer();
  134. // Set number of indices to draw
  135. primitive->SetNumVtxToDraw(int(mLockedVertices - mLockedVerticesStart));
  136. // Add to draw list
  137. mTempPrimitives[new Geometry(mLockedPrimitive, mLockedPrimitiveBounds)].mInstances.push_back({ Mat44::sIdentity(), Mat44::sIdentity(), Color::sWhite, mLockedPrimitiveBounds, 1.0f });
  138. ++mNumInstances;
  139. // Clear pointers
  140. mLockedPrimitive = nullptr;
  141. mLockedVerticesStart = nullptr;
  142. mLockedVertices = nullptr;
  143. mLockedVerticesEnd = nullptr;
  144. mLockedPrimitiveBounds = AABox();
  145. }
  146. }
  147. void DebugRendererImp::EnsurePrimitiveSpace(int inVtxSize)
  148. {
  149. const int cVertexBufferSize = 10240;
  150. if (mLockedPrimitive == nullptr
  151. || mLockedVerticesEnd - mLockedVertices < inVtxSize)
  152. {
  153. FinalizePrimitive();
  154. // Create new
  155. BatchImpl *primitive = new BatchImpl(mRenderer, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  156. primitive->CreateVertexBuffer(cVertexBufferSize, sizeof(Vertex));
  157. mLockedPrimitive = primitive;
  158. // Lock buffers
  159. mLockedVerticesStart = mLockedVertices = (Vertex *)primitive->LockVertexBuffer();
  160. mLockedVerticesEnd = mLockedVertices + cVertexBufferSize;
  161. }
  162. }
  163. void DebugRendererImp::DrawTriangle(RVec3Arg inV1, RVec3Arg inV2, RVec3Arg inV3, ColorArg inColor)
  164. {
  165. RVec3 offset = mRenderer->GetBaseOffset();
  166. Vec3 v1(inV1 - offset);
  167. Vec3 v2(inV2 - offset);
  168. Vec3 v3(inV3 - offset);
  169. lock_guard lock(mPrimitivesLock);
  170. EnsurePrimitiveSpace(3);
  171. // Set alpha to zero to tell our pixel shader to not cast shadows for this triangle
  172. // this is because our algorithm only renders shadows for backfacing triangles and this
  173. // triangle doesn't have one
  174. Color color(inColor, 0);
  175. // Construct triangle
  176. new ((Triangle *)mLockedVertices) Triangle(v1, v2, v3, color);
  177. mLockedVertices += 3;
  178. // Update bounding box
  179. mLockedPrimitiveBounds.Encapsulate(v1);
  180. mLockedPrimitiveBounds.Encapsulate(v2);
  181. mLockedPrimitiveBounds.Encapsulate(v3);
  182. }
  183. void DebugRendererImp::DrawInstances(const Geometry *inGeometry, const Array<int> &inStartIdx)
  184. {
  185. RenderInstances *instances_buffer = mInstancesBuffer[mRenderer->GetCurrentFrameIndex()];
  186. if (!inStartIdx.empty())
  187. {
  188. // Get LODs
  189. const Array<LOD> &geometry_lods = inGeometry->mLODs;
  190. // Write instances for all LODS
  191. int next_start_idx = inStartIdx.front();
  192. for (size_t lod = 0; lod < geometry_lods.size(); ++lod)
  193. {
  194. int start_idx = next_start_idx;
  195. next_start_idx = inStartIdx[lod + 1];
  196. int num_instances = next_start_idx - start_idx;
  197. instances_buffer->Draw(static_cast<BatchImpl *>(geometry_lods[lod].mTriangleBatch.GetPtr()), start_idx, num_instances);
  198. }
  199. }
  200. }
  201. void DebugRendererImp::DrawText3D(RVec3Arg inPosition, const string_view &inString, ColorArg inColor, float inHeight)
  202. {
  203. RVec3 offset = mRenderer->GetBaseOffset();
  204. Vec3 pos(inPosition - offset);
  205. lock_guard lock(mTextsLock);
  206. mTexts.emplace_back(pos, inString, inColor, inHeight);
  207. }
  208. void DebugRendererImp::DrawLines()
  209. {
  210. JPH_PROFILE_FUNCTION();
  211. lock_guard lock(mLinesLock);
  212. // Draw the lines
  213. if (!mLines.empty())
  214. {
  215. RenderPrimitive primitive(mRenderer, D3D_PRIMITIVE_TOPOLOGY_LINELIST);
  216. primitive.CreateVertexBuffer((int)mLines.size() * 2, sizeof(Line) / 2);
  217. void *data = primitive.LockVertexBuffer();
  218. memcpy(data, &mLines[0], mLines.size() * sizeof(Line));
  219. primitive.UnlockVertexBuffer();
  220. mLineState->Activate();
  221. primitive.Draw();
  222. }
  223. }
  224. void DebugRendererImp::DrawTriangles()
  225. {
  226. JPH_PROFILE_FUNCTION();
  227. lock_guard lock(mPrimitivesLock);
  228. // Finish the last primitive
  229. FinalizePrimitive();
  230. // Render to shadow map texture first
  231. mRenderer->SetRenderTarget(mDepthTexture);
  232. // Clear the shadow map texture to max depth
  233. mDepthTexture->ClearRenderTarget();
  234. // Get the camera and light frustum for culling
  235. Vec3 camera_pos(mRenderer->GetCameraState().mPos - mRenderer->GetBaseOffset());
  236. const Frustum &camera_frustum = mRenderer->GetCameraFrustum();
  237. const Frustum &light_frustum = mRenderer->GetLightFrustum();
  238. // Resize instances buffer and copy all visible instance data into it
  239. if (mNumInstances > 0)
  240. {
  241. // Create instances buffer
  242. RenderInstances *instances_buffer = mInstancesBuffer[mRenderer->GetCurrentFrameIndex()];
  243. instances_buffer->CreateBuffer(2 * mNumInstances, sizeof(Instance));
  244. Instance *dst_instance = reinterpret_cast<Instance *>(instances_buffer->Lock());
  245. // Next write index
  246. int dst_index = 0;
  247. // This keeps track of which instances use which lod, first array: 0 = light pass, 1 = geometry pass
  248. Array<Array<int>> lod_indices[2];
  249. for (InstanceMap *primitive_map : { &mPrimitives, &mTempPrimitives, &mPrimitivesBackFacing, &mWireframePrimitives })
  250. for (InstanceMap::value_type &v : *primitive_map)
  251. {
  252. // Get LODs
  253. const Array<LOD> &geometry_lods = v.first->mLODs;
  254. size_t num_lods = geometry_lods.size();
  255. JPH_ASSERT(num_lods > 0);
  256. // Ensure that our lod index array is big enough (to avoid reallocating memory too often)
  257. if (lod_indices[0].size() < num_lods)
  258. lod_indices[0].resize(num_lods);
  259. if (lod_indices[1].size() < num_lods)
  260. lod_indices[1].resize(num_lods);
  261. // Iterate over all instances
  262. const Array<InstanceWithLODInfo> &instances = v.second.mInstances;
  263. for (size_t i = 0; i < instances.size(); ++i)
  264. {
  265. const InstanceWithLODInfo &src_instance = instances[i];
  266. // Check if it overlaps with the light or camera frustum
  267. bool light_overlaps = light_frustum.Overlaps(src_instance.mWorldSpaceBounds);
  268. bool camera_overlaps = camera_frustum.Overlaps(src_instance.mWorldSpaceBounds);
  269. if (light_overlaps || camera_overlaps)
  270. {
  271. // Figure out which LOD to use
  272. float dist_sq = src_instance.mWorldSpaceBounds.GetSqDistanceTo(camera_pos);
  273. for (size_t lod = 0; lod < num_lods; ++lod)
  274. if (dist_sq <= src_instance.mLODScaleSq * Square(geometry_lods[lod].mDistance))
  275. {
  276. // Store which index goes in which LOD
  277. if (light_overlaps)
  278. lod_indices[0][lod].push_back((int)i);
  279. if (camera_overlaps)
  280. lod_indices[1][lod].push_back((int)i);
  281. break;
  282. }
  283. }
  284. }
  285. // Loop over both passes: 0 = light, 1 = geometry
  286. Array<int> *start_idx[] = { &v.second.mLightStartIdx, &v.second.mGeometryStartIdx };
  287. for (int type = 0; type < 2; ++type)
  288. {
  289. // Reserve space for instance indices
  290. Array<int> &type_start_idx = *start_idx[type];
  291. type_start_idx.resize(num_lods + 1);
  292. // Write out geometry pass instances
  293. for (size_t lod = 0; lod < num_lods; ++lod)
  294. {
  295. // Write start index for this LOD
  296. type_start_idx[lod] = dst_index;
  297. // Copy instances
  298. Array<int> &this_lod_indices = lod_indices[type][lod];
  299. for (int i : this_lod_indices)
  300. {
  301. const Instance &src_instance = instances[i];
  302. dst_instance[dst_index++] = src_instance;
  303. }
  304. // Prepare for next iteration (will preserve memory)
  305. this_lod_indices.clear();
  306. }
  307. // Write out end of last LOD
  308. type_start_idx.back() = dst_index;
  309. }
  310. }
  311. instances_buffer->Unlock();
  312. }
  313. if (!mPrimitives.empty() || !mTempPrimitives.empty())
  314. {
  315. // Front face culling, we want to render the back side of the geometry for casting shadows
  316. mShadowStateFF->Activate();
  317. // Draw all primitives as seen from the light
  318. if (mNumInstances > 0)
  319. for (InstanceMap::value_type &v : mPrimitives)
  320. DrawInstances(v.first, v.second.mLightStartIdx);
  321. for (InstanceMap::value_type &v : mTempPrimitives)
  322. DrawInstances(v.first, v.second.mLightStartIdx);
  323. }
  324. if (!mPrimitivesBackFacing.empty())
  325. {
  326. // Back face culling, we want to render the front side of back facing geometry
  327. mShadowStateBF->Activate();
  328. // Draw all primitives as seen from the light
  329. for (InstanceMap::value_type &v : mPrimitivesBackFacing)
  330. DrawInstances(v.first, v.second.mLightStartIdx);
  331. }
  332. if (!mWireframePrimitives.empty())
  333. {
  334. // Switch to wireframe mode
  335. mShadowStateWire->Activate();
  336. // Draw all wireframe primitives as seen from the light
  337. for (InstanceMap::value_type &v : mWireframePrimitives)
  338. DrawInstances(v.first, v.second.mLightStartIdx);
  339. }
  340. // Switch to the main render target
  341. mRenderer->SetRenderTarget(nullptr);
  342. // Bind the shadow map texture
  343. mDepthTexture->Bind(2);
  344. if (!mPrimitives.empty() || !mTempPrimitives.empty())
  345. {
  346. // Bind the normal shader, back face culling
  347. mTriangleStateBF->Activate();
  348. // Draw all primitives
  349. if (mNumInstances > 0)
  350. for (InstanceMap::value_type &v : mPrimitives)
  351. DrawInstances(v.first, v.second.mGeometryStartIdx);
  352. for (InstanceMap::value_type &v : mTempPrimitives)
  353. DrawInstances(v.first, v.second.mGeometryStartIdx);
  354. }
  355. if (!mPrimitivesBackFacing.empty())
  356. {
  357. // Front face culling, the next batch needs to render inside out
  358. mTriangleStateFF->Activate();
  359. // Draw all back primitives
  360. for (InstanceMap::value_type &v : mPrimitivesBackFacing)
  361. DrawInstances(v.first, v.second.mGeometryStartIdx);
  362. }
  363. if (!mWireframePrimitives.empty())
  364. {
  365. // Wire frame mode
  366. mTriangleStateWire->Activate();
  367. // Draw all wireframe primitives
  368. for (InstanceMap::value_type &v : mWireframePrimitives)
  369. DrawInstances(v.first, v.second.mGeometryStartIdx);
  370. }
  371. }
  372. void DebugRendererImp::DrawTexts()
  373. {
  374. lock_guard lock(mTextsLock);
  375. JPH_PROFILE_FUNCTION();
  376. const CameraState &camera_state = mRenderer->GetCameraState();
  377. for (const Text &t : mTexts)
  378. {
  379. Vec3 forward = camera_state.mForward;
  380. Vec3 right = forward.Cross(camera_state.mUp).Normalized();
  381. Vec3 up = right.Cross(forward).Normalized();
  382. Mat44 transform(Vec4(right, 0), Vec4(up, 0), Vec4(forward, 0), Vec4(t.mPosition, 1));
  383. mFont->DrawText3D(transform * Mat44::sScale(t.mHeight), t.mText, t.mColor);
  384. }
  385. }
  386. void DebugRendererImp::Draw()
  387. {
  388. DrawLines();
  389. DrawTriangles();
  390. DrawTexts();
  391. }
  392. void DebugRendererImp::ClearLines()
  393. {
  394. lock_guard lock(mLinesLock);
  395. mLines.clear();
  396. }
  397. void DebugRendererImp::ClearMap(InstanceMap &ioInstances)
  398. {
  399. Array<GeometryRef> to_delete;
  400. for (InstanceMap::value_type &kv : ioInstances)
  401. {
  402. if (kv.second.mInstances.empty())
  403. to_delete.push_back(kv.first);
  404. else
  405. kv.second.mInstances.clear();
  406. }
  407. for (GeometryRef &b : to_delete)
  408. ioInstances.erase(b);
  409. }
  410. void DebugRendererImp::ClearTriangles()
  411. {
  412. lock_guard lock(mPrimitivesLock);
  413. // Close any primitive that's being built
  414. FinalizePrimitive();
  415. // Move primitives to draw back to the free list
  416. ClearMap(mWireframePrimitives);
  417. ClearMap(mPrimitives);
  418. mTempPrimitives.clear(); // These are created by FinalizePrimitive() and need to be cleared every frame
  419. ClearMap(mPrimitivesBackFacing);
  420. mNumInstances = 0;
  421. }
  422. void DebugRendererImp::ClearTexts()
  423. {
  424. lock_guard lock(mTextsLock);
  425. mTexts.clear();
  426. }
  427. void DebugRendererImp::Clear()
  428. {
  429. ClearLines();
  430. ClearTriangles();
  431. ClearTexts();
  432. }