persistent_buffer_example.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "persistent_buffer.h"
  2. PersistentRingBuffer<CylinderInstanceGpu> m_cylinderPersistentBuffer;
  3. void Backend::initializeCylinderPipeline() {
  4. const std::size_t initialCapacity = 10000;
  5. if (m_cylinderPersistentBuffer.initialize(initialCapacity, 3)) {
  6. qDebug() << "Persistent cylinder buffer initialized";
  7. } else {
  8. qWarning()
  9. << "Failed to init persistent buffer, falling back to old method";
  10. }
  11. }
  12. void Backend::beginFrame() {
  13. if (m_cylinderPersistentBuffer.isValid()) {
  14. m_cylinderPersistentBuffer.beginFrame();
  15. }
  16. }
  17. void Backend::uploadCylinderInstances(std::size_t count) {
  18. if (count == 0)
  19. return;
  20. if (m_cylinderPersistentBuffer.isValid()) {
  21. if (count > m_cylinderPersistentBuffer.capacity()) {
  22. qWarning() << "Too many cylinders:" << count
  23. << "max:" << m_cylinderPersistentBuffer.capacity();
  24. count = m_cylinderPersistentBuffer.capacity();
  25. }
  26. m_cylinderPersistentBuffer.write(m_cylinderScratch.data(), count);
  27. glBindBuffer(GL_ARRAY_BUFFER, m_cylinderPersistentBuffer.buffer());
  28. return;
  29. }
  30. if (!m_cylinderInstanceBuffer)
  31. return;
  32. glBindBuffer(GL_ARRAY_BUFFER, m_cylinderInstanceBuffer);
  33. if (count > m_cylinderInstanceCapacity) {
  34. m_cylinderInstanceCapacity = std::max<std::size_t>(
  35. count,
  36. m_cylinderInstanceCapacity ? m_cylinderInstanceCapacity * 2 : count);
  37. glBufferData(GL_ARRAY_BUFFER,
  38. m_cylinderInstanceCapacity * sizeof(CylinderInstanceGpu),
  39. nullptr, GL_DYNAMIC_DRAW);
  40. m_cylinderScratch.reserve(m_cylinderInstanceCapacity);
  41. }
  42. glBufferSubData(GL_ARRAY_BUFFER, 0, count * sizeof(CylinderInstanceGpu),
  43. m_cylinderScratch.data());
  44. glBindBuffer(GL_ARRAY_BUFFER, 0);
  45. }
  46. void Backend::drawCylinders(std::size_t count) {
  47. if (!m_cylinderVao || m_cylinderIndexCount == 0 || count == 0)
  48. return;
  49. initializeOpenGLFunctions();
  50. glBindVertexArray(m_cylinderVao);
  51. glDrawElementsInstanced(GL_TRIANGLES, m_cylinderIndexCount, GL_UNSIGNED_INT,
  52. nullptr, static_cast<GLsizei>(count));
  53. glBindVertexArray(0);
  54. }
  55. void Backend::shutdownCylinderPipeline() {
  56. m_cylinderPersistentBuffer.destroy();
  57. }