OpenGL.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /**
  2. * Copyright (c) 2006-2016 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. #ifndef LOVE_GRAPHICS_OPENGL_OPENGL_H
  21. #define LOVE_GRAPHICS_OPENGL_OPENGL_H
  22. // LOVE
  23. #include "common/config.h"
  24. #include "common/int.h"
  25. #include "graphics/Color.h"
  26. #include "graphics/Texture.h"
  27. #include "common/Matrix.h"
  28. // GLAD
  29. #include "libraries/glad/gladfuncs.hpp"
  30. // C++
  31. #include <vector>
  32. #include <stack>
  33. // The last argument to AttribPointer takes a buffer offset casted to a pointer.
  34. #define BUFFER_OFFSET(i) ((char *) NULL + (i))
  35. namespace love
  36. {
  37. namespace graphics
  38. {
  39. namespace opengl
  40. {
  41. // Awful, but the library uses the namespace in order to use the functions sanely
  42. // with proper autocomplete in IDEs while having name mangling safety -
  43. // no clashes with other GL libraries when linking, etc.
  44. using namespace glad;
  45. // Vertex attribute indices used in shaders by LOVE. The values map to OpenGL
  46. // generic vertex attribute indices.
  47. enum VertexAttribID
  48. {
  49. ATTRIB_POS = 0,
  50. ATTRIB_TEXCOORD,
  51. ATTRIB_COLOR,
  52. ATTRIB_CONSTANTCOLOR,
  53. ATTRIB_MAX_ENUM
  54. };
  55. enum VertexAttribFlags
  56. {
  57. ATTRIBFLAG_POS = 1 << ATTRIB_POS,
  58. ATTRIBFLAG_TEXCOORD = 1 << ATTRIB_TEXCOORD,
  59. ATTRIBFLAG_COLOR = 1 << ATTRIB_COLOR,
  60. ATTRIBFLAG_CONSTANTCOLOR = 1 << ATTRIB_CONSTANTCOLOR
  61. };
  62. enum BufferType
  63. {
  64. BUFFER_VERTEX = 0,
  65. BUFFER_INDEX,
  66. BUFFER_MAX_ENUM
  67. };
  68. /**
  69. * Thin layer between OpenGL and the rest of the program.
  70. * Internally shadows some OpenGL context state for improved efficiency and
  71. * accuracy (compared to glGet etc.)
  72. * A class is more convenient and readable than plain namespaced functions, but
  73. * typically only one OpenGL object should be used (singleton.)
  74. **/
  75. class OpenGL
  76. {
  77. public:
  78. // OpenGL GPU vendors.
  79. enum Vendor
  80. {
  81. VENDOR_AMD,
  82. VENDOR_NVIDIA,
  83. VENDOR_INTEL,
  84. VENDOR_MESA_SOFT, // Software renderer.
  85. VENDOR_APPLE, // Software renderer on desktops.
  86. VENDOR_MICROSOFT, // Software renderer.
  87. VENDOR_IMGTEC,
  88. VENDOR_ARM,
  89. VENDOR_QUALCOMM,
  90. VENDOR_BROADCOM,
  91. VENDOR_VIVANTE,
  92. VENDOR_UNKNOWN
  93. };
  94. // A rectangle representing an OpenGL viewport or a scissor box.
  95. struct Viewport
  96. {
  97. int x, y;
  98. int w, h;
  99. bool operator == (const Viewport &rhs) const
  100. {
  101. return x == rhs.x && y == rhs.y && w == rhs.w && h == rhs.h;
  102. }
  103. };
  104. struct
  105. {
  106. std::vector<Matrix4> transform;
  107. std::vector<Matrix4> projection;
  108. } matrices;
  109. class TempTransform
  110. {
  111. public:
  112. TempTransform(OpenGL &gl)
  113. : gl(gl)
  114. {
  115. gl.pushTransform();
  116. }
  117. ~TempTransform()
  118. {
  119. gl.popTransform();
  120. }
  121. Matrix4 &get()
  122. {
  123. return gl.getTransform();
  124. }
  125. private:
  126. OpenGL &gl;
  127. };
  128. class TempDebugGroup
  129. {
  130. public:
  131. #if defined(LOVE_IOS)
  132. TempDebugGroup(const char *name)
  133. {
  134. if (GLAD_EXT_debug_marker)
  135. glPushGroupMarkerEXT(0, (const GLchar *) name);
  136. }
  137. #else
  138. TempDebugGroup(const char *) {}
  139. #endif
  140. #if defined(LOVE_IOS)
  141. ~TempDebugGroup()
  142. {
  143. if (GLAD_EXT_debug_marker)
  144. glPopGroupMarkerEXT();
  145. }
  146. #endif
  147. };
  148. struct Stats
  149. {
  150. size_t textureMemory;
  151. int drawCalls;
  152. int framebufferBinds;
  153. int shaderSwitches;
  154. } stats;
  155. struct Bugs
  156. {
  157. /**
  158. * On AMD's Windows (and probably Linux) drivers,
  159. * glBindFramebuffer + glClear + glBindFramebuffer + draw(fbo_tex) won't
  160. * work unless there's some kind of draw or state change which causes
  161. * the driver to update the texture's contents (just drawing the texture
  162. * won't always do it, with this driver bug).
  163. * Activating shader program 0 and then activating the actual program
  164. * seems to always 'fix' it for me.
  165. * Bug observed January 2016 with multiple AMD GPUs and driver versions.
  166. * https://love2d.org/forums/viewtopic.php?f=4&t=81496
  167. **/
  168. bool clearRequiresDriverTextureStateUpdate;
  169. /**
  170. * AMD's Windows drivers don't always properly generate mipmaps unless
  171. * glEnable(GL_TEXTURE_2D) is called directly before glGenerateMipmap.
  172. * This only applies to legacy and Compatibility Profile contexts, of
  173. * course.
  174. * https://www.opengl.org/wiki/Common_Mistakes#Automatic_mipmap_generation
  175. **/
  176. bool generateMipmapsRequiresTexture2DEnable;
  177. /**
  178. * Other bugs which have workarounds that don't use conditional code at
  179. * the moment:
  180. *
  181. * Kepler nvidia GPUs in at least OS X 10.10 and 10.11 fail to render
  182. * geometry with glDrawElements if index data comes from a Buffer Object
  183. * and vertex data doesn't. One workaround is to use a CPU-side index
  184. * array when there's also a CPU-side vertex array.
  185. * https://love2d.org/forums/viewtopic.php?f=4&t=81401&start=10
  186. *
  187. * Some android drivers don't seem to initialize the sampler index
  188. * values of sampler uniforms in shaders to 0 (which is required by the
  189. * GLSL ES specification) when linking the shader program. One
  190. * workaround is to always set the values of said sampler uniforms to 0
  191. * just after linking the shader program.
  192. * https://love2d.org/forums/viewtopic.php?f=4&t=81458
  193. **/
  194. } bugs;
  195. OpenGL();
  196. /**
  197. * Initializes the active OpenGL context.
  198. **/
  199. bool initContext();
  200. /**
  201. * Sets up some required context state based on current and default OpenGL
  202. * state. Call this directly after initializing an OpenGL context!
  203. **/
  204. void setupContext();
  205. /**
  206. * Marks current context state as invalid and deletes OpenGL objects owned
  207. * by this class instance. Call this directly before potentially deleting
  208. * an OpenGL context!
  209. **/
  210. void deInitContext();
  211. void pushTransform();
  212. void popTransform();
  213. Matrix4 &getTransform();
  214. /**
  215. * Set up necessary state (LOVE-provided shader uniforms, etc.) for drawing.
  216. * This *MUST* be called directly before OpenGL drawing functions.
  217. **/
  218. void prepareDraw();
  219. /**
  220. * State-tracked glBindBuffer.
  221. * NOTE: This does not account for multiple VAOs being used! Index buffer
  222. * bindings are per-VAO in OpenGL, but this doesn't know about that.
  223. **/
  224. void bindBuffer(BufferType type, GLuint buffer);
  225. /**
  226. * glDeleteBuffers which updates our shadowed state.
  227. **/
  228. void deleteBuffer(GLuint buffer);
  229. /**
  230. * glDrawArrays and glDrawElements which increment the draw-call counter by
  231. * themselves.
  232. **/
  233. void drawArrays(GLenum mode, GLint first, GLsizei count);
  234. void drawElements(GLenum mode, GLsizei count, GLenum type, const void *indices);
  235. /**
  236. * Sets the enabled vertex attribute arrays based on the specified attribute
  237. * bits. Each bit in the uint32 represents an enabled attribute array index.
  238. * For example, useVertexAttribArrays(1 << 0) will enable attribute index 0.
  239. * See the VertexAttribFlags enum for the standard vertex attributes.
  240. * This function *must* be used instead of glEnable/DisableVertexAttribArray.
  241. **/
  242. void useVertexAttribArrays(uint32 arraybits);
  243. /**
  244. * Sets the OpenGL rendering viewport to the specified rectangle.
  245. * The y-coordinate starts at the top.
  246. **/
  247. void setViewport(const Viewport &v);
  248. /**
  249. * Gets the current OpenGL rendering viewport rectangle.
  250. **/
  251. Viewport getViewport() const;
  252. /**
  253. * Sets the scissor box to the specified rectangle.
  254. * The y-coordinate starts at the top and is flipped internally.
  255. **/
  256. void setScissor(const Viewport &v);
  257. /**
  258. * Gets the current scissor box (regardless of whether scissoring is enabled.)
  259. **/
  260. Viewport getScissor() const;
  261. /**
  262. * Sets the global point size.
  263. **/
  264. void setPointSize(float size);
  265. /**
  266. * Gets the global point size.
  267. **/
  268. float getPointSize() const;
  269. /**
  270. * Calls glEnable/glDisable(GL_FRAMEBUFFER_SRGB).
  271. **/
  272. void setFramebufferSRGB(bool enable);
  273. /**
  274. * Equivalent to glIsEnabled(GL_FRAMEBUFFER_SRGB).
  275. **/
  276. bool hasFramebufferSRGB() const;
  277. /**
  278. * Binds a Framebuffer Object to the specified target.
  279. **/
  280. void bindFramebuffer(GLenum target, GLuint framebuffer);
  281. /**
  282. * Calls glUseProgram.
  283. **/
  284. void useProgram(GLuint program);
  285. /**
  286. * This will usually be 0 (system drawable), but some platforms require a
  287. * non-zero FBO for rendering.
  288. **/
  289. GLuint getDefaultFBO() const;
  290. /**
  291. * Gets the ID for love's default texture (used for "untextured" primitives.)
  292. **/
  293. GLuint getDefaultTexture() const;
  294. /**
  295. * Helper for setting the active texture unit.
  296. *
  297. * @param textureunit Index in the range of [0, maxtextureunits-1]
  298. **/
  299. void setTextureUnit(int textureunit);
  300. /**
  301. * Helper for binding a texture to a specific texture unit.
  302. *
  303. * @param textureunit Index in the range of [0, maxtextureunits-1]
  304. * @param restoreprev Restore previously bound texture unit when done.
  305. **/
  306. void bindTextureToUnit(GLuint texture, int textureunit, bool restoreprev);
  307. /**
  308. * Helper for deleting an OpenGL texture.
  309. * Cleans up if the texture is currently bound.
  310. **/
  311. void deleteTexture(GLuint texture);
  312. /**
  313. * Sets the texture filter mode for the currently bound texture.
  314. * The anisotropy parameter of the argument is set to the actual amount of
  315. * anisotropy that was used.
  316. **/
  317. void setTextureFilter(graphics::Texture::Filter &f);
  318. /**
  319. * Sets the texture wrap mode for the currently bound texture.
  320. **/
  321. void setTextureWrap(const graphics::Texture::Wrap &w);
  322. bool isClampZeroTextureWrapSupported() const;
  323. /**
  324. * Returns the maximum supported width or height of a texture.
  325. **/
  326. int getMaxTextureSize() const;
  327. /**
  328. * Returns the maximum supported number of simultaneous render targets.
  329. **/
  330. int getMaxRenderTargets() const;
  331. /**
  332. * Returns the maximum supported number of MSAA samples for renderbuffers.
  333. **/
  334. int getMaxRenderbufferSamples() const;
  335. /**
  336. * Returns the maximum number of accessible texture units.
  337. **/
  338. int getMaxTextureUnits() const;
  339. /**
  340. * Returns the maximum point size.
  341. **/
  342. float getMaxPointSize() const;
  343. void updateTextureMemorySize(size_t oldsize, size_t newsize);
  344. /**
  345. * Get the GPU vendor of this OpenGL context.
  346. **/
  347. Vendor getVendor() const;
  348. static GLenum getGLBufferType(BufferType type);
  349. static GLint getGLWrapMode(Texture::WrapMode wmode);
  350. static const char *errorString(GLenum errorcode);
  351. // Get human-readable strings for debug info.
  352. static const char *debugSeverityString(GLenum severity);
  353. static const char *debugSourceString(GLenum source);
  354. static const char *debugTypeString(GLenum type);
  355. private:
  356. void initVendor();
  357. void initOpenGLFunctions();
  358. void initMaxValues();
  359. void initMatrices();
  360. void createDefaultTexture();
  361. bool contextInitialized;
  362. float maxAnisotropy;
  363. int maxTextureSize;
  364. int maxRenderTargets;
  365. int maxRenderbufferSamples;
  366. int maxTextureUnits;
  367. float maxPointSize;
  368. Vendor vendor;
  369. // Tracked OpenGL state.
  370. struct
  371. {
  372. GLuint boundBuffers[BUFFER_MAX_ENUM];
  373. // Texture unit state (currently bound texture for each texture unit.)
  374. std::vector<GLuint> boundTextures;
  375. // Currently active texture unit.
  376. int curTextureUnit;
  377. uint32 enabledAttribArrays;
  378. Viewport viewport;
  379. Viewport scissor;
  380. float pointSize;
  381. bool framebufferSRGBEnabled;
  382. GLuint defaultTexture;
  383. Matrix4 lastProjectionMatrix;
  384. Matrix4 lastTransformMatrix;
  385. } state;
  386. }; // OpenGL
  387. // OpenGL class instance singleton.
  388. extern OpenGL gl;
  389. } // opengl
  390. } // graphics
  391. } // love
  392. #endif // LOVE_GRAPHICS_OPENGL_OPENGL_H