VertexBuffer.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /**
  2. * Copyright (c) 2006-2014 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "VertexBuffer.h"
  21. #include "common/Exception.h"
  22. #include <cstdlib>
  23. #include <cstring>
  24. #include <algorithm>
  25. #include <limits>
  26. namespace love
  27. {
  28. namespace graphics
  29. {
  30. namespace opengl
  31. {
  32. // VertexBuffer
  33. VertexBuffer *VertexBuffer::Create(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  34. {
  35. return new VertexBuffer(size, target, usage, backing);
  36. }
  37. VertexBuffer::VertexBuffer(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  38. : is_bound(false)
  39. , is_mapped(false)
  40. , size(size)
  41. , target(target)
  42. , usage(usage)
  43. , backing(backing)
  44. , vbo(0)
  45. , memory_map(nullptr)
  46. , is_dirty(false)
  47. {
  48. if (getMemoryBacking() == BACKING_FULL)
  49. memory_map = (char *) malloc(getSize());
  50. bool ok = load(false);
  51. if (!ok)
  52. {
  53. free(memory_map);
  54. throw love::Exception("Could not load VBO.");
  55. }
  56. }
  57. VertexBuffer::~VertexBuffer()
  58. {
  59. if (vbo != 0)
  60. unload(false);
  61. if (memory_map)
  62. free(memory_map);
  63. }
  64. void *VertexBuffer::map()
  65. {
  66. if (is_mapped)
  67. return memory_map;
  68. if (!memory_map)
  69. {
  70. memory_map = (char *) malloc(getSize());
  71. if (!memory_map)
  72. throw love::Exception("Out of memory (oh the humanity!)");
  73. }
  74. if (is_dirty)
  75. {
  76. glGetBufferSubData(getTarget(), 0, (GLsizeiptr) getSize(), memory_map);
  77. is_dirty = false;
  78. }
  79. is_mapped = true;
  80. return memory_map;
  81. }
  82. void VertexBuffer::unmapStatic(size_t offset, size_t size)
  83. {
  84. // Upload the mapped data to the buffer.
  85. glBufferSubData(getTarget(), (GLintptr) offset, (GLsizeiptr) size, memory_map + offset);
  86. }
  87. void VertexBuffer::unmapStream()
  88. {
  89. // "orphan" current buffer to avoid implicit synchronisation on the GPU:
  90. // http://www.seas.upenn.edu/~pcozzi/OpenGLInsights/OpenGLInsights-AsynchronousBufferTransfers.pdf
  91. glBufferData(getTarget(), (GLsizeiptr) getSize(), nullptr, getUsage());
  92. glBufferData(getTarget(), (GLsizeiptr) getSize(), memory_map, getUsage());
  93. }
  94. void VertexBuffer::unmap(size_t usedOffset, size_t usedSize)
  95. {
  96. if (!is_mapped)
  97. return;
  98. usedOffset = std::min(usedOffset, getSize());
  99. usedSize = std::min(usedSize, getSize() - usedOffset);
  100. // VBO::bind is a no-op when the VBO is mapped, so we have to make sure it's
  101. // bound here.
  102. if (!is_bound)
  103. {
  104. glBindBuffer(getTarget(), vbo);
  105. is_bound = true;
  106. }
  107. switch (getUsage())
  108. {
  109. case GL_STATIC_DRAW:
  110. unmapStatic(usedOffset, usedSize);
  111. break;
  112. case GL_STREAM_DRAW:
  113. unmapStream();
  114. break;
  115. case GL_DYNAMIC_DRAW:
  116. default:
  117. // It's probably more efficient to treat it like a streaming buffer if
  118. // more than a third of its contents have been modified during the map().
  119. if (usedSize >= getSize() / 3)
  120. unmapStream();
  121. else
  122. unmapStatic(usedOffset, usedSize);
  123. break;
  124. }
  125. is_mapped = false;
  126. }
  127. void VertexBuffer::bind()
  128. {
  129. if (!is_mapped)
  130. {
  131. glBindBuffer(getTarget(), vbo);
  132. is_bound = true;
  133. }
  134. }
  135. void VertexBuffer::unbind()
  136. {
  137. if (is_bound)
  138. glBindBuffer(getTarget(), 0);
  139. is_bound = false;
  140. }
  141. void VertexBuffer::fill(size_t offset, size_t size, const void *data)
  142. {
  143. if (is_mapped || getMemoryBacking() == BACKING_FULL)
  144. memcpy(memory_map + offset, data, size);
  145. if (!is_mapped)
  146. {
  147. glBufferSubData(getTarget(), (GLintptr) offset, (GLsizeiptr) size, data);
  148. if (getMemoryBacking() != BACKING_FULL)
  149. is_dirty = true;
  150. }
  151. }
  152. const void *VertexBuffer::getPointer(size_t offset) const
  153. {
  154. return BUFFER_OFFSET(offset);
  155. }
  156. bool VertexBuffer::loadVolatile()
  157. {
  158. return load(true);
  159. }
  160. void VertexBuffer::unloadVolatile()
  161. {
  162. unload(true);
  163. }
  164. bool VertexBuffer::load(bool restore)
  165. {
  166. glGenBuffers(1, &vbo);
  167. VertexBuffer::Bind bind(*this);
  168. // Copy the old buffer only if 'restore' was requested.
  169. const GLvoid *src = restore ? memory_map : nullptr;
  170. while (GL_NO_ERROR != glGetError())
  171. /* clear error messages */;
  172. // Note that if 'src' is '0', no data will be copied.
  173. glBufferData(getTarget(), (GLsizeiptr) getSize(), src, getUsage());
  174. GLenum err = glGetError();
  175. return (GL_NO_ERROR == err);
  176. }
  177. void VertexBuffer::unload(bool save)
  178. {
  179. // Save data before unloading, if we need to.
  180. if (save && getMemoryBacking() == BACKING_PARTIAL)
  181. {
  182. VertexBuffer::Bind bind(*this);
  183. map(); // saves buffer content to memory_map.
  184. }
  185. is_mapped = false;
  186. glDeleteBuffers(1, &vbo);
  187. vbo = 0;
  188. }
  189. // VertexIndex
  190. size_t VertexIndex::maxSize = 0;
  191. size_t VertexIndex::elementSize = 0;
  192. std::list<size_t> VertexIndex::sizeRefs;
  193. VertexBuffer *VertexIndex::element_array = NULL;
  194. VertexIndex::VertexIndex(size_t size)
  195. : size(size)
  196. {
  197. // The upper limit is the maximum of GLuint divided by six (the number
  198. // of indices per size) and divided by the size of GLuint. This guarantees
  199. // no overflows when calculating the array size in bytes.
  200. // Memory issues will be handled by other exceptions.
  201. if (size == 0 || size > ((GLuint) -1) / 6 / sizeof(GLuint))
  202. throw love::Exception("Invalid size.");
  203. addSize(size);
  204. }
  205. VertexIndex::VertexIndex(const VertexIndex &other)
  206. : size(other.size)
  207. {
  208. addSize(size);
  209. }
  210. VertexIndex &VertexIndex::operator = (const VertexIndex &other)
  211. {
  212. addSize(other.size);
  213. removeSize(size);
  214. size = other.size;
  215. return *this;
  216. }
  217. VertexIndex::~VertexIndex()
  218. {
  219. removeSize(size);
  220. }
  221. size_t VertexIndex::getSize() const
  222. {
  223. return size;
  224. }
  225. size_t VertexIndex::getIndexCount(size_t elements) const
  226. {
  227. return elements * 6;
  228. }
  229. GLenum VertexIndex::getType(size_t s) const
  230. {
  231. // Calculates if unsigned short is big enough to hold all the vertex indices.
  232. static const GLenum type_table[] = {GL_UNSIGNED_SHORT, GL_UNSIGNED_INT};
  233. return type_table[s * 4 > std::numeric_limits<GLushort>::max()];
  234. // if buffer-size > max(GLushort) then GL_UNSIGNED_INT else GL_UNSIGNED_SHORT
  235. }
  236. size_t VertexIndex::getElementSize()
  237. {
  238. return elementSize;
  239. }
  240. VertexBuffer *VertexIndex::getVertexBuffer() const
  241. {
  242. return element_array;
  243. }
  244. const void *VertexIndex::getPointer(size_t offset) const
  245. {
  246. return element_array->getPointer(offset);
  247. }
  248. void VertexIndex::addSize(size_t newSize)
  249. {
  250. if (newSize <= maxSize)
  251. {
  252. // Current size is bigger. Append the size to list and sort.
  253. sizeRefs.push_back(newSize);
  254. sizeRefs.sort();
  255. return;
  256. }
  257. // Try to resize before adding it to the list because resize may throw.
  258. resize(newSize);
  259. sizeRefs.push_back(newSize);
  260. }
  261. void VertexIndex::removeSize(size_t oldSize)
  262. {
  263. // TODO: For debugging purposes, this should check if the size was actually found.
  264. sizeRefs.erase(std::find(sizeRefs.begin(), sizeRefs.end(), oldSize));
  265. if (sizeRefs.size() == 0)
  266. {
  267. resize(0);
  268. return;
  269. }
  270. if (oldSize == maxSize)
  271. {
  272. // Shrink if there's a smaller size.
  273. size_t newSize = sizeRefs.back();
  274. if (newSize < maxSize)
  275. resize(newSize);
  276. }
  277. }
  278. void VertexIndex::resize(size_t size)
  279. {
  280. if (size == 0)
  281. {
  282. delete element_array;
  283. element_array = NULL;
  284. maxSize = 0;
  285. return;
  286. }
  287. VertexBuffer *new_element_array;
  288. // Depending on the size, a switch to int and more memory is needed.
  289. GLenum target_type = getType(size);
  290. size_t elem_size = (target_type == GL_UNSIGNED_SHORT) ? sizeof(GLushort) : sizeof(GLuint);
  291. size_t array_size = elem_size * 6 * size;
  292. // Create may throw out-of-memory exceptions.
  293. // VertexIndex will propagate the exception and keep the old VertexBuffer.
  294. try
  295. {
  296. new_element_array = VertexBuffer::Create(array_size, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW);
  297. }
  298. catch (std::bad_alloc &)
  299. {
  300. throw love::Exception("Out of memory.");
  301. }
  302. // Allocation of the new VertexBuffer succeeded.
  303. // The old VertexBuffer can now be deleted.
  304. delete element_array;
  305. element_array = new_element_array;
  306. maxSize = size;
  307. elementSize = elem_size;
  308. switch (target_type)
  309. {
  310. case GL_UNSIGNED_SHORT:
  311. fill<GLushort>();
  312. break;
  313. case GL_UNSIGNED_INT:
  314. fill<GLuint>();
  315. break;
  316. }
  317. }
  318. template <typename T>
  319. void VertexIndex::fill()
  320. {
  321. VertexBuffer::Bind bind(*element_array);
  322. VertexBuffer::Mapper mapper(*element_array);
  323. T *indices = (T *) mapper.get();
  324. for (size_t i = 0; i < maxSize; ++i)
  325. {
  326. indices[i*6+0] = i * 4 + 0;
  327. indices[i*6+1] = i * 4 + 1;
  328. indices[i*6+2] = i * 4 + 2;
  329. indices[i*6+3] = i * 4 + 0;
  330. indices[i*6+4] = i * 4 + 2;
  331. indices[i*6+5] = i * 4 + 3;
  332. }
  333. }
  334. } // opengl
  335. } // graphics
  336. } // love