VertexBuffer.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 "common/config.h"
  23. #include <cstdlib>
  24. #include <cstring>
  25. #include <algorithm>
  26. #include <limits>
  27. // Conflicts with std::numeric_limits<GLushort>::max() (Windows).
  28. #ifdef max
  29. # undef max
  30. #endif
  31. namespace love
  32. {
  33. namespace graphics
  34. {
  35. namespace opengl
  36. {
  37. // VertexBuffer
  38. VertexBuffer *VertexBuffer::Create(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  39. {
  40. return new VertexBuffer(size, target, usage, backing);
  41. }
  42. VertexBuffer::VertexBuffer(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  43. : is_bound(false)
  44. , is_mapped(false)
  45. , size(size)
  46. , target(target)
  47. , usage(usage)
  48. , backing(backing)
  49. , vbo(0)
  50. , memory_map(0)
  51. , is_dirty(true)
  52. {
  53. if (getMemoryBacking() == BACKING_FULL)
  54. memory_map = malloc(getSize());
  55. bool ok = load(false);
  56. if (!ok)
  57. {
  58. free(memory_map);
  59. throw love::Exception("Could not load VBO.");
  60. }
  61. }
  62. VertexBuffer::~VertexBuffer()
  63. {
  64. if (vbo != 0)
  65. unload(false);
  66. if (memory_map)
  67. free(memory_map);
  68. }
  69. void *VertexBuffer::map()
  70. {
  71. if (is_mapped)
  72. return memory_map;
  73. if (!memory_map)
  74. {
  75. memory_map = malloc(getSize());
  76. if (!memory_map)
  77. throw love::Exception("Out of memory (oh the humanity!)");
  78. }
  79. if (is_dirty)
  80. {
  81. glGetBufferSubData(getTarget(), 0, (GLsizeiptr) getSize(), memory_map);
  82. is_dirty = false;
  83. }
  84. is_mapped = true;
  85. return memory_map;
  86. }
  87. void VertexBuffer::unmap()
  88. {
  89. if (!is_mapped)
  90. return;
  91. // VBO::bind is a no-op when the VBO is mapped, so we have to make sure it's
  92. // bound here.
  93. if (!is_bound)
  94. {
  95. glBindBuffer(getTarget(), vbo);
  96. is_bound = true;
  97. }
  98. // "orphan" current buffer to avoid implicit synchronisation on the GPU:
  99. // http://www.seas.upenn.edu/~pcozzi/OpenGLInsights/OpenGLInsights-AsynchronousBufferTransfers.pdf
  100. glBufferData(getTarget(), (GLsizeiptr) getSize(), NULL, getUsage());
  101. glBufferData(getTarget(), (GLsizeiptr) getSize(), memory_map, getUsage());
  102. is_mapped = false;
  103. }
  104. void VertexBuffer::bind()
  105. {
  106. if (!is_mapped)
  107. {
  108. glBindBuffer(getTarget(), vbo);
  109. is_bound = true;
  110. }
  111. }
  112. void VertexBuffer::unbind()
  113. {
  114. if (is_bound)
  115. glBindBuffer(getTarget(), 0);
  116. is_bound = false;
  117. }
  118. void VertexBuffer::fill(size_t offset, size_t size, const void *data)
  119. {
  120. if (is_mapped || getMemoryBacking() == BACKING_FULL)
  121. memcpy(static_cast<char *>(memory_map) + offset, data, size);
  122. if (!is_mapped)
  123. {
  124. // Not all systems have access to some faster paths...
  125. if (GLEE_APPLE_flush_buffer_range)
  126. {
  127. void *mapdata = glMapBuffer(getTarget(), GL_WRITE_ONLY);
  128. if (mapdata)
  129. {
  130. // We specified in VBO::load that we'll do manual flushing.
  131. // Now we tell the driver it only needs to deal with the data
  132. // we changed.
  133. memcpy(static_cast<char *>(mapdata) + offset, data, size);
  134. glFlushMappedBufferRangeAPPLE(getTarget(), (GLintptr) offset, (GLsizei) size);
  135. }
  136. glUnmapBuffer(getTarget());
  137. }
  138. else
  139. {
  140. // Fall back to a possibly slower SubData (more chance of syncing.)
  141. glBufferSubData(getTarget(), (GLintptr) offset, (GLsizeiptr) size, data);
  142. }
  143. if (getMemoryBacking() != BACKING_FULL)
  144. is_dirty = true;
  145. }
  146. }
  147. const void *VertexBuffer::getPointer(size_t offset) const
  148. {
  149. return BUFFER_OFFSET(offset);
  150. }
  151. bool VertexBuffer::loadVolatile()
  152. {
  153. return load(true);
  154. }
  155. void VertexBuffer::unloadVolatile()
  156. {
  157. unload(true);
  158. }
  159. bool VertexBuffer::load(bool restore)
  160. {
  161. glGenBuffers(1, &vbo);
  162. VertexBuffer::Bind bind(*this);
  163. // Copy the old buffer only if 'restore' was requested.
  164. const GLvoid *src = restore ? memory_map : 0;
  165. while (GL_NO_ERROR != glGetError())
  166. /* clear error messages */;
  167. // We don't want to flush the entire buffer when we just modify a small
  168. // portion of it (VBO::fill without VBO::map), so we'll handle the flushing
  169. // ourselves when we can.
  170. if (GLEE_APPLE_flush_buffer_range)
  171. glBufferParameteriAPPLE(getTarget(), GL_BUFFER_FLUSHING_UNMAP_APPLE, GL_FALSE);
  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. bool mapped = is_mapped;
  184. map(); // saves buffer content to memory_map.
  185. is_mapped = mapped;
  186. }
  187. glDeleteBuffers(1, &vbo);
  188. vbo = 0;
  189. }
  190. // VertexIndex
  191. size_t VertexIndex::maxSize = 0;
  192. size_t VertexIndex::elementSize = 0;
  193. std::list<size_t> VertexIndex::sizeRefs;
  194. VertexBuffer *VertexIndex::element_array = NULL;
  195. VertexIndex::VertexIndex(size_t size)
  196. : size(size)
  197. {
  198. // The upper limit is the maximum of GLuint divided by six (the number
  199. // of indices per size) and divided by the size of GLuint. This guarantees
  200. // no overflows when calculating the array size in bytes.
  201. // Memory issues will be handled by other exceptions.
  202. if (size == 0 || size > ((GLuint) -1) / 6 / sizeof(GLuint))
  203. throw love::Exception("Invalid size.");
  204. addSize(size);
  205. }
  206. VertexIndex::~VertexIndex()
  207. {
  208. removeSize(size);
  209. }
  210. size_t VertexIndex::getSize() const
  211. {
  212. return size;
  213. }
  214. size_t VertexIndex::getIndexCount(size_t elements) const
  215. {
  216. return elements * 6;
  217. }
  218. GLenum VertexIndex::getType(size_t s) const
  219. {
  220. // Calculates if unsigned short is big enough to hold all the vertex indices.
  221. static const GLenum type_table[] = {GL_UNSIGNED_SHORT, GL_UNSIGNED_INT};
  222. return type_table[s * 4 > std::numeric_limits<GLushort>::max()];
  223. // if buffer-size > max(GLushort) then GL_UNSIGNED_INT else GL_UNSIGNED_SHORT
  224. }
  225. size_t VertexIndex::getElementSize()
  226. {
  227. return elementSize;
  228. }
  229. VertexBuffer *VertexIndex::getVertexBuffer() const
  230. {
  231. return element_array;
  232. }
  233. const void *VertexIndex::getPointer(size_t offset) const
  234. {
  235. return element_array->getPointer(offset);
  236. }
  237. void VertexIndex::addSize(size_t newSize)
  238. {
  239. if (newSize <= maxSize)
  240. {
  241. // Current size is bigger. Append the size to list and sort.
  242. sizeRefs.push_back(newSize);
  243. sizeRefs.sort();
  244. return;
  245. }
  246. // Try to resize before adding it to the list because resize may throw.
  247. resize(newSize);
  248. sizeRefs.push_back(newSize);
  249. }
  250. void VertexIndex::removeSize(size_t oldSize)
  251. {
  252. // TODO: For debugging purposes, this should check if the size was actually found.
  253. sizeRefs.erase(std::find(sizeRefs.begin(), sizeRefs.end(), oldSize));
  254. if (sizeRefs.size() == 0)
  255. {
  256. resize(0);
  257. return;
  258. }
  259. if (oldSize == maxSize)
  260. {
  261. // Shrink if there's a smaller size.
  262. size_t newSize = sizeRefs.back();
  263. if (newSize < maxSize)
  264. resize(newSize);
  265. }
  266. }
  267. void VertexIndex::resize(size_t size)
  268. {
  269. if (size == 0)
  270. {
  271. delete element_array;
  272. element_array = NULL;
  273. maxSize = 0;
  274. return;
  275. }
  276. VertexBuffer *new_element_array;
  277. // Depending on the size, a switch to int and more memory is needed.
  278. GLenum target_type = getType(size);
  279. size_t elem_size = (target_type == GL_UNSIGNED_SHORT) ? sizeof(GLushort) : sizeof(GLuint);
  280. size_t array_size = elem_size * 6 * size;
  281. // Create may throw out-of-memory exceptions.
  282. // VertexIndex will propagate the exception and keep the old VertexBuffer.
  283. try
  284. {
  285. new_element_array = VertexBuffer::Create(array_size, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW);
  286. }
  287. catch (std::bad_alloc &)
  288. {
  289. throw love::Exception("Out of memory.");
  290. }
  291. // Allocation of the new VertexBuffer succeeded.
  292. // The old VertexBuffer can now be deleted.
  293. delete element_array;
  294. element_array = new_element_array;
  295. maxSize = size;
  296. elementSize = elem_size;
  297. switch (target_type)
  298. {
  299. case GL_UNSIGNED_SHORT:
  300. fill<GLushort>();
  301. break;
  302. case GL_UNSIGNED_INT:
  303. fill<GLuint>();
  304. break;
  305. }
  306. }
  307. template <typename T>
  308. void VertexIndex::fill()
  309. {
  310. VertexBuffer::Bind bind(*element_array);
  311. VertexBuffer::Mapper mapper(*element_array);
  312. T *indices = (T *) mapper.get();
  313. for (size_t i = 0; i < maxSize; ++i)
  314. {
  315. indices[i*6+0] = i * 4 + 0;
  316. indices[i*6+1] = i * 4 + 1;
  317. indices[i*6+2] = i * 4 + 2;
  318. indices[i*6+3] = i * 4 + 0;
  319. indices[i*6+4] = i * 4 + 2;
  320. indices[i*6+5] = i * 4 + 3;
  321. }
  322. }
  323. } // opengl
  324. } // graphics
  325. } // love