BsGLTimerQuery.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsGLTimerQuery.h"
  4. #include "BsGLCommandBuffer.h"
  5. #include "Math/BsMath.h"
  6. #include "Profiling/BsRenderStats.h"
  7. namespace bs { namespace ct
  8. {
  9. GLTimerQuery::GLTimerQuery(UINT32 deviceIdx)
  10. :mQueryStartObj(0), mQueryEndObj(0), mFinalized(false), mEndIssued(false), mTimeDelta(0.0f)
  11. {
  12. assert(deviceIdx == 0 && "Multiple GPUs not supported natively on OpenGL.");
  13. GLuint queries[2];
  14. glGenQueries(2, queries);
  15. mQueryStartObj = queries[0];
  16. mQueryEndObj = queries[1];
  17. BS_INC_RENDER_STAT_CAT(ResCreated, RenderStatObject_Query);
  18. }
  19. GLTimerQuery::~GLTimerQuery()
  20. {
  21. GLuint queries[2];
  22. queries[0] = mQueryStartObj;
  23. queries[1] = mQueryEndObj;
  24. glDeleteQueries(2, queries);
  25. BS_INC_RENDER_STAT_CAT(ResDestroyed, RenderStatObject_Query);
  26. }
  27. void GLTimerQuery::begin(const SPtr<CommandBuffer>& cb)
  28. {
  29. auto execute = [&]()
  30. {
  31. glQueryCounter(mQueryStartObj, GL_TIMESTAMP);
  32. setActive(true);
  33. mEndIssued = false;
  34. };
  35. if (cb == nullptr)
  36. execute();
  37. else
  38. {
  39. SPtr<GLCommandBuffer> glCB = std::static_pointer_cast<GLCommandBuffer>(cb);
  40. glCB->queueCommand(execute);
  41. }
  42. }
  43. void GLTimerQuery::end(const SPtr<CommandBuffer>& cb)
  44. {
  45. auto execute = [&]()
  46. {
  47. glQueryCounter(mQueryEndObj, GL_TIMESTAMP);
  48. mEndIssued = true;
  49. mFinalized = false;
  50. };
  51. if (cb == nullptr)
  52. execute();
  53. else
  54. {
  55. SPtr<GLCommandBuffer> glCB = std::static_pointer_cast<GLCommandBuffer>(cb);
  56. glCB->queueCommand(execute);
  57. }
  58. }
  59. bool GLTimerQuery::isReady() const
  60. {
  61. if (!mEndIssued)
  62. return false;
  63. GLint done = 0;
  64. glGetQueryObjectiv(mQueryEndObj, GL_QUERY_RESULT_AVAILABLE, &done);
  65. return done == GL_TRUE;
  66. }
  67. float GLTimerQuery::getTimeMs()
  68. {
  69. if(!mFinalized && isReady())
  70. {
  71. finalize();
  72. }
  73. return mTimeDelta;
  74. }
  75. void GLTimerQuery::finalize()
  76. {
  77. mFinalized = true;
  78. GLuint64 timeStart;
  79. GLuint64 timeEnd;
  80. glGetQueryObjectui64v(mQueryStartObj, GL_QUERY_RESULT, &timeStart);
  81. glGetQueryObjectui64v(mQueryEndObj, GL_QUERY_RESULT, &timeEnd);
  82. mTimeDelta = (timeEnd - timeStart) / 1000000.0f;
  83. }
  84. }}