SoftwareGLContext.cpp 45 KB

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