BufferObject.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <cstring>
  2. #include "anki/gl/BufferObject.h"
  3. #include "anki/gl/GlException.h"
  4. #include "anki/util/Exception.h"
  5. namespace anki {
  6. //==============================================================================
  7. const thread_local BufferObject* BufferObject::lastBindedBo = nullptr;
  8. //==============================================================================
  9. BufferObject::~BufferObject()
  10. {
  11. if(isCreated())
  12. {
  13. destroy();
  14. }
  15. }
  16. //==============================================================================
  17. void BufferObject::create(GLenum target_, uint sizeInBytes_,
  18. const void* dataPtr, GLenum usage_)
  19. {
  20. ANKI_ASSERT(!isCreated());
  21. ANKI_ASSERT(usage_ == GL_STREAM_DRAW
  22. || usage_ == GL_STATIC_DRAW
  23. || usage_ == GL_DYNAMIC_DRAW);
  24. ANKI_ASSERT(sizeInBytes_ > 0 && "Unacceptable sizeInBytes");
  25. usage = usage_;
  26. target = target_;
  27. sizeInBytes = sizeInBytes_;
  28. glGenBuffers(1, &glId);
  29. bind();
  30. glBufferData(target, sizeInBytes, dataPtr, usage);
  31. // make a check
  32. int bufferSize = 0;
  33. glGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize);
  34. if(sizeInBytes != (uint)bufferSize)
  35. {
  36. destroy();
  37. throw ANKI_EXCEPTION("Data size mismatch");
  38. }
  39. unbind();
  40. ANKI_CHECK_GL_ERROR();
  41. }
  42. //==============================================================================
  43. void BufferObject::write(void* buff)
  44. {
  45. ANKI_ASSERT(isCreated());
  46. ANKI_ASSERT(usage != GL_STATIC_DRAW);
  47. bind();
  48. void* mapped = glMapBuffer(target, GL_WRITE_ONLY);
  49. memcpy(mapped, buff, sizeInBytes);
  50. glUnmapBuffer(target);
  51. unbind();
  52. }
  53. //==============================================================================
  54. void BufferObject::write(void* buff, size_t offset, size_t size)
  55. {
  56. ANKI_ASSERT(isCreated());
  57. ANKI_ASSERT(usage != GL_STATIC_DRAW);
  58. ANKI_ASSERT(offset + size <= sizeInBytes);
  59. bind();
  60. void* mapped = glMapBufferRange(target, offset, size, GL_MAP_WRITE_BIT);
  61. memcpy(mapped, buff, size);
  62. glUnmapBuffer(target);
  63. unbind();
  64. }
  65. } // end namespace