SoftwareGLContext.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. /*
  2. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  3. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@gmx.de>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "SoftwareGLContext.h"
  8. #include "GLStruct.h"
  9. #include "SoftwareRasterizer.h"
  10. #include <AK/Assertions.h>
  11. #include <AK/Debug.h>
  12. #include <AK/Format.h>
  13. #include <AK/QuickSort.h>
  14. #include <AK/TemporaryChange.h>
  15. #include <AK/Variant.h>
  16. #include <AK/Vector.h>
  17. #include <LibGfx/Bitmap.h>
  18. #include <LibGfx/Painter.h>
  19. #include <LibGfx/Vector4.h>
  20. #include <math.h>
  21. using AK::dbgln;
  22. namespace GL {
  23. // FIXME: We should set this up when we create the context!
  24. static constexpr size_t MATRIX_STACK_LIMIT = 1024;
  25. #define APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(name, ...) \
  26. if (should_append_to_listing()) { \
  27. append_to_listing<&SoftwareGLContext::name>(__VA_ARGS__); \
  28. if (!should_execute_after_appending_to_listing()) \
  29. return; \
  30. }
  31. SoftwareGLContext::SoftwareGLContext(Gfx::Bitmap& frontbuffer)
  32. : m_frontbuffer(frontbuffer)
  33. , m_rasterizer(frontbuffer.size())
  34. {
  35. }
  36. void SoftwareGLContext::gl_begin(GLenum mode)
  37. {
  38. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_begin, mode);
  39. if (m_in_draw_state) {
  40. m_error = GL_INVALID_OPERATION;
  41. return;
  42. }
  43. if (mode < GL_TRIANGLES || mode > GL_POLYGON) {
  44. m_error = GL_INVALID_ENUM;
  45. return;
  46. }
  47. m_current_draw_mode = mode;
  48. m_in_draw_state = true; // Certain commands will now generate an error
  49. m_error = GL_NO_ERROR;
  50. }
  51. void SoftwareGLContext::gl_clear(GLbitfield mask)
  52. {
  53. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear, mask);
  54. if (m_in_draw_state) {
  55. m_error = GL_INVALID_OPERATION;
  56. return;
  57. }
  58. if (mask & ~(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)) {
  59. m_error = GL_INVALID_ENUM;
  60. return;
  61. }
  62. if (mask & GL_COLOR_BUFFER_BIT)
  63. m_rasterizer.clear_color(m_clear_color);
  64. if (mask & GL_DEPTH_BUFFER_BIT)
  65. m_rasterizer.clear_depth(static_cast<float>(m_clear_depth));
  66. m_error = GL_NO_ERROR;
  67. }
  68. void SoftwareGLContext::gl_clear_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
  69. {
  70. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_color, red, green, blue, alpha);
  71. if (m_in_draw_state) {
  72. m_error = GL_INVALID_OPERATION;
  73. return;
  74. }
  75. m_clear_color = { red, green, blue, alpha };
  76. m_error = GL_NO_ERROR;
  77. }
  78. void SoftwareGLContext::gl_clear_depth(GLdouble depth)
  79. {
  80. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_depth, depth);
  81. if (m_in_draw_state) {
  82. m_error = GL_INVALID_OPERATION;
  83. return;
  84. }
  85. m_clear_depth = depth;
  86. m_error = GL_NO_ERROR;
  87. }
  88. void SoftwareGLContext::gl_color(GLdouble r, GLdouble g, GLdouble b, GLdouble a)
  89. {
  90. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_color, r, g, b, a);
  91. m_current_vertex_color = { (float)r, (float)g, (float)b, (float)a };
  92. m_error = GL_NO_ERROR;
  93. }
  94. void SoftwareGLContext::gl_end()
  95. {
  96. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_end);
  97. // At this point, the user has effectively specified that they are done with defining the geometry
  98. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  99. //
  100. // 1. Transform all of the vertices in the current vertex list into eye space by mulitplying the model-view matrix
  101. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  102. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  103. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  104. // 5. The vertices are sorted (for the rasteriser, how are we doing this? 3Dfx did this top to bottom in terms of vertex y coordinates)
  105. // 6. The vertices are then sent off to the rasteriser and drawn to the screen
  106. float scr_width = m_frontbuffer->width();
  107. float scr_height = m_frontbuffer->height();
  108. // Make sure we had a `glBegin` before this call...
  109. if (!m_in_draw_state) {
  110. m_error = GL_INVALID_OPERATION;
  111. return;
  112. }
  113. // Let's construct some triangles
  114. if (m_current_draw_mode == GL_TRIANGLES) {
  115. GLTriangle triangle;
  116. for (size_t i = 0; i < vertex_list.size(); i += 3) {
  117. triangle.vertices[0] = vertex_list.at(i);
  118. triangle.vertices[1] = vertex_list.at(i + 1);
  119. triangle.vertices[2] = vertex_list.at(i + 2);
  120. triangle_list.append(triangle);
  121. }
  122. } else if (m_current_draw_mode == GL_QUADS) {
  123. // We need to construct two triangles to form the quad
  124. GLTriangle triangle;
  125. VERIFY(vertex_list.size() % 4 == 0);
  126. for (size_t i = 0; i < vertex_list.size(); i += 4) {
  127. // Triangle 1
  128. triangle.vertices[0] = vertex_list.at(i);
  129. triangle.vertices[1] = vertex_list.at(i + 1);
  130. triangle.vertices[2] = vertex_list.at(i + 2);
  131. triangle_list.append(triangle);
  132. // Triangle 2
  133. triangle.vertices[0] = vertex_list.at(i + 2);
  134. triangle.vertices[1] = vertex_list.at(i + 3);
  135. triangle.vertices[2] = vertex_list.at(i);
  136. triangle_list.append(triangle);
  137. }
  138. } else if (m_current_draw_mode == GL_TRIANGLE_FAN) {
  139. GLTriangle triangle;
  140. triangle.vertices[0] = vertex_list.at(0); // Root vertex is always the vertex defined first
  141. for (size_t i = 1; i < vertex_list.size() - 1; i++) // This is technically `n-2` triangles. We start at index 1
  142. {
  143. triangle.vertices[1] = vertex_list.at(i);
  144. triangle.vertices[2] = vertex_list.at(i + 1);
  145. triangle_list.append(triangle);
  146. }
  147. } else if (m_current_draw_mode == GL_TRIANGLE_STRIP) {
  148. GLTriangle triangle;
  149. for (size_t i = 0; i < vertex_list.size() - 2; i++) {
  150. triangle.vertices[0] = vertex_list.at(i);
  151. triangle.vertices[1] = vertex_list.at(i + 1);
  152. triangle.vertices[2] = vertex_list.at(i + 2);
  153. triangle_list.append(triangle);
  154. }
  155. } else {
  156. m_error = GL_INVALID_ENUM;
  157. return;
  158. }
  159. // Now let's transform each triangle and send that to the GPU
  160. for (size_t i = 0; i < triangle_list.size(); i++) {
  161. GLTriangle& triangle = triangle_list.at(i);
  162. GLVertex& vertexa = triangle.vertices[0];
  163. GLVertex& vertexb = triangle.vertices[1];
  164. GLVertex& vertexc = triangle.vertices[2];
  165. FloatVector4 veca({ vertexa.x, vertexa.y, vertexa.z, 1.0f });
  166. FloatVector4 vecb({ vertexb.x, vertexb.y, vertexb.z, 1.0f });
  167. FloatVector4 vecc({ vertexc.x, vertexc.y, vertexc.z, 1.0f });
  168. // First multiply the vertex by the MODELVIEW matrix and then the PROJECTION matrix
  169. veca = m_model_view_matrix * veca;
  170. veca = m_projection_matrix * veca;
  171. vecb = m_model_view_matrix * vecb;
  172. vecb = m_projection_matrix * vecb;
  173. vecc = m_model_view_matrix * vecc;
  174. vecc = m_projection_matrix * vecc;
  175. // At this point, we're in clip space
  176. // Here's where we do the clipping. This is a really crude implementation of the
  177. // https://learnopengl.com/Getting-started/Coordinate-Systems
  178. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  179. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  180. //
  181. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  182. // Okay, let's do some face culling first
  183. Vector<FloatVector4> vecs;
  184. Vector<GLVertex> verts;
  185. vecs.append(veca);
  186. vecs.append(vecb);
  187. vecs.append(vecc);
  188. m_clipper.clip_triangle_against_frustum(vecs);
  189. // TODO: Copy color and UV information too!
  190. for (size_t vec_idx = 0; vec_idx < vecs.size(); vec_idx++) {
  191. FloatVector4& vec = vecs.at(vec_idx);
  192. GLVertex vertex;
  193. // Perform the perspective divide
  194. if (vec.w() != 0.0f) {
  195. vec.set_x(vec.x() / vec.w());
  196. vec.set_y(vec.y() / vec.w());
  197. vec.set_z(vec.z() / vec.w());
  198. vec.set_w(1 / vec.w());
  199. }
  200. vertex.x = vec.x();
  201. vertex.y = vec.y();
  202. vertex.z = vec.z();
  203. vertex.w = vec.w();
  204. // FIXME: This is to suppress any -Wunused errors
  205. vertex.u = 0.0f;
  206. vertex.v = 0.0f;
  207. if (vec_idx == 0) {
  208. vertex.r = vertexa.r;
  209. vertex.g = vertexa.g;
  210. vertex.b = vertexa.b;
  211. vertex.a = vertexa.a;
  212. } else if (vec_idx == 1) {
  213. vertex.r = vertexb.r;
  214. vertex.g = vertexb.g;
  215. vertex.b = vertexb.b;
  216. vertex.a = vertexb.a;
  217. } else {
  218. vertex.r = vertexc.r;
  219. vertex.g = vertexc.g;
  220. vertex.b = vertexc.b;
  221. vertex.a = vertexc.a;
  222. }
  223. vertex.x = (vec.x() + 1.0f) * (scr_width / 2.0f) + 0.0f; // TODO: 0.0f should be something!?
  224. vertex.y = scr_height - ((vec.y() + 1.0f) * (scr_height / 2.0f) + 0.0f);
  225. vertex.z = vec.z();
  226. verts.append(vertex);
  227. }
  228. if (verts.size() == 0) {
  229. continue;
  230. } else if (verts.size() == 3) {
  231. GLTriangle tri;
  232. tri.vertices[0] = verts.at(0);
  233. tri.vertices[1] = verts.at(1);
  234. tri.vertices[2] = verts.at(2);
  235. processed_triangles.append(tri);
  236. } else if (verts.size() == 4) {
  237. GLTriangle tri1;
  238. GLTriangle tri2;
  239. tri1.vertices[0] = verts.at(0);
  240. tri1.vertices[1] = verts.at(1);
  241. tri1.vertices[2] = verts.at(2);
  242. processed_triangles.append(tri1);
  243. tri2.vertices[0] = verts.at(0);
  244. tri2.vertices[1] = verts.at(2);
  245. tri2.vertices[2] = verts.at(3);
  246. processed_triangles.append(tri2);
  247. }
  248. }
  249. for (size_t i = 0; i < processed_triangles.size(); i++) {
  250. GLTriangle& triangle = processed_triangles.at(i);
  251. // Let's calculate the (signed) area of the triangle
  252. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  253. float dxAB = triangle.vertices[0].x - triangle.vertices[1].x; // A.x - B.x
  254. float dxBC = triangle.vertices[1].x - triangle.vertices[2].x; // B.X - C.x
  255. float dyAB = triangle.vertices[0].y - triangle.vertices[1].y;
  256. float dyBC = triangle.vertices[1].y - triangle.vertices[2].y;
  257. float area = (dxAB * dyBC) - (dxBC * dyAB);
  258. if (area == 0.0f)
  259. continue;
  260. if (m_cull_faces) {
  261. bool is_front = (m_front_face == GL_CCW ? area > 0 : area < 0);
  262. if (is_front && (m_culled_sides == GL_FRONT || m_culled_sides == GL_FRONT_AND_BACK))
  263. continue;
  264. if (!is_front && (m_culled_sides == GL_BACK || m_culled_sides == GL_FRONT_AND_BACK))
  265. continue;
  266. }
  267. m_rasterizer.submit_triangle(triangle);
  268. }
  269. triangle_list.clear();
  270. processed_triangles.clear();
  271. vertex_list.clear();
  272. m_in_draw_state = false;
  273. m_error = GL_NO_ERROR;
  274. }
  275. void SoftwareGLContext::gl_frustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  276. {
  277. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_frustum, left, right, bottom, top, near_val, far_val);
  278. if (m_in_draw_state) {
  279. m_error = GL_INVALID_OPERATION;
  280. return;
  281. }
  282. // Let's do some math!
  283. // FIXME: Are we losing too much precision by doing this?
  284. float a = static_cast<float>((right + left) / (right - left));
  285. float b = static_cast<float>((top + bottom) / (top - bottom));
  286. float c = static_cast<float>(-((far_val + near_val) / (far_val - near_val)));
  287. float d = static_cast<float>(-((2 * (far_val * near_val)) / (far_val - near_val)));
  288. FloatMatrix4x4 frustum {
  289. ((2 * (float)near_val) / ((float)right - (float)left)), 0, a, 0,
  290. 0, ((2 * (float)near_val) / ((float)top - (float)bottom)), b, 0,
  291. 0, 0, c, d,
  292. 0, 0, -1, 0
  293. };
  294. if (m_current_matrix_mode == GL_PROJECTION) {
  295. m_projection_matrix = m_projection_matrix * frustum;
  296. } else if (m_current_matrix_mode == GL_MODELVIEW) {
  297. dbgln_if(GL_DEBUG, "glFrustum(): frustum created with curr_matrix_mode == GL_MODELVIEW!!!");
  298. m_projection_matrix = m_model_view_matrix * frustum;
  299. }
  300. m_error = GL_NO_ERROR;
  301. }
  302. void SoftwareGLContext::gl_ortho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  303. {
  304. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_ortho, left, right, bottom, top, near_val, far_val);
  305. if (m_in_draw_state) {
  306. m_error = GL_INVALID_OPERATION;
  307. return;
  308. }
  309. if (left == right || bottom == top || near_val == far_val) {
  310. m_error = GL_INVALID_VALUE;
  311. return;
  312. }
  313. auto rl = right - left;
  314. auto tb = top - bottom;
  315. auto fn = far_val - near_val;
  316. auto tx = -(right + left) / rl;
  317. auto ty = -(top + bottom) / tb;
  318. auto tz = -(far_val + near_val) / fn;
  319. FloatMatrix4x4 projection {
  320. static_cast<float>(2 / rl), 0, 0, static_cast<float>(tx),
  321. 0, static_cast<float>(2 / tb), 0, static_cast<float>(ty),
  322. 0, 0, static_cast<float>(-2 / fn), static_cast<float>(tz),
  323. 0, 0, 0, 1
  324. };
  325. if (m_current_matrix_mode == GL_PROJECTION) {
  326. m_projection_matrix = m_projection_matrix * projection;
  327. } else if (m_current_matrix_mode == GL_MODELVIEW) {
  328. m_projection_matrix = m_model_view_matrix * projection;
  329. }
  330. m_error = GL_NO_ERROR;
  331. }
  332. GLenum SoftwareGLContext::gl_get_error()
  333. {
  334. if (m_in_draw_state) {
  335. return GL_INVALID_OPERATION;
  336. }
  337. return m_error;
  338. }
  339. GLubyte* SoftwareGLContext::gl_get_string(GLenum name)
  340. {
  341. if (m_in_draw_state) {
  342. m_error = GL_INVALID_OPERATION;
  343. return nullptr;
  344. }
  345. switch (name) {
  346. case GL_VENDOR:
  347. return reinterpret_cast<GLubyte*>(const_cast<char*>("The SerenityOS Developers"));
  348. case GL_RENDERER:
  349. return reinterpret_cast<GLubyte*>(const_cast<char*>("SerenityOS OpenGL"));
  350. case GL_VERSION:
  351. return reinterpret_cast<GLubyte*>(const_cast<char*>("OpenGL 1.2 SerenityOS"));
  352. default:
  353. dbgln_if(GL_DEBUG, "glGetString(): Unknown enum name!");
  354. break;
  355. }
  356. m_error = GL_INVALID_ENUM;
  357. return nullptr;
  358. }
  359. void SoftwareGLContext::gl_load_identity()
  360. {
  361. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_load_identity);
  362. if (m_in_draw_state) {
  363. m_error = GL_INVALID_OPERATION;
  364. return;
  365. }
  366. if (m_current_matrix_mode == GL_PROJECTION)
  367. m_projection_matrix = FloatMatrix4x4::identity();
  368. else if (m_current_matrix_mode == GL_MODELVIEW)
  369. m_model_view_matrix = FloatMatrix4x4::identity();
  370. else
  371. VERIFY_NOT_REACHED();
  372. m_error = GL_NO_ERROR;
  373. }
  374. void SoftwareGLContext::gl_load_matrix(const FloatMatrix4x4& matrix)
  375. {
  376. if (should_append_to_listing()) {
  377. auto ptr = store_in_listing(matrix);
  378. append_to_listing<&SoftwareGLContext::gl_load_matrix>(*ptr);
  379. if (!should_execute_after_appending_to_listing())
  380. return;
  381. }
  382. if (m_in_draw_state) {
  383. m_error = GL_INVALID_OPERATION;
  384. return;
  385. }
  386. if (m_current_matrix_mode == GL_PROJECTION)
  387. m_projection_matrix = matrix;
  388. else if (m_current_matrix_mode == GL_MODELVIEW)
  389. m_model_view_matrix = matrix;
  390. else
  391. VERIFY_NOT_REACHED();
  392. m_error = GL_NO_ERROR;
  393. }
  394. void SoftwareGLContext::gl_matrix_mode(GLenum mode)
  395. {
  396. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_matrix_mode, mode);
  397. if (m_in_draw_state) {
  398. m_error = GL_INVALID_OPERATION;
  399. return;
  400. }
  401. if (mode < GL_MODELVIEW || mode > GL_PROJECTION) {
  402. m_error = GL_INVALID_ENUM;
  403. return;
  404. }
  405. m_current_matrix_mode = mode;
  406. m_error = GL_NO_ERROR;
  407. }
  408. void SoftwareGLContext::gl_push_matrix()
  409. {
  410. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_push_matrix);
  411. if (m_in_draw_state) {
  412. m_error = GL_INVALID_OPERATION;
  413. return;
  414. }
  415. dbgln_if(GL_DEBUG, "glPushMatrix(): Pushing matrix to the matrix stack (matrix_mode {})", m_current_matrix_mode);
  416. switch (m_current_matrix_mode) {
  417. case GL_PROJECTION:
  418. if (m_projection_matrix_stack.size() >= MATRIX_STACK_LIMIT) {
  419. m_error = GL_STACK_OVERFLOW;
  420. return;
  421. }
  422. m_projection_matrix_stack.append(m_projection_matrix);
  423. break;
  424. case GL_MODELVIEW:
  425. if (m_model_view_matrix_stack.size() >= MATRIX_STACK_LIMIT) {
  426. m_error = GL_STACK_OVERFLOW;
  427. return;
  428. }
  429. m_model_view_matrix_stack.append(m_model_view_matrix);
  430. break;
  431. default:
  432. dbgln_if(GL_DEBUG, "glPushMatrix(): Attempt to push matrix with invalid matrix mode {})", m_current_matrix_mode);
  433. return;
  434. }
  435. m_error = GL_NO_ERROR;
  436. }
  437. void SoftwareGLContext::gl_pop_matrix()
  438. {
  439. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_pop_matrix);
  440. if (m_in_draw_state) {
  441. m_error = GL_INVALID_OPERATION;
  442. return;
  443. }
  444. dbgln_if(GL_DEBUG, "glPopMatrix(): Popping matrix from matrix stack (matrix_mode = {})", m_current_matrix_mode);
  445. // FIXME: Make sure stack::top() doesn't cause any nasty issues if it's empty (that could result in a lockup/hang)
  446. switch (m_current_matrix_mode) {
  447. case GL_PROJECTION:
  448. if (m_projection_matrix_stack.size() == 0) {
  449. m_error = GL_STACK_UNDERFLOW;
  450. return;
  451. }
  452. m_projection_matrix = m_projection_matrix_stack.take_last();
  453. break;
  454. case GL_MODELVIEW:
  455. if (m_model_view_matrix_stack.size() == 0) {
  456. m_error = GL_STACK_UNDERFLOW;
  457. return;
  458. }
  459. m_model_view_matrix = m_model_view_matrix_stack.take_last();
  460. break;
  461. default:
  462. dbgln_if(GL_DEBUG, "glPopMatrix(): Attempt to pop matrix with invalid matrix mode, {}", m_current_matrix_mode);
  463. return;
  464. }
  465. m_error = GL_NO_ERROR;
  466. }
  467. void SoftwareGLContext::gl_rotate(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)
  468. {
  469. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_rotate, angle, x, y, z);
  470. if (m_in_draw_state) {
  471. m_error = GL_INVALID_OPERATION;
  472. return;
  473. }
  474. FloatVector3 axis = { (float)x, (float)y, (float)z };
  475. axis.normalize();
  476. auto rotation_mat = Gfx::rotation_matrix(axis, static_cast<float>(angle));
  477. if (m_current_matrix_mode == GL_MODELVIEW)
  478. m_model_view_matrix = m_model_view_matrix * rotation_mat;
  479. else if (m_current_matrix_mode == GL_PROJECTION)
  480. m_projection_matrix = m_projection_matrix * rotation_mat;
  481. m_error = GL_NO_ERROR;
  482. }
  483. void SoftwareGLContext::gl_scale(GLdouble x, GLdouble y, GLdouble z)
  484. {
  485. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_scale, x, y, z);
  486. if (m_in_draw_state) {
  487. m_error = GL_INVALID_OPERATION;
  488. return;
  489. }
  490. if (m_current_matrix_mode == GL_MODELVIEW) {
  491. m_model_view_matrix = m_model_view_matrix * Gfx::scale_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  492. } else if (m_current_matrix_mode == GL_PROJECTION) {
  493. m_projection_matrix = m_projection_matrix * Gfx::scale_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  494. }
  495. m_error = GL_NO_ERROR;
  496. }
  497. void SoftwareGLContext::gl_translate(GLdouble x, GLdouble y, GLdouble z)
  498. {
  499. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_translate, x, y, z);
  500. if (m_in_draw_state) {
  501. m_error = GL_INVALID_OPERATION;
  502. return;
  503. }
  504. if (m_current_matrix_mode == GL_MODELVIEW) {
  505. m_model_view_matrix = m_model_view_matrix * Gfx::translation_matrix(FloatVector3 { (float)x, (float)y, (float)z });
  506. } else if (m_current_matrix_mode == GL_PROJECTION) {
  507. m_projection_matrix = m_projection_matrix * Gfx::translation_matrix(FloatVector3 { (float)x, (float)y, (float)z });
  508. }
  509. m_error = GL_NO_ERROR;
  510. }
  511. void SoftwareGLContext::gl_vertex(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
  512. {
  513. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_vertex, x, y, z, w);
  514. GLVertex vertex;
  515. vertex.x = x;
  516. vertex.y = y;
  517. vertex.z = z;
  518. vertex.w = w;
  519. vertex.r = m_current_vertex_color.x();
  520. vertex.g = m_current_vertex_color.y();
  521. vertex.b = m_current_vertex_color.z();
  522. vertex.a = m_current_vertex_color.w();
  523. // FIXME: This is to suppress any -Wunused errors
  524. vertex.w = 0.0f;
  525. vertex.u = 0.0f;
  526. vertex.v = 0.0f;
  527. vertex_list.append(vertex);
  528. m_error = GL_NO_ERROR;
  529. }
  530. void SoftwareGLContext::gl_viewport(GLint x, GLint y, GLsizei width, GLsizei height)
  531. {
  532. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_viewport, x, y, width, height);
  533. if (m_in_draw_state) {
  534. m_error = GL_INVALID_OPERATION;
  535. return;
  536. }
  537. (void)(x);
  538. (void)(y);
  539. (void)(width);
  540. (void)(height);
  541. m_error = GL_NO_ERROR;
  542. }
  543. void SoftwareGLContext::gl_enable(GLenum capability)
  544. {
  545. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_enable, capability);
  546. if (m_in_draw_state) {
  547. m_error = GL_INVALID_OPERATION;
  548. return;
  549. }
  550. auto rasterizer_options = m_rasterizer.options();
  551. bool update_rasterizer_options = false;
  552. switch (capability) {
  553. case GL_CULL_FACE:
  554. m_cull_faces = true;
  555. break;
  556. case GL_DEPTH_TEST:
  557. m_depth_test_enabled = true;
  558. rasterizer_options.enable_depth_test = true;
  559. update_rasterizer_options = true;
  560. break;
  561. case GL_BLEND:
  562. m_blend_enabled = true;
  563. rasterizer_options.enable_blending = true;
  564. update_rasterizer_options = true;
  565. break;
  566. case GL_ALPHA_TEST:
  567. m_alpha_test_enabled = true;
  568. rasterizer_options.enable_alpha_test = true;
  569. update_rasterizer_options = true;
  570. break;
  571. default:
  572. m_error = GL_INVALID_ENUM;
  573. break;
  574. }
  575. if (update_rasterizer_options)
  576. m_rasterizer.set_options(rasterizer_options);
  577. }
  578. void SoftwareGLContext::gl_disable(GLenum capability)
  579. {
  580. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_disable, capability);
  581. if (m_in_draw_state) {
  582. m_error = GL_INVALID_OPERATION;
  583. return;
  584. }
  585. auto rasterizer_options = m_rasterizer.options();
  586. bool update_rasterizer_options = false;
  587. switch (capability) {
  588. case GL_CULL_FACE:
  589. m_cull_faces = false;
  590. break;
  591. case GL_DEPTH_TEST:
  592. m_depth_test_enabled = false;
  593. rasterizer_options.enable_depth_test = false;
  594. update_rasterizer_options = true;
  595. break;
  596. case GL_BLEND:
  597. m_blend_enabled = false;
  598. rasterizer_options.enable_blending = false;
  599. update_rasterizer_options = false;
  600. break;
  601. case GL_ALPHA_TEST:
  602. m_alpha_test_enabled = false;
  603. rasterizer_options.enable_alpha_test = false;
  604. update_rasterizer_options = false;
  605. break;
  606. default:
  607. m_error = GL_INVALID_ENUM;
  608. break;
  609. }
  610. if (update_rasterizer_options)
  611. m_rasterizer.set_options(rasterizer_options);
  612. }
  613. void SoftwareGLContext::gl_gen_textures(GLsizei n, GLuint* textures)
  614. {
  615. if (n < 0) {
  616. m_error = GL_INVALID_VALUE;
  617. return;
  618. }
  619. if (m_in_draw_state) {
  620. m_error = GL_INVALID_OPERATION;
  621. return;
  622. }
  623. m_name_allocator.allocate(n, textures);
  624. // Let's allocate a new texture for each texture name
  625. for (auto i = 0; i < n; i++) {
  626. GLuint name = textures[i];
  627. m_allocated_textures.set(name, adopt_ref(*new Texture()));
  628. }
  629. }
  630. void SoftwareGLContext::gl_delete_textures(GLsizei n, const GLuint* textures)
  631. {
  632. if (n < 0) {
  633. m_error = GL_INVALID_VALUE;
  634. return;
  635. }
  636. if (m_in_draw_state) {
  637. m_error = GL_INVALID_OPERATION;
  638. return;
  639. }
  640. m_name_allocator.free(n, textures);
  641. // Let's allocate a new texture for each texture name
  642. for (auto i = 0; i < n; i++) {
  643. GLuint name = textures[i];
  644. m_allocated_textures.remove(name);
  645. }
  646. }
  647. void SoftwareGLContext::gl_tex_image_2d(GLenum target, GLint level, GLint internal_format, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* data)
  648. {
  649. if (m_in_draw_state) {
  650. m_error = GL_INVALID_OPERATION;
  651. return;
  652. }
  653. // We only support GL_TEXTURE_2D for now
  654. if (target != GL_TEXTURE_2D) {
  655. m_error = GL_INVALID_ENUM;
  656. return;
  657. }
  658. // We only support symbolic constants for now
  659. if (!(internal_format == GL_RGB || internal_format == GL_RGBA)) {
  660. m_error = GL_INVALID_VALUE;
  661. return;
  662. }
  663. if (type != GL_UNSIGNED_BYTE) {
  664. m_error = GL_INVALID_VALUE;
  665. return;
  666. }
  667. if (level < 0 || level > Texture::LOG2_MAX_TEXTURE_SIZE) {
  668. m_error = GL_INVALID_VALUE;
  669. return;
  670. }
  671. if (width < 0 || height < 0 || width > (2 + Texture::MAX_TEXTURE_SIZE) || height > (2 + Texture::MAX_TEXTURE_SIZE)) {
  672. m_error = GL_INVALID_VALUE;
  673. return;
  674. }
  675. if ((width & 2) != 0 || (height & 2) != 0) {
  676. m_error = GL_INVALID_VALUE;
  677. return;
  678. }
  679. if (border < 0 || border > 1) {
  680. m_error = GL_INVALID_VALUE;
  681. return;
  682. }
  683. // TODO: Load texture from the currently active texture unit
  684. // This is to test the functionality of texture data upload
  685. m_allocated_textures.find(1)->value->upload_texture_data(target, level, internal_format, width, height, border, format, type, data);
  686. }
  687. void SoftwareGLContext::gl_front_face(GLenum face)
  688. {
  689. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_front_face, face);
  690. if (face < GL_CW || face > GL_CCW) {
  691. m_error = GL_INVALID_ENUM;
  692. return;
  693. }
  694. m_front_face = face;
  695. }
  696. void SoftwareGLContext::gl_cull_face(GLenum cull_mode)
  697. {
  698. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_cull_face, cull_mode);
  699. if (cull_mode < GL_FRONT || cull_mode > GL_FRONT_AND_BACK) {
  700. m_error = GL_INVALID_ENUM;
  701. return;
  702. }
  703. m_culled_sides = cull_mode;
  704. }
  705. GLuint SoftwareGLContext::gl_gen_lists(GLsizei range)
  706. {
  707. if (range <= 0) {
  708. m_error = GL_INVALID_VALUE;
  709. return 0;
  710. }
  711. if (m_in_draw_state) {
  712. m_error = GL_INVALID_OPERATION;
  713. return 0;
  714. }
  715. auto initial_entry = m_listings.size();
  716. m_listings.resize(range + initial_entry);
  717. return initial_entry + 1;
  718. }
  719. void SoftwareGLContext::gl_call_list(GLuint list)
  720. {
  721. if (m_gl_call_depth > max_allowed_gl_call_depth)
  722. return;
  723. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_call_list, list);
  724. if (m_listings.size() < list)
  725. return;
  726. TemporaryChange change { m_gl_call_depth, m_gl_call_depth + 1 };
  727. auto& listing = m_listings[list - 1];
  728. for (auto& entry : listing.entries) {
  729. entry.function.visit([&](auto& function) {
  730. entry.arguments.visit([&](auto& arguments) {
  731. auto apply = [&]<typename... Args>(Args && ... args)
  732. {
  733. if constexpr (requires { (this->*function)(forward<Args>(args)...); })
  734. (this->*function)(forward<Args>(args)...);
  735. };
  736. arguments.apply_as_args(apply);
  737. });
  738. });
  739. }
  740. }
  741. void SoftwareGLContext::gl_delete_lists(GLuint list, GLsizei range)
  742. {
  743. if (m_listings.size() < list || m_listings.size() <= list + range)
  744. return;
  745. for (auto& entry : m_listings.span().slice(list - 1, range))
  746. entry.entries.clear();
  747. }
  748. void SoftwareGLContext::gl_end_list()
  749. {
  750. if (m_in_draw_state) {
  751. m_error = GL_INVALID_OPERATION;
  752. return;
  753. }
  754. if (!m_current_listing_index.has_value()) {
  755. m_error = GL_INVALID_OPERATION;
  756. return;
  757. }
  758. m_listings[m_current_listing_index->index] = move(m_current_listing_index->listing);
  759. m_current_listing_index.clear();
  760. }
  761. void SoftwareGLContext::gl_new_list(GLuint list, GLenum mode)
  762. {
  763. if (list == 0) {
  764. m_error = GL_INVALID_VALUE;
  765. return;
  766. }
  767. if (mode != GL_COMPILE && mode != GL_COMPILE_AND_EXECUTE) {
  768. m_error = GL_INVALID_ENUM;
  769. return;
  770. }
  771. if (m_in_draw_state) {
  772. m_error = GL_INVALID_OPERATION;
  773. return;
  774. }
  775. if (m_current_listing_index.has_value()) {
  776. m_error = GL_INVALID_OPERATION;
  777. return;
  778. }
  779. if (m_listings.size() < list)
  780. return;
  781. m_current_listing_index = CurrentListing { {}, static_cast<size_t>(list - 1), mode };
  782. }
  783. void SoftwareGLContext::gl_flush()
  784. {
  785. if (m_in_draw_state) {
  786. m_error = GL_INVALID_OPERATION;
  787. return;
  788. }
  789. // No-op since SoftwareGLContext is completely synchronous at the moment
  790. }
  791. void SoftwareGLContext::gl_finish()
  792. {
  793. if (m_in_draw_state) {
  794. m_error = GL_INVALID_OPERATION;
  795. return;
  796. }
  797. // No-op since SoftwareGLContext is completely synchronous at the moment
  798. }
  799. void SoftwareGLContext::gl_blend_func(GLenum src_factor, GLenum dst_factor)
  800. {
  801. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_blend_func, src_factor, dst_factor);
  802. if (m_in_draw_state) {
  803. m_error = GL_INVALID_OPERATION;
  804. return;
  805. }
  806. // FIXME: The list of allowed enums differs between API versions
  807. // This was taken from the 2.0 spec on https://docs.gl/gl2/glBlendFunc
  808. if (!(src_factor == GL_ZERO
  809. || src_factor == GL_ONE
  810. || src_factor == GL_SRC_COLOR
  811. || src_factor == GL_ONE_MINUS_SRC_COLOR
  812. || src_factor == GL_DST_COLOR
  813. || src_factor == GL_ONE_MINUS_DST_COLOR
  814. || src_factor == GL_SRC_ALPHA
  815. || src_factor == GL_ONE_MINUS_SRC_ALPHA
  816. || src_factor == GL_DST_ALPHA
  817. || src_factor == GL_ONE_MINUS_DST_ALPHA
  818. || src_factor == GL_CONSTANT_COLOR
  819. || src_factor == GL_ONE_MINUS_CONSTANT_COLOR
  820. || src_factor == GL_CONSTANT_ALPHA
  821. || src_factor == GL_ONE_MINUS_CONSTANT_ALPHA
  822. || src_factor == GL_SRC_ALPHA_SATURATE)) {
  823. m_error = GL_INVALID_ENUM;
  824. return;
  825. }
  826. if (!(dst_factor == GL_ZERO
  827. || dst_factor == GL_ONE
  828. || dst_factor == GL_SRC_COLOR
  829. || dst_factor == GL_ONE_MINUS_SRC_COLOR
  830. || dst_factor == GL_DST_COLOR
  831. || dst_factor == GL_ONE_MINUS_DST_COLOR
  832. || dst_factor == GL_SRC_ALPHA
  833. || dst_factor == GL_ONE_MINUS_SRC_ALPHA
  834. || dst_factor == GL_DST_ALPHA
  835. || dst_factor == GL_ONE_MINUS_DST_ALPHA
  836. || dst_factor == GL_CONSTANT_COLOR
  837. || dst_factor == GL_ONE_MINUS_CONSTANT_COLOR
  838. || dst_factor == GL_CONSTANT_ALPHA
  839. || dst_factor == GL_ONE_MINUS_CONSTANT_ALPHA)) {
  840. m_error = GL_INVALID_ENUM;
  841. return;
  842. }
  843. m_blend_source_factor = src_factor;
  844. m_blend_destination_factor = dst_factor;
  845. auto options = m_rasterizer.options();
  846. options.blend_source_factor = m_blend_source_factor;
  847. options.blend_destination_factor = m_blend_destination_factor;
  848. m_rasterizer.set_options(options);
  849. }
  850. void SoftwareGLContext::gl_shade_model(GLenum mode)
  851. {
  852. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_shade_model, mode);
  853. if (m_in_draw_state) {
  854. m_error = GL_INVALID_OPERATION;
  855. return;
  856. }
  857. if (mode != GL_FLAT && mode != GL_SMOOTH) {
  858. m_error = GL_INVALID_ENUM;
  859. return;
  860. }
  861. auto options = m_rasterizer.options();
  862. options.shade_smooth = (mode == GL_SMOOTH);
  863. m_rasterizer.set_options(options);
  864. }
  865. void SoftwareGLContext::gl_alpha_func(GLenum func, GLclampf ref)
  866. {
  867. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_alpha_func, func, ref);
  868. if (m_in_draw_state) {
  869. m_error = GL_INVALID_OPERATION;
  870. return;
  871. }
  872. if (func < GL_NEVER || func > GL_ALWAYS) {
  873. m_error = GL_INVALID_ENUM;
  874. return;
  875. }
  876. m_alpha_test_func = func;
  877. m_alpha_test_ref_value = ref;
  878. auto options = m_rasterizer.options();
  879. options.alpha_test_func = m_alpha_test_func;
  880. options.alpha_test_ref_value = m_alpha_test_ref_value;
  881. m_rasterizer.set_options(options);
  882. }
  883. void SoftwareGLContext::gl_hint(GLenum target, GLenum mode)
  884. {
  885. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_hint, target, mode);
  886. if (m_in_draw_state) {
  887. m_error = GL_INVALID_OPERATION;
  888. return;
  889. }
  890. if (target != GL_PERSPECTIVE_CORRECTION_HINT
  891. && target != GL_POINT_SMOOTH_HINT
  892. && target != GL_LINE_SMOOTH_HINT
  893. && target != GL_POLYGON_SMOOTH_HINT
  894. && target != GL_FOG_HINT
  895. && target != GL_GENERATE_MIPMAP_HINT
  896. && target != GL_TEXTURE_COMPRESSION_HINT) {
  897. m_error = GL_INVALID_ENUM;
  898. return;
  899. }
  900. if (mode != GL_DONT_CARE
  901. && mode != GL_FASTEST
  902. && mode != GL_NICEST) {
  903. m_error = GL_INVALID_ENUM;
  904. return;
  905. }
  906. // According to the spec implementors are free to ignore glHint. So we do.
  907. }
  908. void SoftwareGLContext::gl_read_buffer(GLenum mode)
  909. {
  910. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_read_buffer, mode);
  911. if (m_in_draw_state) {
  912. m_error = GL_INVALID_OPERATION;
  913. return;
  914. }
  915. // FIXME: Also allow aux buffers GL_AUX0 through GL_AUX3 here
  916. // plus any aux buffer between 0 and GL_AUX_BUFFERS
  917. if (mode != GL_FRONT_LEFT
  918. && mode != GL_FRONT_RIGHT
  919. && mode != GL_BACK_LEFT
  920. && mode != GL_BACK_RIGHT
  921. && mode != GL_FRONT
  922. && mode != GL_BACK
  923. && mode != GL_LEFT
  924. && mode != GL_RIGHT) {
  925. m_error = GL_INVALID_ENUM;
  926. return;
  927. }
  928. // FIXME: We do not currently have aux buffers, so make it an invalid
  929. // operation to select anything but front or back buffers. Also we do
  930. // not allow selecting the stereoscopic RIGHT buffers since we do not
  931. // have them configured.
  932. if (mode != GL_FRONT_LEFT
  933. && mode != GL_FRONT
  934. && mode != GL_BACK_LEFT
  935. && mode != GL_BACK
  936. && mode != GL_FRONT
  937. && mode != GL_BACK
  938. && mode != GL_LEFT) {
  939. m_error = GL_INVALID_OPERATION;
  940. return;
  941. }
  942. m_current_read_buffer = mode;
  943. }
  944. void SoftwareGLContext::gl_read_pixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels)
  945. {
  946. if (m_in_draw_state) {
  947. m_error = GL_INVALID_OPERATION;
  948. return;
  949. }
  950. // Check for negative width/height omitted because GLsizei is unsigned in our implementation
  951. if (format != GL_COLOR_INDEX
  952. && format != GL_STENCIL_INDEX
  953. && format != GL_DEPTH_COMPONENT
  954. && format != GL_RED
  955. && format != GL_GREEN
  956. && format != GL_BLUE
  957. && format != GL_ALPHA
  958. && format != GL_RGB
  959. && format != GL_RGBA
  960. && format != GL_LUMINANCE
  961. && format != GL_LUMINANCE_ALPHA) {
  962. m_error = GL_INVALID_ENUM;
  963. return;
  964. }
  965. if (type != GL_UNSIGNED_BYTE
  966. && type != GL_BYTE
  967. && type != GL_BITMAP
  968. && type != GL_UNSIGNED_SHORT
  969. && type != GL_SHORT
  970. && type != GL_BLUE
  971. && type != GL_UNSIGNED_INT
  972. && type != GL_INT
  973. && type != GL_FLOAT) {
  974. m_error = GL_INVALID_ENUM;
  975. return;
  976. }
  977. if (format == GL_COLOR_INDEX) {
  978. // FIXME: We only support RGBA buffers for now.
  979. // Once we add support for indexed color modes do the correct check here
  980. m_error = GL_INVALID_OPERATION;
  981. return;
  982. }
  983. if (format == GL_STENCIL_INDEX) {
  984. // FIXME: We do not have stencil buffers yet
  985. // Once we add support for stencil buffers do the correct check here
  986. m_error = GL_INVALID_OPERATION;
  987. return;
  988. }
  989. if (format == GL_DEPTH_COMPONENT) {
  990. // FIXME: This check needs to be a bit more sophisticated. Currently the buffers
  991. // are hardcoded. Once we add proper structures for them we need to correct this check
  992. if (m_current_read_buffer == GL_FRONT
  993. || m_current_read_buffer == GL_FRONT_LEFT
  994. || m_current_read_buffer == GL_FRONT_RIGHT) {
  995. // Error because only back buffer has a depth buffer
  996. m_error = GL_INVALID_OPERATION;
  997. return;
  998. }
  999. }
  1000. // Some helper functions for converting float values to integer types
  1001. auto float_to_i8 = [](float f) -> GLchar {
  1002. return static_cast<GLchar>((0x7f * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1003. };
  1004. auto float_to_i16 = [](float f) -> GLshort {
  1005. return static_cast<GLshort>((0x7fff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1006. };
  1007. auto float_to_i32 = [](float f) -> GLint {
  1008. return static_cast<GLint>((0x7fffffff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1009. };
  1010. auto float_to_u8 = [](float f) -> GLubyte {
  1011. return static_cast<GLubyte>(0xff * min(max(f, 0.0f), 1.0f));
  1012. };
  1013. auto float_to_u16 = [](float f) -> GLushort {
  1014. return static_cast<GLushort>(0xffff * min(max(f, 0.0f), 1.0f));
  1015. };
  1016. auto float_to_u32 = [](float f) -> GLuint {
  1017. return static_cast<GLuint>(0xffffffff * min(max(f, 0.0f), 1.0f));
  1018. };
  1019. if (format == GL_DEPTH_COMPONENT) {
  1020. // Read from depth buffer
  1021. for (size_t i = 0; i < height; ++i) {
  1022. for (size_t j = 0; j < width; ++j) {
  1023. float depth = m_rasterizer.get_depthbuffer_value(x + j, y + i);
  1024. switch (type) {
  1025. case GL_BYTE:
  1026. reinterpret_cast<GLchar*>(pixels)[i * width + j] = float_to_i8(depth);
  1027. break;
  1028. case GL_SHORT:
  1029. reinterpret_cast<GLshort*>(pixels)[i * width + j] = float_to_i16(depth);
  1030. break;
  1031. case GL_INT:
  1032. reinterpret_cast<GLint*>(pixels)[i * width + j] = float_to_i32(depth);
  1033. break;
  1034. case GL_UNSIGNED_BYTE:
  1035. reinterpret_cast<GLubyte*>(pixels)[i * width + j] = float_to_u8(depth);
  1036. break;
  1037. case GL_UNSIGNED_SHORT:
  1038. reinterpret_cast<GLushort*>(pixels)[i * width + j] = float_to_u16(depth);
  1039. break;
  1040. case GL_UNSIGNED_INT:
  1041. reinterpret_cast<GLuint*>(pixels)[i * width + j] = float_to_u32(depth);
  1042. break;
  1043. case GL_FLOAT:
  1044. reinterpret_cast<GLfloat*>(pixels)[i * width + j] = min(max(depth, 0.0f), 1.0f);
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. return;
  1050. }
  1051. bool write_red = false;
  1052. bool write_green = false;
  1053. bool write_blue = false;
  1054. bool write_alpha = false;
  1055. size_t component_count = 0;
  1056. size_t component_size = 0;
  1057. size_t red_offset = 0;
  1058. size_t green_offset = 0;
  1059. size_t blue_offset = 0;
  1060. size_t alpha_offset = 0;
  1061. char* red_ptr = nullptr;
  1062. char* green_ptr = nullptr;
  1063. char* blue_ptr = nullptr;
  1064. char* alpha_ptr = nullptr;
  1065. switch (format) {
  1066. case GL_RGB:
  1067. write_red = true;
  1068. write_green = true;
  1069. write_blue = true;
  1070. component_count = 3;
  1071. red_offset = 2;
  1072. green_offset = 1;
  1073. blue_offset = 0;
  1074. break;
  1075. case GL_RGBA:
  1076. write_red = true;
  1077. write_green = true;
  1078. write_blue = true;
  1079. write_alpha = true;
  1080. component_count = 4;
  1081. red_offset = 3;
  1082. green_offset = 2;
  1083. blue_offset = 1;
  1084. alpha_offset = 0;
  1085. break;
  1086. case GL_RED:
  1087. write_red = true;
  1088. component_count = 1;
  1089. red_offset = 0;
  1090. break;
  1091. case GL_GREEN:
  1092. write_green = true;
  1093. component_count = 1;
  1094. green_offset = 0;
  1095. break;
  1096. case GL_BLUE:
  1097. write_blue = true;
  1098. component_count = 1;
  1099. blue_offset = 0;
  1100. break;
  1101. case GL_ALPHA:
  1102. write_alpha = true;
  1103. component_count = 1;
  1104. alpha_offset = 0;
  1105. break;
  1106. }
  1107. switch (type) {
  1108. case GL_BYTE:
  1109. case GL_UNSIGNED_BYTE:
  1110. component_size = 1;
  1111. break;
  1112. case GL_SHORT:
  1113. case GL_UNSIGNED_SHORT:
  1114. component_size = 2;
  1115. break;
  1116. case GL_INT:
  1117. case GL_UNSIGNED_INT:
  1118. case GL_FLOAT:
  1119. component_size = 4;
  1120. break;
  1121. }
  1122. char* out_ptr = reinterpret_cast<char*>(pixels);
  1123. for (int i = 0; i < (int)height; ++i) {
  1124. for (int j = 0; j < (int)width; ++j) {
  1125. Gfx::RGBA32 color {};
  1126. if (m_current_read_buffer == GL_FRONT || m_current_read_buffer == GL_LEFT || m_current_read_buffer == GL_FRONT_LEFT) {
  1127. if (y + i >= m_frontbuffer->width() || x + j >= m_frontbuffer->height())
  1128. color = 0;
  1129. else
  1130. color = m_frontbuffer->scanline(y + i)[x + j];
  1131. } else {
  1132. color = m_rasterizer.get_backbuffer_pixel(x + j, y + i);
  1133. }
  1134. float red = ((color >> 24) & 0xff) / 255.0f;
  1135. float green = ((color >> 16) & 0xff) / 255.0f;
  1136. float blue = ((color >> 8) & 0xff) / 255.0f;
  1137. float alpha = (color & 0xff) / 255.0f;
  1138. // FIXME: Set up write pointers based on selected endianness (glPixelStore)
  1139. red_ptr = out_ptr + (component_size * red_offset);
  1140. green_ptr = out_ptr + (component_size * green_offset);
  1141. blue_ptr = out_ptr + (component_size * blue_offset);
  1142. alpha_ptr = out_ptr + (component_size * alpha_offset);
  1143. switch (type) {
  1144. case GL_BYTE:
  1145. if (write_red)
  1146. *reinterpret_cast<GLchar*>(red_ptr) = float_to_i8(red);
  1147. if (write_green)
  1148. *reinterpret_cast<GLchar*>(green_ptr) = float_to_i8(green);
  1149. if (write_blue)
  1150. *reinterpret_cast<GLchar*>(blue_ptr) = float_to_i8(blue);
  1151. if (write_alpha)
  1152. *reinterpret_cast<GLchar*>(alpha_ptr) = float_to_i8(alpha);
  1153. break;
  1154. case GL_UNSIGNED_BYTE:
  1155. if (write_red)
  1156. *reinterpret_cast<GLubyte*>(red_ptr) = float_to_u8(red);
  1157. if (write_green)
  1158. *reinterpret_cast<GLubyte*>(green_ptr) = float_to_u8(green);
  1159. if (write_blue)
  1160. *reinterpret_cast<GLubyte*>(blue_ptr) = float_to_u8(blue);
  1161. if (write_alpha)
  1162. *reinterpret_cast<GLubyte*>(alpha_ptr) = float_to_u8(alpha);
  1163. break;
  1164. case GL_SHORT:
  1165. if (write_red)
  1166. *reinterpret_cast<GLshort*>(red_ptr) = float_to_i16(red);
  1167. if (write_green)
  1168. *reinterpret_cast<GLshort*>(green_ptr) = float_to_i16(green);
  1169. if (write_blue)
  1170. *reinterpret_cast<GLshort*>(blue_ptr) = float_to_i16(blue);
  1171. if (write_alpha)
  1172. *reinterpret_cast<GLshort*>(alpha_ptr) = float_to_i16(alpha);
  1173. break;
  1174. case GL_UNSIGNED_SHORT:
  1175. if (write_red)
  1176. *reinterpret_cast<GLushort*>(red_ptr) = float_to_u16(red);
  1177. if (write_green)
  1178. *reinterpret_cast<GLushort*>(green_ptr) = float_to_u16(green);
  1179. if (write_blue)
  1180. *reinterpret_cast<GLushort*>(blue_ptr) = float_to_u16(blue);
  1181. if (write_alpha)
  1182. *reinterpret_cast<GLushort*>(alpha_ptr) = float_to_u16(alpha);
  1183. break;
  1184. case GL_INT:
  1185. if (write_red)
  1186. *reinterpret_cast<GLint*>(red_ptr) = float_to_i32(red);
  1187. if (write_green)
  1188. *reinterpret_cast<GLint*>(green_ptr) = float_to_i32(green);
  1189. if (write_blue)
  1190. *reinterpret_cast<GLint*>(blue_ptr) = float_to_i32(blue);
  1191. if (write_alpha)
  1192. *reinterpret_cast<GLint*>(alpha_ptr) = float_to_i32(alpha);
  1193. break;
  1194. case GL_UNSIGNED_INT:
  1195. if (write_red)
  1196. *reinterpret_cast<GLuint*>(red_ptr) = float_to_u32(red);
  1197. if (write_green)
  1198. *reinterpret_cast<GLuint*>(green_ptr) = float_to_u32(green);
  1199. if (write_blue)
  1200. *reinterpret_cast<GLuint*>(blue_ptr) = float_to_u32(blue);
  1201. if (write_alpha)
  1202. *reinterpret_cast<GLuint*>(alpha_ptr) = float_to_u32(alpha);
  1203. break;
  1204. case GL_FLOAT:
  1205. if (write_red)
  1206. *reinterpret_cast<GLfloat*>(red_ptr) = min(max(red, 0.0f), 1.0f);
  1207. if (write_green)
  1208. *reinterpret_cast<GLfloat*>(green_ptr) = min(max(green, 0.0f), 1.0f);
  1209. if (write_blue)
  1210. *reinterpret_cast<GLfloat*>(blue_ptr) = min(max(blue, 0.0f), 1.0f);
  1211. if (write_alpha)
  1212. *reinterpret_cast<GLfloat*>(alpha_ptr) = min(max(alpha, 0.0f), 1.0f);
  1213. break;
  1214. }
  1215. out_ptr += component_size * component_count;
  1216. }
  1217. }
  1218. }
  1219. void SoftwareGLContext::present()
  1220. {
  1221. m_rasterizer.blit_to(*m_frontbuffer);
  1222. }
  1223. }