OpenGL.h 12 KB

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