RenderInstancesMTL.mm 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2025 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Renderer/MTL/RenderInstancesMTL.h>
  6. #include <Renderer/MTL/RenderPrimitiveMTL.h>
  7. void RenderInstancesMTL::Clear()
  8. {
  9. [mBuffer release];
  10. mBuffer = nil;
  11. }
  12. void RenderInstancesMTL::CreateBuffer(int inNumInstances, int inInstanceSize)
  13. {
  14. mInstanceSize = NSUInteger(inInstanceSize);
  15. NSUInteger size = mInstanceSize * inNumInstances;
  16. if (mBuffer == nullptr || mBufferSize < size)
  17. {
  18. Clear();
  19. mBuffer = [mRenderer->GetView().device newBufferWithLength: size options: MTLResourceCPUCacheModeDefaultCache | MTLResourceStorageModeShared | MTLResourceHazardTrackingModeTracked];
  20. mBufferSize = size;
  21. }
  22. }
  23. void *RenderInstancesMTL::Lock()
  24. {
  25. return mBuffer.contents;
  26. }
  27. void RenderInstancesMTL::Unlock()
  28. {
  29. }
  30. void RenderInstancesMTL::Draw(RenderPrimitive *inPrimitive, int inStartInstance, int inNumInstances) const
  31. {
  32. if (inNumInstances <= 0)
  33. return;
  34. id<MTLRenderCommandEncoder> encoder = mRenderer->GetRenderEncoder();
  35. RenderPrimitiveMTL *prim = static_cast<RenderPrimitiveMTL *>(inPrimitive);
  36. [encoder setVertexBuffer: prim->mVertexBuffer offset: 0 atIndex: 0];
  37. [encoder setVertexBuffer: mBuffer offset: mInstanceSize * inStartInstance atIndex: 1];
  38. if (prim->mIndexBuffer == nil)
  39. [encoder drawPrimitives: prim->mPrimitiveType vertexStart: 0 vertexCount: prim->mNumVtxToDraw instanceCount: inNumInstances];
  40. else
  41. [encoder drawIndexedPrimitives: prim->mPrimitiveType indexCount: prim->mNumIdxToDraw indexType: MTLIndexTypeUInt32 indexBuffer: prim->mIndexBuffer indexBufferOffset: 0 instanceCount: inNumInstances];
  42. }