Canvas.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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 "Canvas.h"
  21. #include "Image.h"
  22. #include "Graphics.h"
  23. #include "common/Matrix.h"
  24. #include "common/config.h"
  25. #include <cstring> // For memcpy
  26. #include <limits>
  27. namespace love
  28. {
  29. namespace graphics
  30. {
  31. namespace opengl
  32. {
  33. // strategy for fbo creation, interchangable at runtime:
  34. // none, opengl >= 3.0, extensions
  35. struct FramebufferStrategy
  36. {
  37. virtual ~FramebufferStrategy() {}
  38. /// create a new framebuffer and texture
  39. /**
  40. * @param[out] framebuffer Framebuffer name
  41. * @param[in] texture Texture name
  42. * @return Creation status
  43. */
  44. virtual GLenum createFBO(GLuint &, GLuint)
  45. {
  46. return GL_FRAMEBUFFER_UNSUPPORTED;
  47. }
  48. /// Create a stencil buffer and attach it to the active framebuffer object
  49. /**
  50. * @param[in] width Width of the stencil buffer
  51. * @param[in] height Height of the stencil buffer
  52. * @param[in] samples Number of samples to use
  53. * @param[out] stencil Name for stencil buffer
  54. * @return Whether the stencil buffer was successfully created
  55. **/
  56. virtual bool createStencil(int, int, int, GLuint &)
  57. {
  58. return false;
  59. }
  60. /// Create a MSAA renderbuffer and attach it to the active FBO.
  61. /**
  62. * @param[in] width Width of the MSAA buffer
  63. * @param[in] height Height of the MSAA buffer
  64. * @param[inout] samples Number of samples to use
  65. * @param[in] internalformat The internal format to use for the buffer
  66. * @param[out] buffer Name for the MSAA buffer
  67. * @return Whether the MSAA buffer was successfully created and attached
  68. **/
  69. virtual bool createMSAABuffer(int, int, int &, GLenum, GLuint &)
  70. {
  71. return false;
  72. }
  73. /// remove objects
  74. /**
  75. * @param[in] framebuffer Framebuffer name
  76. * @param[in] depth_stencil Name for packed depth and stencil buffer
  77. */
  78. virtual void deleteFBO(GLuint, GLuint, GLuint) {}
  79. virtual void bindFBO(GLuint) {}
  80. /// attach additional canvases to the active framebuffer for rendering
  81. /**
  82. * @param[in] canvases List of canvases to attach
  83. **/
  84. virtual void setAttachments(const std::vector<Canvas *> &) {}
  85. /// stop using all additional attached canvases
  86. virtual void setAttachments() {}
  87. };
  88. struct FramebufferStrategyGL3 : public FramebufferStrategy
  89. {
  90. virtual GLenum createFBO(GLuint &framebuffer, GLuint texture)
  91. {
  92. // get currently bound fbo to reset to it later
  93. GLint current_fbo;
  94. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &current_fbo);
  95. // create framebuffer
  96. glGenFramebuffers(1, &framebuffer);
  97. glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
  98. if (texture != 0)
  99. {
  100. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
  101. GL_TEXTURE_2D, texture, 0);
  102. }
  103. // check status
  104. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  105. // unbind framebuffer
  106. glBindFramebuffer(GL_FRAMEBUFFER, (GLuint) current_fbo);
  107. return status;
  108. }
  109. virtual bool createStencil(int width, int height, int samples, GLuint &stencil)
  110. {
  111. // create combined depth/stencil buffer
  112. glDeleteRenderbuffers(1, &stencil);
  113. glGenRenderbuffers(1, &stencil);
  114. glBindRenderbuffer(GL_RENDERBUFFER, stencil);
  115. if (samples > 1)
  116. glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_DEPTH_STENCIL, width, height);
  117. else
  118. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL, width, height);
  119. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
  120. GL_RENDERBUFFER, stencil);
  121. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  122. // check status
  123. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  124. {
  125. glDeleteRenderbuffers(1, &stencil);
  126. stencil = 0;
  127. return false;
  128. }
  129. return true;
  130. }
  131. virtual bool createMSAABuffer(int width, int height, int &samples, GLenum internalformat, GLuint &buffer)
  132. {
  133. glGenRenderbuffers(1, &buffer);
  134. glBindRenderbuffer(GL_RENDERBUFFER, buffer);
  135. glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, internalformat,
  136. width, height);
  137. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
  138. GL_RENDERBUFFER, buffer);
  139. glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
  140. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  141. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  142. {
  143. glDeleteRenderbuffers(1, &buffer);
  144. buffer = 0;
  145. return false;
  146. }
  147. return true;
  148. }
  149. virtual void deleteFBO(GLuint framebuffer, GLuint depth_stencil, GLuint msaa_buffer)
  150. {
  151. if (depth_stencil != 0)
  152. glDeleteRenderbuffers(1, &depth_stencil);
  153. if (msaa_buffer != 0)
  154. glDeleteRenderbuffers(1, &msaa_buffer);
  155. if (framebuffer != 0)
  156. glDeleteFramebuffers(1, &framebuffer);
  157. }
  158. virtual void bindFBO(GLuint framebuffer)
  159. {
  160. glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
  161. }
  162. virtual void setAttachments()
  163. {
  164. // set a single render target
  165. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  166. }
  167. virtual void setAttachments(const std::vector<Canvas *> &canvases)
  168. {
  169. if (canvases.size() == 0)
  170. {
  171. setAttachments();
  172. return;
  173. }
  174. std::vector<GLenum> drawbuffers;
  175. drawbuffers.push_back(GL_COLOR_ATTACHMENT0);
  176. // Attach the canvas textures to the currently bound framebuffer.
  177. for (size_t i = 0; i < canvases.size(); i++)
  178. {
  179. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 + i,
  180. GL_TEXTURE_2D, canvases[i]->getGLTexture(), 0);
  181. drawbuffers.push_back(GL_COLOR_ATTACHMENT1 + i);
  182. }
  183. // set up multiple render targets
  184. if (GLEE_VERSION_2_0)
  185. glDrawBuffers(drawbuffers.size(), &drawbuffers[0]);
  186. else if (GLEE_ARB_draw_buffers)
  187. glDrawBuffersARB(drawbuffers.size(), &drawbuffers[0]);
  188. }
  189. };
  190. struct FramebufferStrategyPackedEXT : public FramebufferStrategy
  191. {
  192. virtual GLenum createFBO(GLuint &framebuffer, GLuint texture)
  193. {
  194. GLint current_fbo;
  195. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING_EXT, &current_fbo);
  196. // create framebuffer
  197. glGenFramebuffersEXT(1, &framebuffer);
  198. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer);
  199. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
  200. GL_TEXTURE_2D, texture, 0);
  201. // check status
  202. GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
  203. // unbind framebuffer
  204. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, (GLuint) current_fbo);
  205. return status;
  206. }
  207. virtual bool createStencil(int width, int height, int samples, GLuint &stencil)
  208. {
  209. // create combined depth/stencil buffer
  210. glDeleteRenderbuffersEXT(1, &stencil);
  211. glGenRenderbuffersEXT(1, &stencil);
  212. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, stencil);
  213. if (samples > 1)
  214. {
  215. glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples,
  216. GL_DEPTH_STENCIL, width, height);
  217. }
  218. else
  219. {
  220. glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT,
  221. width, height);
  222. }
  223. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
  224. GL_RENDERBUFFER_EXT, stencil);
  225. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
  226. // check status
  227. if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  228. {
  229. glDeleteRenderbuffersEXT(1, &stencil);
  230. stencil = 0;
  231. return false;
  232. }
  233. return true;
  234. }
  235. virtual bool createMSAABuffer(int width, int height, int &samples, GLenum internalformat, GLuint &buffer)
  236. {
  237. if (!GLEE_EXT_framebuffer_multisample)
  238. return false;
  239. glGenRenderbuffersEXT(1, &buffer);
  240. glBindRenderbufferEXT(GL_RENDERBUFFER, buffer);
  241. glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples,
  242. internalformat, width, height);
  243. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
  244. GL_RENDERBUFFER, buffer);
  245. glGetRenderbufferParameterivEXT(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
  246. glBindRenderbufferEXT(GL_RENDERBUFFER, 0);
  247. if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  248. {
  249. glDeleteRenderbuffersEXT(1, &buffer);
  250. buffer = 0;
  251. return false;
  252. }
  253. return true;
  254. }
  255. virtual void deleteFBO(GLuint framebuffer, GLuint depth_stencil, GLuint msaa_buffer)
  256. {
  257. if (depth_stencil != 0)
  258. glDeleteRenderbuffersEXT(1, &depth_stencil);
  259. if (msaa_buffer != 0)
  260. glDeleteRenderbuffersEXT(1, &msaa_buffer);
  261. if (framebuffer != 0)
  262. glDeleteFramebuffersEXT(1, &framebuffer);
  263. }
  264. virtual void bindFBO(GLuint framebuffer)
  265. {
  266. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer);
  267. }
  268. virtual void setAttachments()
  269. {
  270. // set a single render target
  271. glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
  272. }
  273. virtual void setAttachments(const std::vector<Canvas *> &canvases)
  274. {
  275. if (canvases.size() == 0)
  276. {
  277. setAttachments();
  278. return;
  279. }
  280. std::vector<GLenum> drawbuffers;
  281. drawbuffers.push_back(GL_COLOR_ATTACHMENT0_EXT);
  282. // Attach the canvas textures to the currently bound framebuffer.
  283. for (size_t i = 0; i < canvases.size(); i++)
  284. {
  285. glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1_EXT + i,
  286. GL_TEXTURE_2D, canvases[i]->getGLTexture(), 0);
  287. drawbuffers.push_back(GL_COLOR_ATTACHMENT1_EXT + i);
  288. }
  289. // set up multiple render targets
  290. if (GLEE_VERSION_2_0)
  291. glDrawBuffers(drawbuffers.size(), &drawbuffers[0]);
  292. else if (GLEE_ARB_draw_buffers)
  293. glDrawBuffersARB(drawbuffers.size(), &drawbuffers[0]);
  294. }
  295. };
  296. struct FramebufferStrategyEXT : public FramebufferStrategyPackedEXT
  297. {
  298. virtual bool createStencil(int width, int height, int samples, GLuint &stencil)
  299. {
  300. // create stencil buffer
  301. glDeleteRenderbuffersEXT(1, &stencil);
  302. glGenRenderbuffersEXT(1, &stencil);
  303. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, stencil);
  304. if (samples > 1)
  305. {
  306. glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples,
  307. GL_STENCIL_INDEX, width, height);
  308. }
  309. else
  310. {
  311. glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX,
  312. width, height);
  313. }
  314. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
  315. GL_RENDERBUFFER_EXT, stencil);
  316. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
  317. // check status
  318. if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  319. {
  320. glDeleteRenderbuffersEXT(1, &stencil);
  321. stencil = 0;
  322. return false;
  323. }
  324. return true;
  325. }
  326. bool isSupported()
  327. {
  328. GLuint fb = 0, stencil = 0;
  329. GLenum status = createFBO(fb, 0);
  330. deleteFBO(fb, stencil, 0);
  331. return status == GL_FRAMEBUFFER_COMPLETE;
  332. }
  333. };
  334. FramebufferStrategy *strategy = nullptr;
  335. FramebufferStrategy strategyNone;
  336. FramebufferStrategyGL3 strategyGL3;
  337. FramebufferStrategyPackedEXT strategyPackedEXT;
  338. FramebufferStrategyEXT strategyEXT;
  339. Canvas *Canvas::current = nullptr;
  340. OpenGL::Viewport Canvas::systemViewport = OpenGL::Viewport();
  341. bool Canvas::screenHasSRGB = false;
  342. static void getStrategy()
  343. {
  344. if (!strategy)
  345. {
  346. if (GLEE_VERSION_3_0 || GLEE_ARB_framebuffer_object)
  347. strategy = &strategyGL3;
  348. else if (GLEE_EXT_framebuffer_object && GLEE_EXT_packed_depth_stencil)
  349. strategy = &strategyPackedEXT;
  350. else if (GLEE_EXT_framebuffer_object && strategyEXT.isSupported())
  351. strategy = &strategyEXT;
  352. else
  353. strategy = &strategyNone;
  354. }
  355. }
  356. Canvas::Canvas(int width, int height, Format format, int fsaa)
  357. : fbo(0)
  358. , resolve_fbo(0)
  359. , texture(0)
  360. , fsaa_buffer(0)
  361. , depth_stencil(0)
  362. , format(format)
  363. , fsaa_samples(fsaa)
  364. , fsaa_dirty(false)
  365. {
  366. this->width = width;
  367. this->height = height;
  368. float w = static_cast<float>(width);
  369. float h = static_cast<float>(height);
  370. // world coordinates
  371. vertices[0].x = 0;
  372. vertices[0].y = 0;
  373. vertices[1].x = 0;
  374. vertices[1].y = h;
  375. vertices[2].x = w;
  376. vertices[2].y = h;
  377. vertices[3].x = w;
  378. vertices[3].y = 0;
  379. // texture coordinates
  380. vertices[0].s = 0;
  381. vertices[0].t = 0;
  382. vertices[1].s = 0;
  383. vertices[1].t = 1;
  384. vertices[2].s = 1;
  385. vertices[2].t = 1;
  386. vertices[3].s = 1;
  387. vertices[3].t = 0;
  388. getStrategy();
  389. loadVolatile();
  390. }
  391. Canvas::~Canvas()
  392. {
  393. // reset framebuffer if still using this one
  394. if (current == this)
  395. stopGrab();
  396. unloadVolatile();
  397. }
  398. bool Canvas::createFSAAFBO(GLenum internalformat)
  399. {
  400. // Create our FBO without a texture.
  401. status = strategy->createFBO(fbo, 0);
  402. GLuint previous = 0;
  403. if (current != this)
  404. {
  405. if (current != nullptr)
  406. previous = current->fbo;
  407. strategy->bindFBO(fbo);
  408. }
  409. // Create and attach the MSAA buffer for our FBO.
  410. if (strategy->createMSAABuffer(width, height, fsaa_samples, internalformat, fsaa_buffer))
  411. status = GL_FRAMEBUFFER_COMPLETE;
  412. else
  413. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  414. // Create the FBO used for the MSAA resolve, and attach the texture.
  415. if (status == GL_FRAMEBUFFER_COMPLETE)
  416. status = strategy->createFBO(resolve_fbo, texture);
  417. if (status != GL_FRAMEBUFFER_COMPLETE)
  418. {
  419. // Clean up.
  420. strategy->deleteFBO(fbo, 0, fsaa_buffer);
  421. strategy->deleteFBO(resolve_fbo, 0, 0);
  422. fbo = fsaa_buffer = resolve_fbo = 0;
  423. fsaa_samples = 0;
  424. }
  425. if (current != this)
  426. strategy->bindFBO(previous);
  427. return status == GL_FRAMEBUFFER_COMPLETE;
  428. }
  429. bool Canvas::loadVolatile()
  430. {
  431. fbo = depth_stencil = texture = 0;
  432. resolve_fbo = fsaa_buffer = 0;
  433. status = GL_FRAMEBUFFER_COMPLETE;
  434. // glTexImage2D is guaranteed to error in this case.
  435. if (width > gl.getMaxTextureSize() || height > gl.getMaxTextureSize())
  436. {
  437. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  438. return false;
  439. }
  440. glGenTextures(1, &texture);
  441. gl.bindTexture(texture);
  442. setFilter(filter);
  443. setWrap(wrap);
  444. GLenum internalformat = GL_RGBA;
  445. GLenum externalformat = GL_RGBA;
  446. GLenum textype = GL_UNSIGNED_BYTE;
  447. convertFormat(format, internalformat, externalformat, textype);
  448. while (glGetError() != GL_NO_ERROR)
  449. /* Clear the error buffer. */;
  450. glTexImage2D(GL_TEXTURE_2D,
  451. 0,
  452. (GLint) internalformat,
  453. width, height,
  454. 0,
  455. externalformat,
  456. textype,
  457. nullptr);
  458. if (glGetError() != GL_NO_ERROR)
  459. {
  460. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  461. return false;
  462. }
  463. int max_samples = 0;
  464. if (GLEE_VERSION_3_0 || GLEE_ARB_framebuffer_object
  465. || GLEE_EXT_framebuffer_multisample)
  466. {
  467. glGetIntegerv(GL_MAX_SAMPLES, &max_samples);
  468. }
  469. if (fsaa_samples > max_samples)
  470. fsaa_samples = max_samples;
  471. // Try to create a FSAA FBO if requested.
  472. bool fsaasuccess = false;
  473. if (fsaa_samples > 1)
  474. fsaasuccess = createFSAAFBO(internalformat);
  475. // On failure (or no requested FSAA), fall back to a regular FBO.
  476. if (!fsaasuccess)
  477. status = strategy->createFBO(fbo, texture);
  478. if (status != GL_FRAMEBUFFER_COMPLETE)
  479. return false;
  480. clear(Color(0, 0, 0, 0));
  481. fsaa_dirty = (fsaa_buffer != 0);
  482. return true;
  483. }
  484. void Canvas::unloadVolatile()
  485. {
  486. strategy->deleteFBO(fbo, depth_stencil, fsaa_buffer);
  487. strategy->deleteFBO(resolve_fbo, 0, 0);
  488. gl.deleteTexture(texture);
  489. fbo = depth_stencil = texture = 0;
  490. resolve_fbo = fsaa_buffer = 0;
  491. for (size_t i = 0; i < attachedCanvases.size(); i++)
  492. attachedCanvases[i]->release();
  493. attachedCanvases.clear();
  494. }
  495. void Canvas::drawv(const Matrix &t, const Vertex *v)
  496. {
  497. glPushMatrix();
  498. glMultMatrixf((const GLfloat *)t.getElements());
  499. predraw();
  500. glEnableClientState(GL_VERTEX_ARRAY);
  501. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  502. glVertexPointer(2, GL_FLOAT, sizeof(Vertex), (GLvoid *)&v[0].x);
  503. glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (GLvoid *)&v[0].s);
  504. gl.prepareDraw();
  505. glDrawArrays(GL_QUADS, 0, 4);
  506. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  507. glDisableClientState(GL_VERTEX_ARRAY);
  508. postdraw();
  509. glPopMatrix();
  510. }
  511. void Canvas::draw(float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  512. {
  513. static Matrix t;
  514. t.setTransformation(x, y, angle, sx, sy, ox, oy, kx, ky);
  515. drawv(t, vertices);
  516. }
  517. void Canvas::drawq(Quad *quad, float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  518. {
  519. static Matrix t;
  520. t.setTransformation(x, y, angle, sx, sy, ox, oy, kx, ky);
  521. const Vertex *v = quad->getVertices();
  522. drawv(t, v);
  523. }
  524. void Canvas::setFilter(const Texture::Filter &f)
  525. {
  526. filter = f;
  527. gl.bindTexture(texture);
  528. gl.setTextureFilter(filter);
  529. }
  530. void Canvas::setWrap(const Texture::Wrap &w)
  531. {
  532. wrap = w;
  533. gl.bindTexture(texture);
  534. gl.setTextureWrap(wrap);
  535. }
  536. GLuint Canvas::getGLTexture() const
  537. {
  538. return texture;
  539. }
  540. void Canvas::predraw()
  541. {
  542. // We need to make sure the texture is up-to-date by resolving the MSAA
  543. // buffer (which we render to when the canvas is active) to it.
  544. resolveMSAA();
  545. gl.bindTexture(texture);
  546. }
  547. void Canvas::setupGrab()
  548. {
  549. // already grabbing
  550. if (current == this)
  551. return;
  552. // cleanup after previous Canvas
  553. if (current != nullptr)
  554. {
  555. systemViewport = current->systemViewport;
  556. current->stopGrab(true);
  557. }
  558. else
  559. systemViewport = gl.getViewport();
  560. // indicate we are using this Canvas.
  561. current = this;
  562. // bind the framebuffer object.
  563. strategy->bindFBO(fbo);
  564. gl.setViewport(OpenGL::Viewport(0, 0, width, height));
  565. // Reset the projection matrix
  566. glMatrixMode(GL_PROJECTION);
  567. glPushMatrix();
  568. glLoadIdentity();
  569. // Set up orthographic view (no depth)
  570. glOrtho(0.0, width, 0.0, height, -1.0, 1.0);
  571. // Switch back to modelview matrix
  572. glMatrixMode(GL_MODELVIEW);
  573. // Make sure the correct sRGB setting is used when drawing to the canvas.
  574. if (format == FORMAT_SRGB)
  575. glEnable(GL_FRAMEBUFFER_SRGB);
  576. else if (screenHasSRGB)
  577. glDisable(GL_FRAMEBUFFER_SRGB);
  578. if (fsaa_buffer != 0)
  579. fsaa_dirty = true;
  580. }
  581. void Canvas::startGrab(const std::vector<Canvas *> &canvases)
  582. {
  583. // Whether the new canvas list is different from the old one.
  584. // A more thorough check is done below.
  585. bool canvaseschanged = canvases.size() != attachedCanvases.size();
  586. if (canvases.size() > 0)
  587. {
  588. if (!isMultiCanvasSupported())
  589. throw love::Exception("Multi-canvas rendering is not supported on this system.");
  590. if ((int) canvases.size() + 1 > gl.getMaxRenderTargets())
  591. throw love::Exception("This system can't simultaniously render to %d canvases.", canvases.size()+1);
  592. if (fsaa_samples != 0)
  593. throw love::Exception("Multi-canvas rendering is not supported with FSAA.");
  594. }
  595. for (size_t i = 0; i < canvases.size(); i++)
  596. {
  597. if (canvases[i]->getWidth() != width || canvases[i]->getHeight() != height)
  598. throw love::Exception("All canvas arguments must have the same dimensions.");
  599. if (canvases[i]->getTextureFormat() != format)
  600. throw love::Exception("All canvas arguments must have the same texture format.");
  601. if (canvases[i]->getFSAA() != 0)
  602. throw love::Exception("Multi-canvas rendering is not supported with FSAA.");
  603. if (!canvaseschanged && canvases[i] != attachedCanvases[i])
  604. canvaseschanged = true;
  605. }
  606. setupGrab();
  607. // Don't attach anything if there's nothing to change.
  608. if (!canvaseschanged)
  609. return;
  610. // Attach the canvas textures to the active FBO and set up MRTs.
  611. strategy->setAttachments(canvases);
  612. for (size_t i = 0; i < canvases.size(); i++)
  613. canvases[i]->retain();
  614. for (size_t i = 0; i < attachedCanvases.size(); i++)
  615. attachedCanvases[i]->release();
  616. attachedCanvases = canvases;
  617. }
  618. void Canvas::startGrab()
  619. {
  620. setupGrab();
  621. if (attachedCanvases.size() == 0)
  622. return;
  623. // make sure the FBO is only using a single canvas
  624. strategy->setAttachments();
  625. // release any previously attached canvases
  626. for (size_t i = 0; i < attachedCanvases.size(); i++)
  627. attachedCanvases[i]->release();
  628. attachedCanvases.clear();
  629. }
  630. void Canvas::stopGrab(bool switchingToOtherCanvas)
  631. {
  632. // i am not grabbing. leave me alone
  633. if (current != this)
  634. return;
  635. glMatrixMode(GL_PROJECTION);
  636. glPopMatrix();
  637. glMatrixMode(GL_MODELVIEW);
  638. if (switchingToOtherCanvas)
  639. {
  640. if (format == FORMAT_SRGB)
  641. glDisable(GL_FRAMEBUFFER_SRGB);
  642. }
  643. else
  644. {
  645. // bind system framebuffer.
  646. strategy->bindFBO(0);
  647. current = nullptr;
  648. gl.setViewport(systemViewport);
  649. if (format == FORMAT_SRGB && !screenHasSRGB)
  650. glDisable(GL_FRAMEBUFFER_SRGB);
  651. else if (format != FORMAT_SRGB && screenHasSRGB)
  652. glEnable(GL_FRAMEBUFFER_SRGB);
  653. }
  654. }
  655. void Canvas::clear(Color c)
  656. {
  657. if (strategy == &strategyNone)
  658. return;
  659. GLuint previous = 0;
  660. if (current != this)
  661. {
  662. if (current != nullptr)
  663. previous = current->fbo;
  664. strategy->bindFBO(fbo);
  665. }
  666. GLfloat glcolor[] = {c.r/255.f, c.g/255.f, c.b/255.f, c.a/255.f};
  667. // We don't need to worry about multiple FBO attachments or global clear
  668. // color state when OpenGL 3.0+ is supported.
  669. if (GLEE_VERSION_3_0)
  670. {
  671. glClearBufferfv(GL_COLOR, 0, glcolor);
  672. if (depth_stencil != 0)
  673. {
  674. GLint stencilvalue = 0;
  675. glClearBufferiv(GL_STENCIL, 0, &stencilvalue);
  676. }
  677. }
  678. else
  679. {
  680. // glClear will clear all active draw buffers, so we need to temporarily
  681. // detach any other canvases (when MRT is being used.)
  682. if (attachedCanvases.size() > 0)
  683. strategy->setAttachments();
  684. // Don't use the state-shadowed gl.setClearColor because we want to save
  685. // the previous clear color.
  686. glClearColor(glcolor[0], glcolor[1], glcolor[2], glcolor[3]);
  687. glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  688. if (attachedCanvases.size() > 0)
  689. strategy->setAttachments(attachedCanvases);
  690. // Restore the global clear color.
  691. gl.setClearColor(gl.getClearColor());
  692. }
  693. if (current != this)
  694. strategy->bindFBO(previous);
  695. if (fsaa_buffer != 0)
  696. fsaa_dirty = true;
  697. }
  698. bool Canvas::checkCreateStencil()
  699. {
  700. // Do nothing if we've already created the stencil buffer.
  701. if (depth_stencil != 0)
  702. return true;
  703. if (current != this)
  704. strategy->bindFBO(fbo);
  705. bool success = strategy->createStencil(width, height, fsaa_samples, depth_stencil);
  706. if (current && current != this)
  707. strategy->bindFBO(current->fbo);
  708. else if (!current)
  709. strategy->bindFBO(0);
  710. return success;
  711. }
  712. love::image::ImageData *Canvas::getImageData(love::image::Image *image)
  713. {
  714. resolveMSAA();
  715. int row = 4 * width;
  716. int size = row * height;
  717. GLubyte *pixels = new GLubyte[size];
  718. // Our texture is attached to 'resolve_fbo' when we use MSAA.
  719. if (fsaa_samples > 1 && (GLEE_VERSION_3_0 || GLEE_ARB_framebuffer_object))
  720. glBindFramebuffer(GL_READ_FRAMEBUFFER, resolve_fbo);
  721. else if (fsaa_samples > 1 && GLEE_EXT_framebuffer_multisample)
  722. glBindFramebufferEXT(GL_READ_FRAMEBUFFER, resolve_fbo);
  723. else
  724. strategy->bindFBO(fbo);
  725. glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  726. if (current)
  727. strategy->bindFBO(current->fbo);
  728. else
  729. strategy->bindFBO(0);
  730. // The new ImageData now owns the pixel data, so we don't delete it here.
  731. love::image::ImageData *img = image->newImageData(width, height, (void *)pixels, true);
  732. return img;
  733. }
  734. void Canvas::getPixel(unsigned char* pixel_rgba, int x, int y)
  735. {
  736. resolveMSAA();
  737. // Our texture is attached to 'resolve_fbo' when we use MSAA.
  738. if (fsaa_samples > 1 && (GLEE_VERSION_3_0 || GLEE_ARB_framebuffer_object))
  739. glBindFramebuffer(GL_READ_FRAMEBUFFER, resolve_fbo);
  740. else if (fsaa_samples > 1 && GLEE_EXT_framebuffer_multisample)
  741. glBindFramebufferEXT(GL_READ_FRAMEBUFFER, resolve_fbo);
  742. else if (current != this)
  743. strategy->bindFBO(fbo);
  744. glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel_rgba);
  745. if (current && current != this)
  746. strategy->bindFBO(current->fbo);
  747. else if (!current)
  748. strategy->bindFBO(0);
  749. }
  750. bool Canvas::resolveMSAA()
  751. {
  752. if (resolve_fbo == 0 || fsaa_buffer == 0)
  753. return false;
  754. if (!fsaa_dirty)
  755. return true;
  756. GLuint previous = 0;
  757. if (current != nullptr)
  758. previous = current->fbo;
  759. // Do the MSAA resolve by blitting the MSAA renderbuffer to the texture.
  760. if (GLEE_VERSION_3_0 || GLEE_ARB_framebuffer_object)
  761. {
  762. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
  763. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolve_fbo);
  764. glBlitFramebuffer(0, 0, width, height, 0, 0, width, height,
  765. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  766. }
  767. else if (GLEE_EXT_framebuffer_multisample && GLEE_EXT_framebuffer_blit)
  768. {
  769. glBindFramebufferEXT(GL_READ_FRAMEBUFFER, fbo);
  770. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER, resolve_fbo);
  771. glBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height,
  772. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  773. }
  774. else
  775. return false;
  776. strategy->bindFBO(previous);
  777. if (current != this)
  778. fsaa_dirty = false;
  779. return true;
  780. }
  781. Canvas::Format Canvas::getSizedFormat(Canvas::Format format)
  782. {
  783. switch (format)
  784. {
  785. case FORMAT_NORMAL:
  786. return FORMAT_RGBA8;
  787. case FORMAT_HDR:
  788. return FORMAT_RGBA16F;
  789. default:
  790. return format;
  791. }
  792. }
  793. void Canvas::convertFormat(Canvas::Format format, GLenum &internalformat, GLenum &externalformat, GLenum &type)
  794. {
  795. format = getSizedFormat(format);
  796. externalformat = GL_RGBA;
  797. switch (format)
  798. {
  799. case FORMAT_RGBA8:
  800. default:
  801. internalformat = GL_RGBA8;
  802. type = GL_UNSIGNED_BYTE;
  803. break;
  804. case FORMAT_RGBA4:
  805. internalformat = GL_RGBA4;
  806. type = GL_UNSIGNED_SHORT_4_4_4_4;
  807. break;
  808. case FORMAT_RGB5A1:
  809. internalformat = GL_RGB5_A1;
  810. type = GL_UNSIGNED_SHORT_5_5_5_1;
  811. break;
  812. case FORMAT_RGB565:
  813. internalformat = GL_RGB565;
  814. externalformat = GL_RGB;
  815. type = GL_UNSIGNED_SHORT_5_6_5;
  816. break;
  817. case FORMAT_RGB10A2:
  818. internalformat = GL_RGB10_A2;
  819. type = GL_UNSIGNED_INT_10_10_10_2;
  820. break;
  821. case FORMAT_RG11B10F:
  822. internalformat = GL_R11F_G11F_B10F;
  823. externalformat = GL_RGB;
  824. type = GL_UNSIGNED_INT_10F_11F_11F_REV;
  825. break;
  826. case FORMAT_RGBA16F:
  827. internalformat = GL_RGBA16F;
  828. type = GL_FLOAT;
  829. break;
  830. case FORMAT_RGBA32F:
  831. internalformat = GL_RGBA32F;
  832. type = GL_FLOAT;
  833. break;
  834. case FORMAT_SRGB:
  835. internalformat = GL_SRGB8_ALPHA8;
  836. type = GL_UNSIGNED_BYTE;
  837. break;
  838. }
  839. }
  840. bool Canvas::isSupported()
  841. {
  842. getStrategy();
  843. return (strategy != &strategyNone);
  844. }
  845. bool Canvas::isMultiCanvasSupported()
  846. {
  847. // system must support at least 4 simultanious active canvases.
  848. return gl.getMaxRenderTargets() >= 4;
  849. }
  850. bool Canvas::supportedFormats[] = {false};
  851. bool Canvas::isFormatSupported(Canvas::Format format)
  852. {
  853. if (!isSupported())
  854. return false;
  855. bool supported = true;
  856. format = getSizedFormat(format);
  857. switch (format)
  858. {
  859. case FORMAT_RGBA8:
  860. case FORMAT_RGBA4:
  861. case FORMAT_RGB5A1:
  862. case FORMAT_RGB10A2:
  863. supported = true;
  864. break;
  865. case FORMAT_RGB565:
  866. supported = GLEE_VERSION_4_2 || GLEE_ARB_ES2_compatibility;
  867. break;
  868. case FORMAT_RG11B10F:
  869. supported = GLEE_VERSION_3_0 || (GLEE_ARB_texture_float && GLEE_ARB_color_buffer_float
  870. && GLEE_EXT_packed_float);
  871. break;
  872. case FORMAT_RGBA16F:
  873. case FORMAT_RGBA32F:
  874. supported = GLEE_VERSION_3_0 || (GLEE_ARB_texture_float && GLEE_ARB_color_buffer_float);
  875. break;
  876. case FORMAT_SRGB:
  877. supported = GLEE_VERSION_3_0 || ((GLEE_ARB_framebuffer_sRGB || GLEE_EXT_framebuffer_sRGB)
  878. && (GLEE_VERSION_2_1 || GLEE_EXT_texture_sRGB));
  879. break;
  880. default:
  881. supported = false;
  882. break;
  883. }
  884. if (!supported)
  885. return false;
  886. if (supportedFormats[format])
  887. return true;
  888. // Even though we might have the necessary OpenGL version or extension,
  889. // drivers are still allowed to throw FRAMEBUFFER_UNSUPPORTED when attaching
  890. // a texture to a FBO whose format the driver doesn't like. So we should
  891. // test with an actual FBO.
  892. GLenum internalformat = GL_RGBA;
  893. GLenum externalformat = GL_RGBA;
  894. GLenum textype = GL_UNSIGNED_BYTE;
  895. convertFormat(format, internalformat, externalformat, textype);
  896. GLuint texture = 0;
  897. glGenTextures(1, &texture);
  898. gl.bindTexture(texture);
  899. Texture::Filter f;
  900. f.min = f.mag = Texture::FILTER_NEAREST;
  901. gl.setTextureFilter(f);
  902. Texture::Wrap w;
  903. gl.setTextureWrap(w);
  904. glTexImage2D(GL_TEXTURE_2D, 0, internalformat, 2, 2, 0, externalformat, textype, nullptr);
  905. GLuint fbo = 0;
  906. GLenum status = strategy->createFBO(fbo, texture);
  907. strategy->deleteFBO(fbo, 0, 0);
  908. gl.deleteTexture(texture);
  909. // Cache the result so we don't do this for every isFormatSupported call.
  910. if (status == GL_FRAMEBUFFER_COMPLETE)
  911. supportedFormats[format] = true;
  912. return status == GL_FRAMEBUFFER_COMPLETE;
  913. }
  914. void Canvas::bindDefaultCanvas()
  915. {
  916. if (current != nullptr)
  917. current->stopGrab();
  918. }
  919. bool Canvas::getConstant(const char *in, Format &out)
  920. {
  921. return formats.find(in, out);
  922. }
  923. bool Canvas::getConstant(Format in, const char *&out)
  924. {
  925. return formats.find(in, out);
  926. }
  927. StringMap<Canvas::Format, Canvas::FORMAT_MAX_ENUM>::Entry Canvas::formatEntries[] =
  928. {
  929. {"normal", Canvas::FORMAT_NORMAL},
  930. {"hdr", Canvas::FORMAT_HDR},
  931. {"rgba8", Canvas::FORMAT_RGBA8},
  932. {"rgba4", Canvas::FORMAT_RGBA4},
  933. {"rgb5a1", Canvas::FORMAT_RGB5A1},
  934. {"rgb565", Canvas::FORMAT_RGB565},
  935. {"rgb10a2", Canvas::FORMAT_RGB10A2},
  936. {"rg11b10f", Canvas::FORMAT_RG11B10F},
  937. {"rgba16f", Canvas::FORMAT_RGBA16F},
  938. {"rgba32f", Canvas::FORMAT_RGBA32F},
  939. {"srgb", Canvas::FORMAT_SRGB},
  940. };
  941. StringMap<Canvas::Format, Canvas::FORMAT_MAX_ENUM> Canvas::formats(Canvas::formatEntries, sizeof(Canvas::formatEntries));
  942. } // opengl
  943. } // graphics
  944. } // love