SoftwareGLContext.cpp 47 KB

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