BufferObject.cpp 1.8 KB

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