GLContext.cpp 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764
  1. /*
  2. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  3. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  4. * Copyright (c) 2022, Jelle Raaijmakers <jelle@gmta.nl>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Assertions.h>
  9. #include <AK/Debug.h>
  10. #include <AK/Format.h>
  11. #include <AK/QuickSort.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/TemporaryChange.h>
  14. #include <AK/Variant.h>
  15. #include <AK/Vector.h>
  16. #include <LibGL/GLContext.h>
  17. #include <LibGPU/Device.h>
  18. #include <LibGPU/Enums.h>
  19. #include <LibGPU/ImageFormat.h>
  20. #include <LibGfx/Bitmap.h>
  21. #include <LibGfx/Painter.h>
  22. #include <LibGfx/Vector4.h>
  23. __attribute__((visibility("hidden"))) GL::GLContext* g_gl_context;
  24. namespace GL {
  25. static constexpr size_t MODELVIEW_MATRIX_STACK_LIMIT = 64;
  26. static constexpr size_t PROJECTION_MATRIX_STACK_LIMIT = 8;
  27. static constexpr size_t TEXTURE_MATRIX_STACK_LIMIT = 8;
  28. #define APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(name, ...) \
  29. if (should_append_to_listing()) { \
  30. append_to_listing<&GLContext::name>(__VA_ARGS__); \
  31. if (!should_execute_after_appending_to_listing()) \
  32. return; \
  33. }
  34. #define APPEND_TO_CALL_LIST_WITH_ARG_AND_RETURN_IF_NEEDED(name, arg) \
  35. if (should_append_to_listing()) { \
  36. auto ptr = store_in_listing(arg); \
  37. append_to_listing<&GLContext::name>(*ptr); \
  38. if (!should_execute_after_appending_to_listing()) \
  39. return; \
  40. }
  41. #define RETURN_WITH_ERROR_IF(condition, error) \
  42. if (condition) { \
  43. dbgln_if(GL_DEBUG, "{}(): error {:#x}", __func__, error); \
  44. if (m_error == GL_NO_ERROR) \
  45. m_error = error; \
  46. return; \
  47. }
  48. #define RETURN_VALUE_WITH_ERROR_IF(condition, error, return_value) \
  49. if (condition) { \
  50. dbgln_if(GL_DEBUG, "{}(): error {:#x}", __func__, error); \
  51. if (m_error == GL_NO_ERROR) \
  52. m_error = error; \
  53. return return_value; \
  54. }
  55. GLContext::GLContext(RefPtr<GPU::Driver> driver, NonnullOwnPtr<GPU::Device> device, Gfx::Bitmap& frontbuffer)
  56. : m_viewport { frontbuffer.rect() }
  57. , m_frontbuffer { frontbuffer }
  58. , m_driver { driver }
  59. , m_rasterizer { move(device) }
  60. , m_device_info { m_rasterizer->info() }
  61. {
  62. m_texture_units.resize(m_device_info.num_texture_units);
  63. m_active_texture_unit = &m_texture_units[0];
  64. // All texture units are initialized with default textures for all targets; these
  65. // can be referenced later on with texture name 0 in operations like glBindTexture().
  66. auto default_texture_2d = adopt_ref(*new Texture2D());
  67. m_default_textures.set(GL_TEXTURE_2D, default_texture_2d);
  68. for (auto& texture_unit : m_texture_units)
  69. texture_unit.set_texture_2d_target_texture(default_texture_2d);
  70. // Query the number lights from the device and set set up their state
  71. // locally in the GL
  72. m_light_states.resize(m_device_info.num_lights);
  73. // Set-up light0's state, as it has a different default state
  74. // to the other lights, as per the OpenGL 1.5 spec
  75. auto& light0 = m_light_states.at(0);
  76. light0.diffuse_intensity = { 1.0f, 1.0f, 1.0f, 1.0f };
  77. light0.specular_intensity = { 1.0f, 1.0f, 1.0f, 1.0f };
  78. m_light_state_is_dirty = true;
  79. m_client_side_texture_coord_array_enabled.resize(m_device_info.num_texture_units);
  80. m_client_tex_coord_pointer.resize(m_device_info.num_texture_units);
  81. m_current_vertex_tex_coord.resize(m_device_info.num_texture_units);
  82. for (auto& tex_coord : m_current_vertex_tex_coord)
  83. tex_coord = { 0.0f, 0.0f, 0.0f, 1.0f };
  84. // Initialize the texture coordinate generation coefficients
  85. // Indices 0,1,2,3 refer to the S,T,R and Q coordinate of the respective texture
  86. // coordinate generation config.
  87. m_texture_coordinate_generation.resize(m_device_info.num_texture_units);
  88. for (auto& texture_coordinate_generation : m_texture_coordinate_generation) {
  89. texture_coordinate_generation[0].object_plane_coefficients = { 1.0f, 0.0f, 0.0f, 0.0f };
  90. texture_coordinate_generation[0].eye_plane_coefficients = { 1.0f, 0.0f, 0.0f, 0.0f };
  91. texture_coordinate_generation[1].object_plane_coefficients = { 0.0f, 1.0f, 0.0f, 0.0f };
  92. texture_coordinate_generation[1].eye_plane_coefficients = { 0.0f, 1.0f, 0.0f, 0.0f };
  93. texture_coordinate_generation[2].object_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  94. texture_coordinate_generation[2].eye_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  95. texture_coordinate_generation[3].object_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  96. texture_coordinate_generation[3].eye_plane_coefficients = { 0.0f, 0.0f, 0.0f, 0.0f };
  97. }
  98. build_extension_string();
  99. }
  100. GLContext::~GLContext()
  101. {
  102. dbgln_if(GL_DEBUG, "GLContext::~GLContext() {:p}", this);
  103. if (g_gl_context == this)
  104. make_context_current(nullptr);
  105. }
  106. Optional<ContextParameter> GLContext::get_context_parameter(GLenum name)
  107. {
  108. switch (name) {
  109. case GL_ALPHA_BITS:
  110. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  111. case GL_ALPHA_TEST:
  112. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_alpha_test_enabled } };
  113. case GL_BLEND:
  114. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_blend_enabled } };
  115. case GL_BLEND_DST_ALPHA:
  116. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_blend_destination_factor) } };
  117. case GL_BLEND_SRC_ALPHA:
  118. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_blend_source_factor) } };
  119. case GL_BLUE_BITS:
  120. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  121. case GL_COLOR_MATERIAL:
  122. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_color_material_enabled } };
  123. case GL_COLOR_MATERIAL_FACE:
  124. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_color_material_face) } };
  125. case GL_COLOR_MATERIAL_MODE:
  126. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_color_material_mode) } };
  127. case GL_CULL_FACE:
  128. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_cull_faces } };
  129. case GL_DEPTH_BITS:
  130. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  131. case GL_DEPTH_TEST:
  132. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_depth_test_enabled } };
  133. case GL_DITHER:
  134. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_dither_enabled } };
  135. case GL_DOUBLEBUFFER:
  136. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = true } };
  137. case GL_FOG: {
  138. auto fog_enabled = m_rasterizer->options().fog_enabled;
  139. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = fog_enabled } };
  140. }
  141. case GL_GREEN_BITS:
  142. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  143. case GL_LIGHTING:
  144. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_lighting_enabled } };
  145. case GL_MAX_LIGHTS:
  146. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_device_info.num_lights) } };
  147. case GL_MAX_MODELVIEW_STACK_DEPTH:
  148. return ContextParameter { .type = GL_INT, .value = { .integer_value = MODELVIEW_MATRIX_STACK_LIMIT } };
  149. case GL_MAX_PROJECTION_STACK_DEPTH:
  150. return ContextParameter { .type = GL_INT, .value = { .integer_value = PROJECTION_MATRIX_STACK_LIMIT } };
  151. case GL_MAX_TEXTURE_SIZE:
  152. return ContextParameter { .type = GL_INT, .value = { .integer_value = 4096 } };
  153. case GL_MAX_TEXTURE_STACK_DEPTH:
  154. return ContextParameter { .type = GL_INT, .value = { .integer_value = TEXTURE_MATRIX_STACK_LIMIT } };
  155. case GL_MAX_TEXTURE_UNITS:
  156. return ContextParameter { .type = GL_INT, .value = { .integer_value = static_cast<GLint>(m_texture_units.size()) } };
  157. case GL_NORMALIZE:
  158. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_normalize } };
  159. case GL_PACK_ALIGNMENT:
  160. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_pack_alignment } };
  161. case GL_PACK_IMAGE_HEIGHT:
  162. return ContextParameter { .type = GL_BOOL, .value = { .integer_value = 0 } };
  163. case GL_PACK_LSB_FIRST:
  164. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  165. case GL_PACK_ROW_LENGTH:
  166. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  167. case GL_PACK_SKIP_PIXELS:
  168. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  169. case GL_PACK_SKIP_ROWS:
  170. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  171. case GL_PACK_SWAP_BYTES:
  172. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  173. case GL_POLYGON_OFFSET_FILL:
  174. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_depth_offset_enabled } };
  175. case GL_RED_BITS:
  176. return ContextParameter { .type = GL_INT, .value = { .integer_value = sizeof(float) * 8 } };
  177. case GL_SCISSOR_BOX: {
  178. auto scissor_box = m_rasterizer->options().scissor_box;
  179. return ContextParameter {
  180. .type = GL_INT,
  181. .count = 4,
  182. .value = {
  183. .integer_list = {
  184. scissor_box.x(),
  185. scissor_box.y(),
  186. scissor_box.width(),
  187. scissor_box.height(),
  188. } }
  189. };
  190. } break;
  191. case GL_SCISSOR_TEST: {
  192. auto scissor_enabled = m_rasterizer->options().scissor_enabled;
  193. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = scissor_enabled } };
  194. }
  195. case GL_STENCIL_BITS:
  196. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_device_info.stencil_bits } };
  197. case GL_STENCIL_CLEAR_VALUE:
  198. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_clear_stencil } };
  199. case GL_STENCIL_TEST:
  200. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = m_stencil_test_enabled } };
  201. case GL_TEXTURE_1D:
  202. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_1d_enabled() } };
  203. case GL_TEXTURE_2D:
  204. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_2d_enabled() } };
  205. case GL_TEXTURE_3D:
  206. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_3d_enabled() } };
  207. case GL_TEXTURE_CUBE_MAP:
  208. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = m_active_texture_unit->texture_cube_map_enabled() } };
  209. case GL_TEXTURE_GEN_Q:
  210. case GL_TEXTURE_GEN_R:
  211. case GL_TEXTURE_GEN_S:
  212. case GL_TEXTURE_GEN_T: {
  213. auto generation_enabled = texture_coordinate_generation(m_active_texture_unit_index, name).enabled;
  214. return ContextParameter { .type = GL_BOOL, .is_capability = true, .value = { .boolean_value = generation_enabled } };
  215. }
  216. case GL_UNPACK_ALIGNMENT:
  217. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_unpack_alignment } };
  218. case GL_UNPACK_IMAGE_HEIGHT:
  219. return ContextParameter { .type = GL_BOOL, .value = { .integer_value = 0 } };
  220. case GL_UNPACK_LSB_FIRST:
  221. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  222. case GL_UNPACK_ROW_LENGTH:
  223. return ContextParameter { .type = GL_INT, .value = { .integer_value = m_unpack_row_length } };
  224. case GL_UNPACK_SKIP_PIXELS:
  225. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  226. case GL_UNPACK_SKIP_ROWS:
  227. return ContextParameter { .type = GL_INT, .value = { .integer_value = 0 } };
  228. case GL_UNPACK_SWAP_BYTES:
  229. return ContextParameter { .type = GL_BOOL, .value = { .boolean_value = false } };
  230. case GL_VIEWPORT:
  231. return ContextParameter {
  232. .type = GL_INT,
  233. .count = 4,
  234. .value = {
  235. .integer_list = {
  236. m_viewport.x(),
  237. m_viewport.y(),
  238. m_viewport.width(),
  239. m_viewport.height(),
  240. } }
  241. };
  242. default:
  243. dbgln_if(GL_DEBUG, "get_context_parameter({:#x}): unknown context parameter", name);
  244. return {};
  245. }
  246. }
  247. void GLContext::gl_begin(GLenum mode)
  248. {
  249. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_begin, mode);
  250. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  251. RETURN_WITH_ERROR_IF(mode > GL_POLYGON, GL_INVALID_ENUM);
  252. m_current_draw_mode = mode;
  253. m_in_draw_state = true; // Certain commands will now generate an error
  254. }
  255. void GLContext::gl_clear(GLbitfield mask)
  256. {
  257. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear, mask);
  258. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  259. RETURN_WITH_ERROR_IF(mask & ~(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT), GL_INVALID_ENUM);
  260. if (mask & GL_COLOR_BUFFER_BIT)
  261. m_rasterizer->clear_color(m_clear_color);
  262. if (mask & GL_DEPTH_BUFFER_BIT)
  263. m_rasterizer->clear_depth(m_clear_depth);
  264. if (mask & GL_STENCIL_BUFFER_BIT)
  265. m_rasterizer->clear_stencil(m_clear_stencil);
  266. }
  267. void GLContext::gl_clear_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
  268. {
  269. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_color, red, green, blue, alpha);
  270. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  271. m_clear_color = { red, green, blue, alpha };
  272. m_clear_color.clamp(0.f, 1.f);
  273. }
  274. void GLContext::gl_clear_depth(GLdouble depth)
  275. {
  276. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_depth, depth);
  277. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  278. m_clear_depth = clamp(static_cast<float>(depth), 0.f, 1.f);
  279. }
  280. void GLContext::gl_clear_stencil(GLint s)
  281. {
  282. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clear_stencil, s);
  283. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  284. m_clear_stencil = static_cast<u8>(s & ((1 << m_device_info.stencil_bits) - 1));
  285. }
  286. void GLContext::gl_color(GLdouble r, GLdouble g, GLdouble b, GLdouble a)
  287. {
  288. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_color, r, g, b, a);
  289. m_current_vertex_color = {
  290. static_cast<float>(r),
  291. static_cast<float>(g),
  292. static_cast<float>(b),
  293. static_cast<float>(a),
  294. };
  295. }
  296. void GLContext::gl_end()
  297. {
  298. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_end);
  299. // Make sure we had a `glBegin` before this call...
  300. RETURN_WITH_ERROR_IF(!m_in_draw_state, GL_INVALID_OPERATION);
  301. m_in_draw_state = false;
  302. // FIXME: Add support for the remaining primitive types.
  303. if (m_current_draw_mode != GL_TRIANGLES
  304. && m_current_draw_mode != GL_TRIANGLE_FAN
  305. && m_current_draw_mode != GL_TRIANGLE_STRIP
  306. && m_current_draw_mode != GL_QUADS
  307. && m_current_draw_mode != GL_QUAD_STRIP
  308. && m_current_draw_mode != GL_POLYGON) {
  309. m_vertex_list.clear_with_capacity();
  310. dbgln_if(GL_DEBUG, "gl_end(): draw mode {:#x} unsupported", m_current_draw_mode);
  311. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  312. }
  313. Vector<size_t, 32> enabled_texture_units;
  314. for (size_t i = 0; i < m_texture_units.size(); ++i) {
  315. if (m_texture_units[i].texture_2d_enabled())
  316. enabled_texture_units.append(i);
  317. }
  318. sync_device_config();
  319. GPU::PrimitiveType primitive_type;
  320. switch (m_current_draw_mode) {
  321. case GL_TRIANGLES:
  322. primitive_type = GPU::PrimitiveType::Triangles;
  323. break;
  324. case GL_TRIANGLE_STRIP:
  325. case GL_QUAD_STRIP:
  326. primitive_type = GPU::PrimitiveType::TriangleStrip;
  327. break;
  328. case GL_TRIANGLE_FAN:
  329. case GL_POLYGON:
  330. primitive_type = GPU::PrimitiveType::TriangleFan;
  331. break;
  332. case GL_QUADS:
  333. primitive_type = GPU::PrimitiveType::Quads;
  334. break;
  335. default:
  336. VERIFY_NOT_REACHED();
  337. }
  338. m_rasterizer->draw_primitives(primitive_type, m_model_view_matrix, m_projection_matrix, m_texture_matrix, m_vertex_list, enabled_texture_units);
  339. m_vertex_list.clear_with_capacity();
  340. }
  341. void GLContext::gl_frustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  342. {
  343. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_frustum, left, right, bottom, top, near_val, far_val);
  344. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  345. RETURN_WITH_ERROR_IF(near_val < 0 || far_val < 0, GL_INVALID_VALUE);
  346. RETURN_WITH_ERROR_IF(left == right || bottom == top || near_val == far_val, GL_INVALID_VALUE);
  347. // Let's do some math!
  348. auto a = static_cast<float>((right + left) / (right - left));
  349. auto b = static_cast<float>((top + bottom) / (top - bottom));
  350. auto c = static_cast<float>(-((far_val + near_val) / (far_val - near_val)));
  351. auto d = static_cast<float>(-((2 * far_val * near_val) / (far_val - near_val)));
  352. FloatMatrix4x4 frustum {
  353. static_cast<float>(2 * near_val / (right - left)), 0, a, 0,
  354. 0, static_cast<float>(2 * near_val / (top - bottom)), b, 0,
  355. 0, 0, c, d,
  356. 0, 0, -1, 0
  357. };
  358. *m_current_matrix = *m_current_matrix * frustum;
  359. }
  360. void GLContext::gl_ortho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near_val, GLdouble far_val)
  361. {
  362. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_ortho, left, right, bottom, top, near_val, far_val);
  363. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  364. RETURN_WITH_ERROR_IF(left == right || bottom == top || near_val == far_val, GL_INVALID_VALUE);
  365. auto rl = right - left;
  366. auto tb = top - bottom;
  367. auto fn = far_val - near_val;
  368. auto tx = -(right + left) / rl;
  369. auto ty = -(top + bottom) / tb;
  370. auto tz = -(far_val + near_val) / fn;
  371. FloatMatrix4x4 projection {
  372. static_cast<float>(2 / rl), 0, 0, static_cast<float>(tx),
  373. 0, static_cast<float>(2 / tb), 0, static_cast<float>(ty),
  374. 0, 0, static_cast<float>(-2 / fn), static_cast<float>(tz),
  375. 0, 0, 0, 1
  376. };
  377. *m_current_matrix = *m_current_matrix * projection;
  378. }
  379. GLenum GLContext::gl_get_error()
  380. {
  381. if (m_in_draw_state)
  382. return GL_INVALID_OPERATION;
  383. auto last_error = m_error;
  384. m_error = GL_NO_ERROR;
  385. return last_error;
  386. }
  387. GLubyte* GLContext::gl_get_string(GLenum name)
  388. {
  389. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, nullptr);
  390. switch (name) {
  391. case GL_VENDOR:
  392. return reinterpret_cast<GLubyte*>(const_cast<char*>(m_device_info.vendor_name.characters()));
  393. case GL_RENDERER:
  394. return reinterpret_cast<GLubyte*>(const_cast<char*>(m_device_info.device_name.characters()));
  395. case GL_VERSION:
  396. return reinterpret_cast<GLubyte*>(const_cast<char*>("1.5"));
  397. case GL_EXTENSIONS:
  398. return reinterpret_cast<GLubyte*>(const_cast<char*>(m_extensions.characters()));
  399. case GL_SHADING_LANGUAGE_VERSION:
  400. return reinterpret_cast<GLubyte*>(const_cast<char*>("0.0"));
  401. default:
  402. dbgln_if(GL_DEBUG, "gl_get_string({:#x}): unknown name", name);
  403. break;
  404. }
  405. RETURN_VALUE_WITH_ERROR_IF(true, GL_INVALID_ENUM, nullptr);
  406. }
  407. void GLContext::gl_load_identity()
  408. {
  409. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_load_identity);
  410. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  411. *m_current_matrix = FloatMatrix4x4::identity();
  412. }
  413. void GLContext::gl_load_matrix(FloatMatrix4x4 const& matrix)
  414. {
  415. APPEND_TO_CALL_LIST_WITH_ARG_AND_RETURN_IF_NEEDED(gl_load_matrix, matrix);
  416. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  417. *m_current_matrix = matrix;
  418. }
  419. void GLContext::gl_matrix_mode(GLenum mode)
  420. {
  421. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_matrix_mode, mode);
  422. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  423. RETURN_WITH_ERROR_IF(mode < GL_MODELVIEW || mode > GL_TEXTURE, GL_INVALID_ENUM);
  424. m_current_matrix_mode = mode;
  425. switch (mode) {
  426. case GL_MODELVIEW:
  427. m_current_matrix = &m_model_view_matrix;
  428. m_current_matrix_stack = &m_model_view_matrix_stack;
  429. break;
  430. case GL_PROJECTION:
  431. m_current_matrix = &m_projection_matrix;
  432. m_current_matrix_stack = &m_projection_matrix_stack;
  433. break;
  434. case GL_TEXTURE:
  435. m_current_matrix = &m_texture_matrix;
  436. m_current_matrix_stack = &m_texture_matrix_stack;
  437. break;
  438. default:
  439. VERIFY_NOT_REACHED();
  440. }
  441. }
  442. static constexpr size_t matrix_stack_limit(GLenum matrix_mode)
  443. {
  444. switch (matrix_mode) {
  445. case GL_MODELVIEW:
  446. return MODELVIEW_MATRIX_STACK_LIMIT;
  447. case GL_PROJECTION:
  448. return PROJECTION_MATRIX_STACK_LIMIT;
  449. case GL_TEXTURE:
  450. return TEXTURE_MATRIX_STACK_LIMIT;
  451. }
  452. VERIFY_NOT_REACHED();
  453. }
  454. void GLContext::gl_push_matrix()
  455. {
  456. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_push_matrix);
  457. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  458. RETURN_WITH_ERROR_IF((*m_current_matrix_stack).size() >= matrix_stack_limit(m_current_matrix_mode), GL_STACK_OVERFLOW);
  459. (*m_current_matrix_stack).append(*m_current_matrix);
  460. }
  461. void GLContext::gl_pop_matrix()
  462. {
  463. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_pop_matrix);
  464. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  465. RETURN_WITH_ERROR_IF((*m_current_matrix_stack).is_empty(), GL_STACK_UNDERFLOW);
  466. *m_current_matrix = (*m_current_matrix_stack).take_last();
  467. }
  468. void GLContext::gl_mult_matrix(FloatMatrix4x4 const& matrix)
  469. {
  470. APPEND_TO_CALL_LIST_WITH_ARG_AND_RETURN_IF_NEEDED(gl_mult_matrix, matrix);
  471. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  472. *m_current_matrix = *m_current_matrix * matrix;
  473. }
  474. void GLContext::gl_rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
  475. {
  476. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_rotate, angle, x, y, z);
  477. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  478. FloatVector3 axis = { x, y, z };
  479. if (axis.length() > 0.f)
  480. axis.normalize();
  481. auto rotation_mat = Gfx::rotation_matrix(axis, angle * static_cast<float>(M_PI * 2 / 360));
  482. *m_current_matrix = *m_current_matrix * rotation_mat;
  483. }
  484. void GLContext::gl_scale(GLdouble x, GLdouble y, GLdouble z)
  485. {
  486. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_scale, x, y, z);
  487. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  488. auto scale_matrix = Gfx::scale_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  489. *m_current_matrix = *m_current_matrix * scale_matrix;
  490. }
  491. void GLContext::gl_translate(GLdouble x, GLdouble y, GLdouble z)
  492. {
  493. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_translate, x, y, z);
  494. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  495. auto translation_matrix = Gfx::translation_matrix(FloatVector3 { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z) });
  496. *m_current_matrix = *m_current_matrix * translation_matrix;
  497. }
  498. void GLContext::gl_vertex(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
  499. {
  500. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_vertex, x, y, z, w);
  501. GPU::Vertex vertex;
  502. vertex.position = { static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), static_cast<float>(w) };
  503. vertex.color = m_current_vertex_color;
  504. for (size_t i = 0; i < m_device_info.num_texture_units; ++i)
  505. vertex.tex_coords[i] = m_current_vertex_tex_coord[i];
  506. vertex.normal = m_current_vertex_normal;
  507. m_vertex_list.append(vertex);
  508. }
  509. void GLContext::gl_tex_coord(GLfloat s, GLfloat t, GLfloat r, GLfloat q)
  510. {
  511. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_coord, s, t, r, q);
  512. m_current_vertex_tex_coord[0] = { s, t, r, q };
  513. }
  514. void GLContext::gl_multi_tex_coord(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
  515. {
  516. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_multi_tex_coord, target, s, t, r, q);
  517. RETURN_WITH_ERROR_IF(target < GL_TEXTURE0 || target >= GL_TEXTURE0 + m_device_info.num_texture_units, GL_INVALID_ENUM);
  518. m_current_vertex_tex_coord[target - GL_TEXTURE0] = { s, t, r, q };
  519. }
  520. void GLContext::gl_viewport(GLint x, GLint y, GLsizei width, GLsizei height)
  521. {
  522. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_viewport, x, y, width, height);
  523. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  524. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  525. m_viewport = { x, y, width, height };
  526. auto rasterizer_options = m_rasterizer->options();
  527. rasterizer_options.viewport = m_viewport;
  528. m_rasterizer->set_options(rasterizer_options);
  529. }
  530. void GLContext::gl_enable(GLenum capability)
  531. {
  532. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_enable, capability);
  533. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  534. auto rasterizer_options = m_rasterizer->options();
  535. bool update_rasterizer_options = false;
  536. switch (capability) {
  537. case GL_COLOR_MATERIAL:
  538. m_color_material_enabled = true;
  539. break;
  540. case GL_CULL_FACE:
  541. m_cull_faces = true;
  542. rasterizer_options.enable_culling = true;
  543. update_rasterizer_options = true;
  544. break;
  545. case GL_DEPTH_TEST:
  546. m_depth_test_enabled = true;
  547. rasterizer_options.enable_depth_test = true;
  548. update_rasterizer_options = true;
  549. break;
  550. case GL_BLEND:
  551. m_blend_enabled = true;
  552. rasterizer_options.enable_blending = true;
  553. update_rasterizer_options = true;
  554. break;
  555. case GL_ALPHA_TEST:
  556. m_alpha_test_enabled = true;
  557. rasterizer_options.enable_alpha_test = true;
  558. update_rasterizer_options = true;
  559. break;
  560. case GL_DITHER:
  561. m_dither_enabled = true;
  562. break;
  563. case GL_FOG:
  564. rasterizer_options.fog_enabled = true;
  565. update_rasterizer_options = true;
  566. break;
  567. case GL_LIGHTING:
  568. m_lighting_enabled = true;
  569. rasterizer_options.lighting_enabled = true;
  570. update_rasterizer_options = true;
  571. break;
  572. case GL_NORMALIZE:
  573. m_normalize = true;
  574. rasterizer_options.normalization_enabled = true;
  575. update_rasterizer_options = true;
  576. break;
  577. case GL_POLYGON_OFFSET_FILL:
  578. m_depth_offset_enabled = true;
  579. rasterizer_options.depth_offset_enabled = true;
  580. update_rasterizer_options = true;
  581. break;
  582. case GL_SCISSOR_TEST:
  583. rasterizer_options.scissor_enabled = true;
  584. update_rasterizer_options = true;
  585. break;
  586. case GL_STENCIL_TEST:
  587. m_stencil_test_enabled = true;
  588. rasterizer_options.enable_stencil_test = true;
  589. update_rasterizer_options = true;
  590. break;
  591. case GL_TEXTURE_1D:
  592. m_active_texture_unit->set_texture_1d_enabled(true);
  593. m_sampler_config_is_dirty = true;
  594. break;
  595. case GL_TEXTURE_2D:
  596. m_active_texture_unit->set_texture_2d_enabled(true);
  597. m_sampler_config_is_dirty = true;
  598. break;
  599. case GL_TEXTURE_3D:
  600. m_active_texture_unit->set_texture_3d_enabled(true);
  601. m_sampler_config_is_dirty = true;
  602. break;
  603. case GL_TEXTURE_CUBE_MAP:
  604. m_active_texture_unit->set_texture_cube_map_enabled(true);
  605. m_sampler_config_is_dirty = true;
  606. break;
  607. case GL_LIGHT0:
  608. case GL_LIGHT1:
  609. case GL_LIGHT2:
  610. case GL_LIGHT3:
  611. case GL_LIGHT4:
  612. case GL_LIGHT5:
  613. case GL_LIGHT6:
  614. case GL_LIGHT7:
  615. m_light_states.at(capability - GL_LIGHT0).is_enabled = true;
  616. m_light_state_is_dirty = true;
  617. break;
  618. case GL_TEXTURE_GEN_Q:
  619. case GL_TEXTURE_GEN_R:
  620. case GL_TEXTURE_GEN_S:
  621. case GL_TEXTURE_GEN_T:
  622. texture_coordinate_generation(m_active_texture_unit_index, capability).enabled = true;
  623. m_texcoord_generation_dirty = true;
  624. break;
  625. default:
  626. dbgln_if(GL_DEBUG, "gl_enable({:#x}): unknown parameter", capability);
  627. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  628. }
  629. if (update_rasterizer_options)
  630. m_rasterizer->set_options(rasterizer_options);
  631. }
  632. void GLContext::gl_disable(GLenum capability)
  633. {
  634. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_disable, capability);
  635. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  636. auto rasterizer_options = m_rasterizer->options();
  637. bool update_rasterizer_options = false;
  638. switch (capability) {
  639. case GL_COLOR_MATERIAL:
  640. m_color_material_enabled = false;
  641. break;
  642. case GL_CULL_FACE:
  643. m_cull_faces = false;
  644. rasterizer_options.enable_culling = false;
  645. update_rasterizer_options = true;
  646. break;
  647. case GL_DEPTH_TEST:
  648. m_depth_test_enabled = false;
  649. rasterizer_options.enable_depth_test = false;
  650. update_rasterizer_options = true;
  651. break;
  652. case GL_BLEND:
  653. m_blend_enabled = false;
  654. rasterizer_options.enable_blending = false;
  655. update_rasterizer_options = true;
  656. break;
  657. case GL_ALPHA_TEST:
  658. m_alpha_test_enabled = false;
  659. rasterizer_options.enable_alpha_test = false;
  660. update_rasterizer_options = true;
  661. break;
  662. case GL_DITHER:
  663. m_dither_enabled = false;
  664. break;
  665. case GL_FOG:
  666. rasterizer_options.fog_enabled = false;
  667. update_rasterizer_options = true;
  668. break;
  669. case GL_LIGHTING:
  670. m_lighting_enabled = false;
  671. rasterizer_options.lighting_enabled = false;
  672. update_rasterizer_options = true;
  673. break;
  674. case GL_LIGHT0:
  675. case GL_LIGHT1:
  676. case GL_LIGHT2:
  677. case GL_LIGHT3:
  678. case GL_LIGHT4:
  679. case GL_LIGHT5:
  680. case GL_LIGHT6:
  681. case GL_LIGHT7:
  682. m_light_states.at(capability - GL_LIGHT0).is_enabled = false;
  683. m_light_state_is_dirty = true;
  684. break;
  685. case GL_NORMALIZE:
  686. m_normalize = false;
  687. rasterizer_options.normalization_enabled = false;
  688. update_rasterizer_options = true;
  689. break;
  690. case GL_POLYGON_OFFSET_FILL:
  691. m_depth_offset_enabled = false;
  692. rasterizer_options.depth_offset_enabled = false;
  693. update_rasterizer_options = true;
  694. break;
  695. case GL_SCISSOR_TEST:
  696. rasterizer_options.scissor_enabled = false;
  697. update_rasterizer_options = true;
  698. break;
  699. case GL_STENCIL_TEST:
  700. m_stencil_test_enabled = false;
  701. rasterizer_options.enable_stencil_test = false;
  702. update_rasterizer_options = true;
  703. break;
  704. case GL_TEXTURE_1D:
  705. m_active_texture_unit->set_texture_1d_enabled(false);
  706. m_sampler_config_is_dirty = true;
  707. break;
  708. case GL_TEXTURE_2D:
  709. m_active_texture_unit->set_texture_2d_enabled(false);
  710. m_sampler_config_is_dirty = true;
  711. break;
  712. case GL_TEXTURE_3D:
  713. m_active_texture_unit->set_texture_3d_enabled(false);
  714. m_sampler_config_is_dirty = true;
  715. break;
  716. case GL_TEXTURE_CUBE_MAP:
  717. m_active_texture_unit->set_texture_cube_map_enabled(false);
  718. m_sampler_config_is_dirty = true;
  719. break;
  720. case GL_TEXTURE_GEN_Q:
  721. case GL_TEXTURE_GEN_R:
  722. case GL_TEXTURE_GEN_S:
  723. case GL_TEXTURE_GEN_T:
  724. texture_coordinate_generation(m_active_texture_unit_index, capability).enabled = false;
  725. m_texcoord_generation_dirty = true;
  726. break;
  727. default:
  728. dbgln_if(GL_DEBUG, "gl_disable({:#x}): unknown parameter", capability);
  729. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  730. }
  731. if (update_rasterizer_options)
  732. m_rasterizer->set_options(rasterizer_options);
  733. }
  734. GLboolean GLContext::gl_is_enabled(GLenum capability)
  735. {
  736. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, 0);
  737. auto optional_parameter = get_context_parameter(capability);
  738. RETURN_VALUE_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM, 0);
  739. auto parameter = optional_parameter.release_value();
  740. RETURN_VALUE_WITH_ERROR_IF(!parameter.is_capability, GL_INVALID_ENUM, 0);
  741. return parameter.value.boolean_value;
  742. }
  743. void GLContext::gl_gen_textures(GLsizei n, GLuint* textures)
  744. {
  745. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  746. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  747. m_name_allocator.allocate(n, textures);
  748. // Initialize all texture names with a nullptr
  749. for (auto i = 0; i < n; ++i) {
  750. GLuint name = textures[i];
  751. m_allocated_textures.set(name, nullptr);
  752. }
  753. }
  754. void GLContext::gl_delete_textures(GLsizei n, GLuint const* textures)
  755. {
  756. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  757. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  758. for (auto i = 0; i < n; i++) {
  759. GLuint name = textures[i];
  760. if (name == 0)
  761. continue;
  762. m_name_allocator.free(name);
  763. auto texture_object = m_allocated_textures.find(name);
  764. if (texture_object == m_allocated_textures.end() || texture_object->value.is_null())
  765. continue;
  766. auto texture = texture_object->value;
  767. // Check all texture units
  768. for (auto& texture_unit : m_texture_units) {
  769. if (texture->is_texture_2d() && texture_unit.texture_2d_target_texture() == texture) {
  770. // If a texture that is currently bound is deleted, the binding reverts to 0 (the default texture)
  771. texture_unit.set_texture_2d_target_texture(get_default_texture<Texture2D>(GL_TEXTURE_2D));
  772. }
  773. }
  774. m_allocated_textures.remove(name);
  775. }
  776. }
  777. void GLContext::gl_tex_image_2d(GLenum target, GLint level, GLint internal_format, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLvoid const* data)
  778. {
  779. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  780. // We only support GL_TEXTURE_2D for now
  781. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  782. // Internal format can also be a number between 1 and 4. Symbolic formats were only added with EXT_texture, promoted to core in OpenGL 1.1
  783. if (internal_format == 1)
  784. internal_format = GL_ALPHA;
  785. else if (internal_format == 2)
  786. internal_format = GL_LUMINANCE_ALPHA;
  787. else if (internal_format == 3)
  788. internal_format = GL_RGB;
  789. else if (internal_format == 4)
  790. internal_format = GL_RGBA;
  791. // We only support symbolic constants for now
  792. RETURN_WITH_ERROR_IF(!(internal_format == GL_RGB || internal_format == GL_RGBA || internal_format == GL_LUMINANCE8 || internal_format == GL_LUMINANCE8_ALPHA8), GL_INVALID_ENUM);
  793. RETURN_WITH_ERROR_IF(!(type == GL_UNSIGNED_BYTE || type == GL_UNSIGNED_SHORT_5_6_5), GL_INVALID_VALUE);
  794. RETURN_WITH_ERROR_IF(level < 0 || level > Texture2D::LOG2_MAX_TEXTURE_SIZE, GL_INVALID_VALUE);
  795. RETURN_WITH_ERROR_IF(width < 0 || height < 0 || width > (2 + Texture2D::MAX_TEXTURE_SIZE) || height > (2 + Texture2D::MAX_TEXTURE_SIZE), GL_INVALID_VALUE);
  796. // Check if width and height are a power of 2
  797. if (!m_device_info.supports_npot_textures) {
  798. RETURN_WITH_ERROR_IF(!is_power_of_two(width), GL_INVALID_VALUE);
  799. RETURN_WITH_ERROR_IF(!is_power_of_two(height), GL_INVALID_VALUE);
  800. }
  801. RETURN_WITH_ERROR_IF(border != 0, GL_INVALID_VALUE);
  802. auto texture_2d = m_active_texture_unit->texture_2d_target_texture();
  803. VERIFY(!texture_2d.is_null());
  804. if (level == 0) {
  805. // FIXME: OpenGL has the concept of texture and mipmap completeness. A texture has to fulfill certain criteria to be considered complete.
  806. // Trying to render while an incomplete texture is bound will result in an error.
  807. // Here we simply create a complete device image when mipmap level 0 is attached to the texture object. This has the unfortunate side effect
  808. // that constructing GL textures in any but the default mipmap order, going from level 0 upwards will cause mip levels to stay uninitialized.
  809. // To be spec compliant we should create the device image once the texture has become complete and is used for rendering the first time.
  810. // All images that were attached before the device image was created need to be stored somewhere to be used to initialize the device image once complete.
  811. texture_2d->set_device_image(m_rasterizer->create_image(GPU::ImageFormat::BGRA8888, width, height, 1, 999, 1));
  812. m_sampler_config_is_dirty = true;
  813. }
  814. texture_2d->upload_texture_data(level, internal_format, width, height, format, type, data, m_unpack_row_length, m_unpack_alignment);
  815. }
  816. void GLContext::gl_tex_sub_image_2d(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid const* data)
  817. {
  818. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  819. // We only support GL_TEXTURE_2D for now
  820. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  821. // We only support symbolic constants for now
  822. RETURN_WITH_ERROR_IF(!(format == GL_RGBA || format == GL_RGB), GL_INVALID_VALUE);
  823. RETURN_WITH_ERROR_IF(!(type == GL_UNSIGNED_BYTE || type == GL_UNSIGNED_SHORT_5_6_5), GL_INVALID_VALUE);
  824. RETURN_WITH_ERROR_IF(level < 0 || level > Texture2D::LOG2_MAX_TEXTURE_SIZE, GL_INVALID_VALUE);
  825. RETURN_WITH_ERROR_IF(width < 0 || height < 0 || width > (2 + Texture2D::MAX_TEXTURE_SIZE) || height > (2 + Texture2D::MAX_TEXTURE_SIZE), GL_INVALID_VALUE);
  826. // A 2D texture array must have been defined by a previous glTexImage2D operation
  827. auto texture_2d = m_active_texture_unit->texture_2d_target_texture();
  828. RETURN_WITH_ERROR_IF(texture_2d.is_null(), GL_INVALID_OPERATION);
  829. RETURN_WITH_ERROR_IF(xoffset < 0 || yoffset < 0 || xoffset + width > texture_2d->width_at_lod(level) || yoffset + height > texture_2d->height_at_lod(level), GL_INVALID_VALUE);
  830. texture_2d->replace_sub_texture_data(level, xoffset, yoffset, width, height, format, type, data, m_unpack_row_length, m_unpack_alignment);
  831. }
  832. void GLContext::gl_tex_parameter(GLenum target, GLenum pname, GLfloat param)
  833. {
  834. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_parameter, target, pname, param);
  835. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  836. // FIXME: We currently only support GL_TETXURE_2D targets. 1D, 3D and CUBE should also be supported (https://docs.gl/gl2/glTexParameter)
  837. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  838. // FIXME: implement the remaining parameters. (https://docs.gl/gl2/glTexParameter)
  839. RETURN_WITH_ERROR_IF(!(pname == GL_TEXTURE_MIN_FILTER
  840. || pname == GL_TEXTURE_MAG_FILTER
  841. || pname == GL_TEXTURE_WRAP_S
  842. || pname == GL_TEXTURE_WRAP_T),
  843. GL_INVALID_ENUM);
  844. // We assume GL_TEXTURE_2D (see above)
  845. auto texture_2d = m_active_texture_unit->texture_2d_target_texture();
  846. if (texture_2d.is_null())
  847. return;
  848. switch (pname) {
  849. case GL_TEXTURE_MIN_FILTER:
  850. RETURN_WITH_ERROR_IF(!(param == GL_NEAREST
  851. || param == GL_LINEAR
  852. || param == GL_NEAREST_MIPMAP_NEAREST
  853. || param == GL_LINEAR_MIPMAP_NEAREST
  854. || param == GL_NEAREST_MIPMAP_LINEAR
  855. || param == GL_LINEAR_MIPMAP_LINEAR),
  856. GL_INVALID_ENUM);
  857. texture_2d->sampler().set_min_filter(param);
  858. break;
  859. case GL_TEXTURE_MAG_FILTER:
  860. RETURN_WITH_ERROR_IF(!(param == GL_NEAREST
  861. || param == GL_LINEAR),
  862. GL_INVALID_ENUM);
  863. texture_2d->sampler().set_mag_filter(param);
  864. break;
  865. case GL_TEXTURE_WRAP_S:
  866. RETURN_WITH_ERROR_IF(!(param == GL_CLAMP
  867. || param == GL_CLAMP_TO_BORDER
  868. || param == GL_CLAMP_TO_EDGE
  869. || param == GL_MIRRORED_REPEAT
  870. || param == GL_REPEAT),
  871. GL_INVALID_ENUM);
  872. texture_2d->sampler().set_wrap_s_mode(param);
  873. break;
  874. case GL_TEXTURE_WRAP_T:
  875. RETURN_WITH_ERROR_IF(!(param == GL_CLAMP
  876. || param == GL_CLAMP_TO_BORDER
  877. || param == GL_CLAMP_TO_EDGE
  878. || param == GL_MIRRORED_REPEAT
  879. || param == GL_REPEAT),
  880. GL_INVALID_ENUM);
  881. texture_2d->sampler().set_wrap_t_mode(param);
  882. break;
  883. default:
  884. VERIFY_NOT_REACHED();
  885. }
  886. m_sampler_config_is_dirty = true;
  887. }
  888. void GLContext::gl_tex_parameterfv(GLenum target, GLenum pname, GLfloat const* params)
  889. {
  890. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_parameterfv, target, pname, params);
  891. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  892. // FIXME: We currently only support GL_TETXURE_2D targets. 1D, 3D and CUBE should also be supported (https://docs.gl/gl2/glTexParameter)
  893. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  894. // FIXME: implement the remaining parameters. (https://docs.gl/gl2/glTexParameter)
  895. RETURN_WITH_ERROR_IF(!(pname == GL_TEXTURE_BORDER_COLOR), GL_INVALID_ENUM);
  896. // We assume GL_TEXTURE_2D (see above)
  897. auto texture_2d = m_active_texture_unit->texture_2d_target_texture();
  898. RETURN_WITH_ERROR_IF(texture_2d.is_null(), GL_INVALID_OPERATION);
  899. switch (pname) {
  900. case GL_TEXTURE_BORDER_COLOR:
  901. texture_2d->sampler().set_border_color(params[0], params[1], params[2], params[3]);
  902. break;
  903. default:
  904. VERIFY_NOT_REACHED();
  905. }
  906. m_sampler_config_is_dirty = true;
  907. }
  908. void GLContext::gl_front_face(GLenum face)
  909. {
  910. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_front_face, face);
  911. RETURN_WITH_ERROR_IF(face < GL_CW || face > GL_CCW, GL_INVALID_ENUM);
  912. m_front_face = face;
  913. auto rasterizer_options = m_rasterizer->options();
  914. rasterizer_options.front_face = (face == GL_CW) ? GPU::WindingOrder::Clockwise : GPU::WindingOrder::CounterClockwise;
  915. m_rasterizer->set_options(rasterizer_options);
  916. }
  917. void GLContext::gl_cull_face(GLenum cull_mode)
  918. {
  919. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_cull_face, cull_mode);
  920. RETURN_WITH_ERROR_IF(cull_mode < GL_FRONT || cull_mode > GL_FRONT_AND_BACK, GL_INVALID_ENUM);
  921. m_culled_sides = cull_mode;
  922. auto rasterizer_options = m_rasterizer->options();
  923. rasterizer_options.cull_back = cull_mode == GL_BACK || cull_mode == GL_FRONT_AND_BACK;
  924. rasterizer_options.cull_front = cull_mode == GL_FRONT || cull_mode == GL_FRONT_AND_BACK;
  925. m_rasterizer->set_options(rasterizer_options);
  926. }
  927. GLuint GLContext::gl_gen_lists(GLsizei range)
  928. {
  929. RETURN_VALUE_WITH_ERROR_IF(range <= 0, GL_INVALID_VALUE, 0);
  930. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, 0);
  931. auto initial_entry = m_listings.size();
  932. m_listings.resize(range + initial_entry);
  933. return initial_entry + 1;
  934. }
  935. void GLContext::invoke_list(size_t list_index)
  936. {
  937. auto& listing = m_listings[list_index - 1];
  938. for (auto& entry : listing.entries) {
  939. entry.function.visit([&](auto& function) {
  940. entry.arguments.visit([&](auto& arguments) {
  941. auto apply = [&]<typename... Args>(Args&&... args) {
  942. if constexpr (requires { (this->*function)(forward<Args>(args)...); })
  943. (this->*function)(forward<Args>(args)...);
  944. };
  945. arguments.apply_as_args(apply);
  946. });
  947. });
  948. }
  949. }
  950. void GLContext::gl_call_list(GLuint list)
  951. {
  952. if (m_gl_call_depth > max_allowed_gl_call_depth)
  953. return;
  954. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_call_list, list);
  955. if (m_listings.size() < list)
  956. return;
  957. TemporaryChange change { m_gl_call_depth, m_gl_call_depth + 1 };
  958. invoke_list(list);
  959. }
  960. void GLContext::gl_call_lists(GLsizei n, GLenum type, void const* lists)
  961. {
  962. if (m_gl_call_depth > max_allowed_gl_call_depth)
  963. return;
  964. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_call_lists, n, type, lists);
  965. RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE);
  966. RETURN_WITH_ERROR_IF(!(type == GL_BYTE
  967. || type == GL_UNSIGNED_BYTE
  968. || type == GL_SHORT
  969. || type == GL_UNSIGNED_SHORT
  970. || type == GL_INT
  971. || type == GL_UNSIGNED_INT
  972. || type == GL_FLOAT
  973. || type == GL_2_BYTES
  974. || type == GL_3_BYTES
  975. || type == GL_4_BYTES),
  976. GL_INVALID_ENUM);
  977. TemporaryChange change { m_gl_call_depth, m_gl_call_depth + 1 };
  978. auto invoke_all_lists = [&]<typename T>(T const* lists) {
  979. for (int i = 0; i < n; ++i) {
  980. auto list = static_cast<size_t>(lists[i]);
  981. invoke_list(m_list_base + list);
  982. }
  983. };
  984. switch (type) {
  985. case GL_BYTE:
  986. invoke_all_lists(static_cast<GLbyte const*>(lists));
  987. break;
  988. case GL_UNSIGNED_BYTE:
  989. invoke_all_lists(static_cast<GLubyte const*>(lists));
  990. break;
  991. case GL_SHORT:
  992. invoke_all_lists(static_cast<GLshort const*>(lists));
  993. break;
  994. case GL_UNSIGNED_SHORT:
  995. invoke_all_lists(static_cast<GLushort const*>(lists));
  996. break;
  997. case GL_INT:
  998. invoke_all_lists(static_cast<GLint const*>(lists));
  999. break;
  1000. case GL_UNSIGNED_INT:
  1001. invoke_all_lists(static_cast<GLuint const*>(lists));
  1002. break;
  1003. case GL_FLOAT:
  1004. invoke_all_lists(static_cast<GLfloat const*>(lists));
  1005. break;
  1006. case GL_2_BYTES:
  1007. case GL_3_BYTES:
  1008. case GL_4_BYTES:
  1009. dbgln("GLContext FIXME: unimplemented glCallLists() with type {}", type);
  1010. break;
  1011. default:
  1012. VERIFY_NOT_REACHED();
  1013. }
  1014. }
  1015. void GLContext::gl_delete_lists(GLuint list, GLsizei range)
  1016. {
  1017. if (m_listings.size() < list || m_listings.size() <= list + range)
  1018. return;
  1019. for (auto& entry : m_listings.span().slice(list - 1, range))
  1020. entry.entries.clear_with_capacity();
  1021. }
  1022. void GLContext::gl_list_base(GLuint base)
  1023. {
  1024. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_list_base, base);
  1025. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1026. m_list_base = base;
  1027. }
  1028. void GLContext::gl_end_list()
  1029. {
  1030. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1031. RETURN_WITH_ERROR_IF(!m_current_listing_index.has_value(), GL_INVALID_OPERATION);
  1032. m_listings[m_current_listing_index->index] = move(m_current_listing_index->listing);
  1033. m_current_listing_index.clear();
  1034. }
  1035. void GLContext::gl_new_list(GLuint list, GLenum mode)
  1036. {
  1037. RETURN_WITH_ERROR_IF(list == 0, GL_INVALID_VALUE);
  1038. RETURN_WITH_ERROR_IF(mode != GL_COMPILE && mode != GL_COMPILE_AND_EXECUTE, GL_INVALID_ENUM);
  1039. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1040. RETURN_WITH_ERROR_IF(m_current_listing_index.has_value(), GL_INVALID_OPERATION);
  1041. if (m_listings.size() < list)
  1042. return;
  1043. m_current_listing_index = CurrentListing { {}, static_cast<size_t>(list - 1), mode };
  1044. }
  1045. GLboolean GLContext::gl_is_list(GLuint list)
  1046. {
  1047. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, GL_FALSE);
  1048. return list < m_listings.size() ? GL_TRUE : GL_FALSE;
  1049. }
  1050. void GLContext::gl_flush()
  1051. {
  1052. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1053. // No-op since GLContext is completely synchronous at the moment
  1054. }
  1055. void GLContext::gl_finish()
  1056. {
  1057. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1058. // No-op since GLContext is completely synchronous at the moment
  1059. }
  1060. void GLContext::gl_blend_func(GLenum src_factor, GLenum dst_factor)
  1061. {
  1062. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_blend_func, src_factor, dst_factor);
  1063. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1064. // FIXME: The list of allowed enums differs between API versions
  1065. // This was taken from the 2.0 spec on https://docs.gl/gl2/glBlendFunc
  1066. RETURN_WITH_ERROR_IF(!(src_factor == GL_ZERO
  1067. || src_factor == GL_ONE
  1068. || src_factor == GL_SRC_COLOR
  1069. || src_factor == GL_ONE_MINUS_SRC_COLOR
  1070. || src_factor == GL_DST_COLOR
  1071. || src_factor == GL_ONE_MINUS_DST_COLOR
  1072. || src_factor == GL_SRC_ALPHA
  1073. || src_factor == GL_ONE_MINUS_SRC_ALPHA
  1074. || src_factor == GL_DST_ALPHA
  1075. || src_factor == GL_ONE_MINUS_DST_ALPHA
  1076. || src_factor == GL_CONSTANT_COLOR
  1077. || src_factor == GL_ONE_MINUS_CONSTANT_COLOR
  1078. || src_factor == GL_CONSTANT_ALPHA
  1079. || src_factor == GL_ONE_MINUS_CONSTANT_ALPHA
  1080. || src_factor == GL_SRC_ALPHA_SATURATE),
  1081. GL_INVALID_ENUM);
  1082. RETURN_WITH_ERROR_IF(!(dst_factor == GL_ZERO
  1083. || dst_factor == GL_ONE
  1084. || dst_factor == GL_SRC_COLOR
  1085. || dst_factor == GL_ONE_MINUS_SRC_COLOR
  1086. || dst_factor == GL_DST_COLOR
  1087. || dst_factor == GL_ONE_MINUS_DST_COLOR
  1088. || dst_factor == GL_SRC_ALPHA
  1089. || dst_factor == GL_ONE_MINUS_SRC_ALPHA
  1090. || dst_factor == GL_DST_ALPHA
  1091. || dst_factor == GL_ONE_MINUS_DST_ALPHA
  1092. || dst_factor == GL_CONSTANT_COLOR
  1093. || dst_factor == GL_ONE_MINUS_CONSTANT_COLOR
  1094. || dst_factor == GL_CONSTANT_ALPHA
  1095. || dst_factor == GL_ONE_MINUS_CONSTANT_ALPHA),
  1096. GL_INVALID_ENUM);
  1097. m_blend_source_factor = src_factor;
  1098. m_blend_destination_factor = dst_factor;
  1099. auto map_gl_blend_factor_to_device = [](GLenum factor) constexpr
  1100. {
  1101. switch (factor) {
  1102. case GL_ZERO:
  1103. return GPU::BlendFactor::Zero;
  1104. case GL_ONE:
  1105. return GPU::BlendFactor::One;
  1106. case GL_SRC_ALPHA:
  1107. return GPU::BlendFactor::SrcAlpha;
  1108. case GL_ONE_MINUS_SRC_ALPHA:
  1109. return GPU::BlendFactor::OneMinusSrcAlpha;
  1110. case GL_SRC_COLOR:
  1111. return GPU::BlendFactor::SrcColor;
  1112. case GL_ONE_MINUS_SRC_COLOR:
  1113. return GPU::BlendFactor::OneMinusSrcColor;
  1114. case GL_DST_ALPHA:
  1115. return GPU::BlendFactor::DstAlpha;
  1116. case GL_ONE_MINUS_DST_ALPHA:
  1117. return GPU::BlendFactor::OneMinusDstAlpha;
  1118. case GL_DST_COLOR:
  1119. return GPU::BlendFactor::DstColor;
  1120. case GL_ONE_MINUS_DST_COLOR:
  1121. return GPU::BlendFactor::OneMinusDstColor;
  1122. case GL_SRC_ALPHA_SATURATE:
  1123. return GPU::BlendFactor::SrcAlphaSaturate;
  1124. default:
  1125. VERIFY_NOT_REACHED();
  1126. }
  1127. };
  1128. auto options = m_rasterizer->options();
  1129. options.blend_source_factor = map_gl_blend_factor_to_device(m_blend_source_factor);
  1130. options.blend_destination_factor = map_gl_blend_factor_to_device(m_blend_destination_factor);
  1131. m_rasterizer->set_options(options);
  1132. }
  1133. void GLContext::gl_shade_model(GLenum mode)
  1134. {
  1135. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_shade_model, mode);
  1136. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1137. RETURN_WITH_ERROR_IF(mode != GL_FLAT && mode != GL_SMOOTH, GL_INVALID_ENUM);
  1138. auto options = m_rasterizer->options();
  1139. options.shade_smooth = (mode == GL_SMOOTH);
  1140. m_rasterizer->set_options(options);
  1141. }
  1142. void GLContext::gl_alpha_func(GLenum func, GLclampf ref)
  1143. {
  1144. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_alpha_func, func, ref);
  1145. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1146. RETURN_WITH_ERROR_IF(func < GL_NEVER || func > GL_ALWAYS, GL_INVALID_ENUM);
  1147. m_alpha_test_func = func;
  1148. m_alpha_test_ref_value = ref;
  1149. auto options = m_rasterizer->options();
  1150. switch (func) {
  1151. case GL_NEVER:
  1152. options.alpha_test_func = GPU::AlphaTestFunction::Never;
  1153. break;
  1154. case GL_ALWAYS:
  1155. options.alpha_test_func = GPU::AlphaTestFunction::Always;
  1156. break;
  1157. case GL_LESS:
  1158. options.alpha_test_func = GPU::AlphaTestFunction::Less;
  1159. break;
  1160. case GL_LEQUAL:
  1161. options.alpha_test_func = GPU::AlphaTestFunction::LessOrEqual;
  1162. break;
  1163. case GL_EQUAL:
  1164. options.alpha_test_func = GPU::AlphaTestFunction::Equal;
  1165. break;
  1166. case GL_NOTEQUAL:
  1167. options.alpha_test_func = GPU::AlphaTestFunction::NotEqual;
  1168. break;
  1169. case GL_GEQUAL:
  1170. options.alpha_test_func = GPU::AlphaTestFunction::GreaterOrEqual;
  1171. break;
  1172. case GL_GREATER:
  1173. options.alpha_test_func = GPU::AlphaTestFunction::Greater;
  1174. break;
  1175. default:
  1176. VERIFY_NOT_REACHED();
  1177. }
  1178. options.alpha_test_ref_value = m_alpha_test_ref_value;
  1179. m_rasterizer->set_options(options);
  1180. }
  1181. void GLContext::gl_hint(GLenum target, GLenum mode)
  1182. {
  1183. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_hint, target, mode);
  1184. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1185. RETURN_WITH_ERROR_IF(target != GL_PERSPECTIVE_CORRECTION_HINT
  1186. && target != GL_POINT_SMOOTH_HINT
  1187. && target != GL_LINE_SMOOTH_HINT
  1188. && target != GL_POLYGON_SMOOTH_HINT
  1189. && target != GL_FOG_HINT
  1190. && target != GL_GENERATE_MIPMAP_HINT
  1191. && target != GL_TEXTURE_COMPRESSION_HINT,
  1192. GL_INVALID_ENUM);
  1193. RETURN_WITH_ERROR_IF(mode != GL_DONT_CARE
  1194. && mode != GL_FASTEST
  1195. && mode != GL_NICEST,
  1196. GL_INVALID_ENUM);
  1197. // According to the spec implementors are free to ignore glHint. So we do.
  1198. }
  1199. void GLContext::gl_read_buffer(GLenum mode)
  1200. {
  1201. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_read_buffer, mode);
  1202. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1203. // FIXME: Also allow aux buffers GL_AUX0 through GL_AUX3 here
  1204. // plus any aux buffer between 0 and GL_AUX_BUFFERS
  1205. RETURN_WITH_ERROR_IF(mode != GL_FRONT_LEFT
  1206. && mode != GL_FRONT_RIGHT
  1207. && mode != GL_BACK_LEFT
  1208. && mode != GL_BACK_RIGHT
  1209. && mode != GL_FRONT
  1210. && mode != GL_BACK
  1211. && mode != GL_LEFT
  1212. && mode != GL_RIGHT,
  1213. GL_INVALID_ENUM);
  1214. // FIXME: We do not currently have aux buffers, so make it an invalid
  1215. // operation to select anything but front or back buffers. Also we do
  1216. // not allow selecting the stereoscopic RIGHT buffers since we do not
  1217. // have them configured.
  1218. RETURN_WITH_ERROR_IF(mode != GL_FRONT_LEFT
  1219. && mode != GL_FRONT
  1220. && mode != GL_BACK_LEFT
  1221. && mode != GL_BACK
  1222. && mode != GL_FRONT
  1223. && mode != GL_BACK
  1224. && mode != GL_LEFT,
  1225. GL_INVALID_OPERATION);
  1226. m_current_read_buffer = mode;
  1227. }
  1228. void GLContext::gl_draw_buffer(GLenum buffer)
  1229. {
  1230. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_buffer, buffer);
  1231. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1232. // FIXME: Also allow aux buffers GL_AUX0 through GL_AUX3 here
  1233. // plus any aux buffer between 0 and GL_AUX_BUFFERS
  1234. RETURN_WITH_ERROR_IF(buffer != GL_NONE
  1235. && buffer != GL_FRONT_LEFT
  1236. && buffer != GL_FRONT_RIGHT
  1237. && buffer != GL_BACK_LEFT
  1238. && buffer != GL_BACK_RIGHT
  1239. && buffer != GL_FRONT
  1240. && buffer != GL_BACK
  1241. && buffer != GL_LEFT
  1242. && buffer != GL_RIGHT,
  1243. GL_INVALID_ENUM);
  1244. // FIXME: We do not currently have aux buffers, so make it an invalid
  1245. // operation to select anything but front or back buffers. Also we do
  1246. // not allow selecting the stereoscopic RIGHT buffers since we do not
  1247. // have them configured.
  1248. RETURN_WITH_ERROR_IF(buffer != GL_NONE
  1249. && buffer != GL_FRONT_LEFT
  1250. && buffer != GL_FRONT
  1251. && buffer != GL_BACK_LEFT
  1252. && buffer != GL_BACK
  1253. && buffer != GL_FRONT
  1254. && buffer != GL_BACK
  1255. && buffer != GL_LEFT,
  1256. GL_INVALID_OPERATION);
  1257. m_current_draw_buffer = buffer;
  1258. auto rasterizer_options = m_rasterizer->options();
  1259. // FIXME: We only have a single draw buffer in SoftGPU at the moment,
  1260. // so we simply disable color writes if GL_NONE is selected
  1261. rasterizer_options.enable_color_write = m_current_draw_buffer != GL_NONE;
  1262. m_rasterizer->set_options(rasterizer_options);
  1263. }
  1264. void GLContext::gl_read_pixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels)
  1265. {
  1266. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1267. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  1268. RETURN_WITH_ERROR_IF(format != GL_COLOR_INDEX
  1269. && format != GL_STENCIL_INDEX
  1270. && format != GL_DEPTH_COMPONENT
  1271. && format != GL_RED
  1272. && format != GL_GREEN
  1273. && format != GL_BLUE
  1274. && format != GL_ALPHA
  1275. && format != GL_RGB
  1276. && format != GL_RGBA
  1277. && format != GL_LUMINANCE
  1278. && format != GL_LUMINANCE_ALPHA,
  1279. GL_INVALID_ENUM);
  1280. RETURN_WITH_ERROR_IF(type != GL_UNSIGNED_BYTE
  1281. && type != GL_BYTE
  1282. && type != GL_BITMAP
  1283. && type != GL_UNSIGNED_SHORT
  1284. && type != GL_SHORT
  1285. && type != GL_BLUE
  1286. && type != GL_UNSIGNED_INT
  1287. && type != GL_INT
  1288. && type != GL_FLOAT,
  1289. GL_INVALID_ENUM);
  1290. // FIXME: We only support RGBA buffers for now.
  1291. // Once we add support for indexed color modes do the correct check here
  1292. RETURN_WITH_ERROR_IF(format == GL_COLOR_INDEX, GL_INVALID_OPERATION);
  1293. // FIXME: We do not have stencil buffers yet
  1294. // Once we add support for stencil buffers do the correct check here
  1295. RETURN_WITH_ERROR_IF(format == GL_STENCIL_INDEX, GL_INVALID_OPERATION);
  1296. if (format == GL_DEPTH_COMPONENT) {
  1297. // FIXME: This check needs to be a bit more sophisticated. Currently the buffers
  1298. // are hardcoded. Once we add proper structures for them we need to correct this check
  1299. // Error because only back buffer has a depth buffer
  1300. RETURN_WITH_ERROR_IF(m_current_read_buffer == GL_FRONT
  1301. || m_current_read_buffer == GL_FRONT_LEFT
  1302. || m_current_read_buffer == GL_FRONT_RIGHT,
  1303. GL_INVALID_OPERATION);
  1304. }
  1305. // Some helper functions for converting float values to integer types
  1306. auto float_to_i8 = [](float f) -> GLchar {
  1307. return static_cast<GLchar>((0x7f * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1308. };
  1309. auto float_to_i16 = [](float f) -> GLshort {
  1310. return static_cast<GLshort>((0x7fff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1311. };
  1312. auto float_to_i32 = [](float f) -> GLint {
  1313. return static_cast<GLint>((0x7fffffff * min(max(f, 0.0f), 1.0f) - 1) / 2);
  1314. };
  1315. auto float_to_u8 = [](float f) -> GLubyte {
  1316. return static_cast<GLubyte>(0xff * min(max(f, 0.0f), 1.0f));
  1317. };
  1318. auto float_to_u16 = [](float f) -> GLushort {
  1319. return static_cast<GLushort>(0xffff * min(max(f, 0.0f), 1.0f));
  1320. };
  1321. auto float_to_u32 = [](float f) -> GLuint {
  1322. return static_cast<GLuint>(0xffffffff * min(max(f, 0.0f), 1.0f));
  1323. };
  1324. u8 component_size = 0;
  1325. switch (type) {
  1326. case GL_BYTE:
  1327. case GL_UNSIGNED_BYTE:
  1328. component_size = 1;
  1329. break;
  1330. case GL_SHORT:
  1331. case GL_UNSIGNED_SHORT:
  1332. component_size = 2;
  1333. break;
  1334. case GL_INT:
  1335. case GL_UNSIGNED_INT:
  1336. case GL_FLOAT:
  1337. component_size = 4;
  1338. break;
  1339. }
  1340. if (format == GL_DEPTH_COMPONENT) {
  1341. auto const row_stride = (width * component_size + m_pack_alignment - 1) / m_pack_alignment * m_pack_alignment;
  1342. // Read from depth buffer
  1343. for (GLsizei i = 0; i < height; ++i) {
  1344. for (GLsizei j = 0; j < width; ++j) {
  1345. float depth = m_rasterizer->get_depthbuffer_value(x + j, y + i);
  1346. auto char_ptr = reinterpret_cast<char*>(pixels) + i * row_stride + j * component_size;
  1347. switch (type) {
  1348. case GL_BYTE:
  1349. *reinterpret_cast<GLchar*>(char_ptr) = float_to_i8(depth);
  1350. break;
  1351. case GL_SHORT:
  1352. *reinterpret_cast<GLshort*>(char_ptr) = float_to_i16(depth);
  1353. break;
  1354. case GL_INT:
  1355. *reinterpret_cast<GLint*>(char_ptr) = float_to_i32(depth);
  1356. break;
  1357. case GL_UNSIGNED_BYTE:
  1358. *reinterpret_cast<GLubyte*>(char_ptr) = float_to_u8(depth);
  1359. break;
  1360. case GL_UNSIGNED_SHORT:
  1361. *reinterpret_cast<GLushort*>(char_ptr) = float_to_u16(depth);
  1362. break;
  1363. case GL_UNSIGNED_INT:
  1364. *reinterpret_cast<GLuint*>(char_ptr) = float_to_u32(depth);
  1365. break;
  1366. case GL_FLOAT:
  1367. *reinterpret_cast<GLfloat*>(char_ptr) = min(max(depth, 0.0f), 1.0f);
  1368. break;
  1369. }
  1370. }
  1371. }
  1372. return;
  1373. }
  1374. bool write_red = false;
  1375. bool write_green = false;
  1376. bool write_blue = false;
  1377. bool write_alpha = false;
  1378. size_t component_count = 0;
  1379. size_t red_offset = 0;
  1380. size_t green_offset = 0;
  1381. size_t blue_offset = 0;
  1382. size_t alpha_offset = 0;
  1383. char* red_ptr = nullptr;
  1384. char* green_ptr = nullptr;
  1385. char* blue_ptr = nullptr;
  1386. char* alpha_ptr = nullptr;
  1387. switch (format) {
  1388. case GL_RGB:
  1389. write_red = true;
  1390. write_green = true;
  1391. write_blue = true;
  1392. component_count = 3;
  1393. red_offset = 2;
  1394. green_offset = 1;
  1395. blue_offset = 0;
  1396. break;
  1397. case GL_RGBA:
  1398. write_red = true;
  1399. write_green = true;
  1400. write_blue = true;
  1401. write_alpha = true;
  1402. component_count = 4;
  1403. red_offset = 3;
  1404. green_offset = 2;
  1405. blue_offset = 1;
  1406. alpha_offset = 0;
  1407. break;
  1408. case GL_RED:
  1409. write_red = true;
  1410. component_count = 1;
  1411. red_offset = 0;
  1412. break;
  1413. case GL_GREEN:
  1414. write_green = true;
  1415. component_count = 1;
  1416. green_offset = 0;
  1417. break;
  1418. case GL_BLUE:
  1419. write_blue = true;
  1420. component_count = 1;
  1421. blue_offset = 0;
  1422. break;
  1423. case GL_ALPHA:
  1424. write_alpha = true;
  1425. component_count = 1;
  1426. alpha_offset = 0;
  1427. break;
  1428. }
  1429. auto const pixel_bytes = component_size * component_count;
  1430. auto const row_alignment_bytes = (m_pack_alignment - ((width * pixel_bytes) % m_pack_alignment)) % m_pack_alignment;
  1431. char* out_ptr = reinterpret_cast<char*>(pixels);
  1432. for (int i = 0; i < (int)height; ++i) {
  1433. for (int j = 0; j < (int)width; ++j) {
  1434. Gfx::ARGB32 color {};
  1435. if (m_current_read_buffer == GL_FRONT || m_current_read_buffer == GL_LEFT || m_current_read_buffer == GL_FRONT_LEFT) {
  1436. if (y + i >= m_frontbuffer->width() || x + j >= m_frontbuffer->height())
  1437. color = 0;
  1438. else
  1439. color = m_frontbuffer->scanline(y + i)[x + j];
  1440. } else {
  1441. color = m_rasterizer->get_color_buffer_pixel(x + j, y + i);
  1442. }
  1443. float red = ((color >> 24) & 0xff) / 255.0f;
  1444. float green = ((color >> 16) & 0xff) / 255.0f;
  1445. float blue = ((color >> 8) & 0xff) / 255.0f;
  1446. float alpha = (color & 0xff) / 255.0f;
  1447. // FIXME: Set up write pointers based on selected endianness (glPixelStore)
  1448. red_ptr = out_ptr + (component_size * red_offset);
  1449. green_ptr = out_ptr + (component_size * green_offset);
  1450. blue_ptr = out_ptr + (component_size * blue_offset);
  1451. alpha_ptr = out_ptr + (component_size * alpha_offset);
  1452. switch (type) {
  1453. case GL_BYTE:
  1454. if (write_red)
  1455. *reinterpret_cast<GLchar*>(red_ptr) = float_to_i8(red);
  1456. if (write_green)
  1457. *reinterpret_cast<GLchar*>(green_ptr) = float_to_i8(green);
  1458. if (write_blue)
  1459. *reinterpret_cast<GLchar*>(blue_ptr) = float_to_i8(blue);
  1460. if (write_alpha)
  1461. *reinterpret_cast<GLchar*>(alpha_ptr) = float_to_i8(alpha);
  1462. break;
  1463. case GL_UNSIGNED_BYTE:
  1464. if (write_red)
  1465. *reinterpret_cast<GLubyte*>(red_ptr) = float_to_u8(red);
  1466. if (write_green)
  1467. *reinterpret_cast<GLubyte*>(green_ptr) = float_to_u8(green);
  1468. if (write_blue)
  1469. *reinterpret_cast<GLubyte*>(blue_ptr) = float_to_u8(blue);
  1470. if (write_alpha)
  1471. *reinterpret_cast<GLubyte*>(alpha_ptr) = float_to_u8(alpha);
  1472. break;
  1473. case GL_SHORT:
  1474. if (write_red)
  1475. *reinterpret_cast<GLshort*>(red_ptr) = float_to_i16(red);
  1476. if (write_green)
  1477. *reinterpret_cast<GLshort*>(green_ptr) = float_to_i16(green);
  1478. if (write_blue)
  1479. *reinterpret_cast<GLshort*>(blue_ptr) = float_to_i16(blue);
  1480. if (write_alpha)
  1481. *reinterpret_cast<GLshort*>(alpha_ptr) = float_to_i16(alpha);
  1482. break;
  1483. case GL_UNSIGNED_SHORT:
  1484. if (write_red)
  1485. *reinterpret_cast<GLushort*>(red_ptr) = float_to_u16(red);
  1486. if (write_green)
  1487. *reinterpret_cast<GLushort*>(green_ptr) = float_to_u16(green);
  1488. if (write_blue)
  1489. *reinterpret_cast<GLushort*>(blue_ptr) = float_to_u16(blue);
  1490. if (write_alpha)
  1491. *reinterpret_cast<GLushort*>(alpha_ptr) = float_to_u16(alpha);
  1492. break;
  1493. case GL_INT:
  1494. if (write_red)
  1495. *reinterpret_cast<GLint*>(red_ptr) = float_to_i32(red);
  1496. if (write_green)
  1497. *reinterpret_cast<GLint*>(green_ptr) = float_to_i32(green);
  1498. if (write_blue)
  1499. *reinterpret_cast<GLint*>(blue_ptr) = float_to_i32(blue);
  1500. if (write_alpha)
  1501. *reinterpret_cast<GLint*>(alpha_ptr) = float_to_i32(alpha);
  1502. break;
  1503. case GL_UNSIGNED_INT:
  1504. if (write_red)
  1505. *reinterpret_cast<GLuint*>(red_ptr) = float_to_u32(red);
  1506. if (write_green)
  1507. *reinterpret_cast<GLuint*>(green_ptr) = float_to_u32(green);
  1508. if (write_blue)
  1509. *reinterpret_cast<GLuint*>(blue_ptr) = float_to_u32(blue);
  1510. if (write_alpha)
  1511. *reinterpret_cast<GLuint*>(alpha_ptr) = float_to_u32(alpha);
  1512. break;
  1513. case GL_FLOAT:
  1514. if (write_red)
  1515. *reinterpret_cast<GLfloat*>(red_ptr) = min(max(red, 0.0f), 1.0f);
  1516. if (write_green)
  1517. *reinterpret_cast<GLfloat*>(green_ptr) = min(max(green, 0.0f), 1.0f);
  1518. if (write_blue)
  1519. *reinterpret_cast<GLfloat*>(blue_ptr) = min(max(blue, 0.0f), 1.0f);
  1520. if (write_alpha)
  1521. *reinterpret_cast<GLfloat*>(alpha_ptr) = min(max(alpha, 0.0f), 1.0f);
  1522. break;
  1523. }
  1524. out_ptr += pixel_bytes;
  1525. }
  1526. out_ptr += row_alignment_bytes;
  1527. }
  1528. }
  1529. void GLContext::gl_bind_texture(GLenum target, GLuint texture)
  1530. {
  1531. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1532. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_1D
  1533. && target != GL_TEXTURE_2D
  1534. && target != GL_TEXTURE_3D
  1535. && target != GL_TEXTURE_1D_ARRAY
  1536. && target != GL_TEXTURE_2D_ARRAY
  1537. && target != GL_TEXTURE_CUBE_MAP,
  1538. GL_INVALID_ENUM);
  1539. // FIXME: We only support GL_TEXTURE_2D for now
  1540. if (target != GL_TEXTURE_2D) {
  1541. dbgln("gl_bind_texture(target = {:#x}): currently only GL_TEXTURE_2D is supported", target);
  1542. return;
  1543. }
  1544. RefPtr<Texture2D> texture_2d;
  1545. if (texture == 0) {
  1546. // Texture name 0 refers to the default texture
  1547. texture_2d = get_default_texture<Texture2D>(target);
  1548. } else {
  1549. // Find this texture name in our previously allocated textures
  1550. auto it = m_allocated_textures.find(texture);
  1551. if (it != m_allocated_textures.end()) {
  1552. auto texture_object = it->value;
  1553. if (!texture_object.is_null()) {
  1554. // Texture must have been created with the same target
  1555. RETURN_WITH_ERROR_IF(!texture_object->is_texture_2d(), GL_INVALID_OPERATION);
  1556. texture_2d = static_cast<Texture2D*>(texture_object.ptr());
  1557. }
  1558. }
  1559. // OpenGL 1.x supports binding texture names that were not previously generated by glGenTextures.
  1560. // If there is not an allocated texture, meaning it was not previously generated by glGenTextures,
  1561. // we can keep texture_object null to both allocate and bind the texture with the passed in texture name.
  1562. // FIXME: Later OpenGL versions such as 4.x enforce that texture names being bound were previously generated
  1563. // by glGenTextures.
  1564. if (!texture_2d) {
  1565. texture_2d = adopt_ref(*new Texture2D());
  1566. m_allocated_textures.set(texture, texture_2d);
  1567. }
  1568. }
  1569. m_active_texture_unit->set_texture_2d_target_texture(texture_2d);
  1570. m_sampler_config_is_dirty = true;
  1571. }
  1572. GLboolean GLContext::gl_is_texture(GLuint texture)
  1573. {
  1574. RETURN_VALUE_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION, GL_FALSE);
  1575. if (texture == 0)
  1576. return GL_FALSE;
  1577. auto it = m_allocated_textures.find(texture);
  1578. if (it == m_allocated_textures.end())
  1579. return GL_FALSE;
  1580. return it->value.is_null() ? GL_FALSE : GL_TRUE;
  1581. }
  1582. void GLContext::gl_active_texture(GLenum texture)
  1583. {
  1584. RETURN_WITH_ERROR_IF(texture < GL_TEXTURE0 || texture >= GL_TEXTURE0 + m_device_info.num_texture_units, GL_INVALID_ENUM);
  1585. m_active_texture_unit_index = texture - GL_TEXTURE0;
  1586. m_active_texture_unit = &m_texture_units.at(m_active_texture_unit_index);
  1587. }
  1588. void GLContext::gl_get_booleanv(GLenum pname, GLboolean* data)
  1589. {
  1590. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1591. auto optional_parameter = get_context_parameter(pname);
  1592. RETURN_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM);
  1593. auto parameter = optional_parameter.release_value();
  1594. switch (parameter.type) {
  1595. case GL_BOOL:
  1596. *data = parameter.value.boolean_value ? GL_TRUE : GL_FALSE;
  1597. break;
  1598. case GL_DOUBLE:
  1599. *data = (parameter.value.double_value == 0.0) ? GL_FALSE : GL_TRUE;
  1600. break;
  1601. case GL_INT:
  1602. *data = (parameter.value.integer_value == 0) ? GL_FALSE : GL_TRUE;
  1603. break;
  1604. default:
  1605. VERIFY_NOT_REACHED();
  1606. }
  1607. }
  1608. void GLContext::gl_get_doublev(GLenum pname, GLdouble* params)
  1609. {
  1610. get_floating_point(pname, params);
  1611. }
  1612. void GLContext::gl_get_floatv(GLenum pname, GLfloat* params)
  1613. {
  1614. get_floating_point(pname, params);
  1615. }
  1616. template<typename T>
  1617. void GLContext::get_floating_point(GLenum pname, T* params)
  1618. {
  1619. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1620. // Handle matrix retrieval first
  1621. auto flatten_and_assign_matrix = [&params](FloatMatrix4x4 const& matrix) {
  1622. auto elements = matrix.elements();
  1623. for (size_t i = 0; i < 4; ++i) {
  1624. for (size_t j = 0; j < 4; ++j) {
  1625. // Return transposed matrix since OpenGL defines them as column-major
  1626. params[i * 4 + j] = static_cast<T>(elements[j][i]);
  1627. }
  1628. }
  1629. };
  1630. switch (pname) {
  1631. case GL_MODELVIEW_MATRIX:
  1632. flatten_and_assign_matrix(m_model_view_matrix);
  1633. return;
  1634. case GL_PROJECTION_MATRIX:
  1635. flatten_and_assign_matrix(m_projection_matrix);
  1636. return;
  1637. }
  1638. // Regular parameters
  1639. auto optional_parameter = get_context_parameter(pname);
  1640. RETURN_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM);
  1641. auto parameter = optional_parameter.release_value();
  1642. switch (parameter.type) {
  1643. case GL_BOOL:
  1644. *params = parameter.value.boolean_value ? GL_TRUE : GL_FALSE;
  1645. break;
  1646. case GL_DOUBLE:
  1647. for (size_t i = 0; i < parameter.count; ++i)
  1648. params[i] = parameter.value.double_list[i];
  1649. break;
  1650. case GL_INT:
  1651. for (size_t i = 0; i < parameter.count; ++i)
  1652. params[i] = parameter.value.integer_list[i];
  1653. break;
  1654. default:
  1655. VERIFY_NOT_REACHED();
  1656. }
  1657. }
  1658. void GLContext::gl_get_integerv(GLenum pname, GLint* data)
  1659. {
  1660. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1661. auto optional_parameter = get_context_parameter(pname);
  1662. RETURN_WITH_ERROR_IF(!optional_parameter.has_value(), GL_INVALID_ENUM);
  1663. auto parameter = optional_parameter.release_value();
  1664. switch (parameter.type) {
  1665. case GL_BOOL:
  1666. *data = parameter.value.boolean_value ? GL_TRUE : GL_FALSE;
  1667. break;
  1668. case GL_DOUBLE: {
  1669. double const int_range = static_cast<double>(NumericLimits<GLint>::max()) - NumericLimits<GLint>::min();
  1670. for (size_t i = 0; i < parameter.count; ++i) {
  1671. double const result_factor = (clamp(parameter.value.double_list[i], -1.0, 1.0) + 1.0) / 2.0;
  1672. data[i] = static_cast<GLint>(NumericLimits<GLint>::min() + result_factor * int_range);
  1673. }
  1674. break;
  1675. }
  1676. case GL_INT:
  1677. for (size_t i = 0; i < parameter.count; ++i)
  1678. data[i] = parameter.value.integer_list[i];
  1679. break;
  1680. default:
  1681. VERIFY_NOT_REACHED();
  1682. }
  1683. }
  1684. void GLContext::gl_depth_mask(GLboolean flag)
  1685. {
  1686. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_depth_mask, flag);
  1687. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1688. auto options = m_rasterizer->options();
  1689. options.enable_depth_write = (flag != GL_FALSE);
  1690. m_rasterizer->set_options(options);
  1691. }
  1692. void GLContext::gl_clip_plane(GLenum plane, [[maybe_unused]] GLdouble const* equation)
  1693. {
  1694. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_clip_plane, plane, equation);
  1695. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1696. RETURN_WITH_ERROR_IF((plane < GL_CLIP_PLANE0) || (plane > GL_CLIP_PLANE5), GL_INVALID_ENUM);
  1697. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_clip_plane() (equation = [{} {} {} {}])", equation[0], equation[1], equation[2], equation[3]);
  1698. }
  1699. void GLContext::gl_enable_client_state(GLenum cap)
  1700. {
  1701. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1702. switch (cap) {
  1703. case GL_COLOR_ARRAY:
  1704. m_client_side_color_array_enabled = true;
  1705. break;
  1706. case GL_NORMAL_ARRAY:
  1707. m_client_side_normal_array_enabled = true;
  1708. break;
  1709. case GL_TEXTURE_COORD_ARRAY:
  1710. m_client_side_texture_coord_array_enabled[m_client_active_texture] = true;
  1711. break;
  1712. case GL_VERTEX_ARRAY:
  1713. m_client_side_vertex_array_enabled = true;
  1714. break;
  1715. default:
  1716. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  1717. }
  1718. }
  1719. void GLContext::gl_disable_client_state(GLenum cap)
  1720. {
  1721. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1722. switch (cap) {
  1723. case GL_COLOR_ARRAY:
  1724. m_client_side_color_array_enabled = false;
  1725. break;
  1726. case GL_NORMAL_ARRAY:
  1727. m_client_side_normal_array_enabled = false;
  1728. break;
  1729. case GL_TEXTURE_COORD_ARRAY:
  1730. m_client_side_texture_coord_array_enabled[m_client_active_texture] = false;
  1731. break;
  1732. case GL_VERTEX_ARRAY:
  1733. m_client_side_vertex_array_enabled = false;
  1734. break;
  1735. default:
  1736. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  1737. }
  1738. }
  1739. void GLContext::gl_client_active_texture(GLenum target)
  1740. {
  1741. RETURN_WITH_ERROR_IF(target < GL_TEXTURE0 || target >= GL_TEXTURE0 + m_device_info.num_texture_units, GL_INVALID_ENUM);
  1742. m_client_active_texture = target - GL_TEXTURE0;
  1743. }
  1744. void GLContext::gl_vertex_pointer(GLint size, GLenum type, GLsizei stride, void const* pointer)
  1745. {
  1746. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1747. RETURN_WITH_ERROR_IF(!(size == 2 || size == 3 || size == 4), GL_INVALID_VALUE);
  1748. RETURN_WITH_ERROR_IF(!(type == GL_SHORT || type == GL_INT || type == GL_FLOAT || type == GL_DOUBLE), GL_INVALID_ENUM);
  1749. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1750. m_client_vertex_pointer = { .size = size, .type = type, .stride = stride, .pointer = pointer };
  1751. }
  1752. void GLContext::gl_color_pointer(GLint size, GLenum type, GLsizei stride, void const* pointer)
  1753. {
  1754. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1755. RETURN_WITH_ERROR_IF(!(size == 3 || size == 4), GL_INVALID_VALUE);
  1756. RETURN_WITH_ERROR_IF(type != GL_BYTE
  1757. && type != GL_UNSIGNED_BYTE
  1758. && type != GL_SHORT
  1759. && type != GL_UNSIGNED_SHORT
  1760. && type != GL_INT
  1761. && type != GL_UNSIGNED_INT
  1762. && type != GL_FLOAT
  1763. && type != GL_DOUBLE,
  1764. GL_INVALID_ENUM);
  1765. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1766. m_client_color_pointer = { .size = size, .type = type, .stride = stride, .pointer = pointer };
  1767. }
  1768. void GLContext::gl_tex_coord_pointer(GLint size, GLenum type, GLsizei stride, void const* pointer)
  1769. {
  1770. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1771. RETURN_WITH_ERROR_IF(!(size == 1 || size == 2 || size == 3 || size == 4), GL_INVALID_VALUE);
  1772. RETURN_WITH_ERROR_IF(!(type == GL_SHORT || type == GL_INT || type == GL_FLOAT || type == GL_DOUBLE), GL_INVALID_ENUM);
  1773. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1774. auto& tex_coord_pointer = m_client_tex_coord_pointer[m_client_active_texture];
  1775. tex_coord_pointer = { .size = size, .type = type, .stride = stride, .pointer = pointer };
  1776. }
  1777. void GLContext::gl_normal_pointer(GLenum type, GLsizei stride, void const* pointer)
  1778. {
  1779. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1780. RETURN_WITH_ERROR_IF(type != GL_BYTE
  1781. && type != GL_SHORT
  1782. && type != GL_INT
  1783. && type != GL_FLOAT
  1784. && type != GL_DOUBLE,
  1785. GL_INVALID_ENUM);
  1786. RETURN_WITH_ERROR_IF(stride < 0, GL_INVALID_VALUE);
  1787. m_client_normal_pointer = { .size = 3, .type = type, .stride = stride, .pointer = pointer };
  1788. }
  1789. void GLContext::gl_tex_env(GLenum target, GLenum pname, GLfloat param)
  1790. {
  1791. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_env, target, pname, param);
  1792. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1793. // FIXME: We currently only support a subset of possible target values. Implement the rest!
  1794. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_ENV, GL_INVALID_ENUM);
  1795. // FIXME: We currently only support a subset of possible pname values. Implement the rest!
  1796. RETURN_WITH_ERROR_IF(pname != GL_TEXTURE_ENV_MODE, GL_INVALID_ENUM);
  1797. auto param_enum = static_cast<GLenum>(param);
  1798. switch (param_enum) {
  1799. case GL_MODULATE:
  1800. case GL_REPLACE:
  1801. case GL_DECAL:
  1802. case GL_ADD:
  1803. m_active_texture_unit->set_env_mode(param_enum);
  1804. m_sampler_config_is_dirty = true;
  1805. break;
  1806. default:
  1807. // FIXME: We currently only support a subset of possible param values. Implement the rest!
  1808. dbgln_if(GL_DEBUG, "gl_tex_env({:#x}, {:#x}, {}): param unimplemented", target, pname, param);
  1809. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  1810. }
  1811. }
  1812. void GLContext::gl_draw_arrays(GLenum mode, GLint first, GLsizei count)
  1813. {
  1814. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_arrays, mode, first, count);
  1815. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1816. // FIXME: Some modes are still missing (GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES)
  1817. RETURN_WITH_ERROR_IF(!(mode == GL_TRIANGLE_STRIP
  1818. || mode == GL_TRIANGLE_FAN
  1819. || mode == GL_TRIANGLES
  1820. || mode == GL_QUADS
  1821. || mode == GL_QUAD_STRIP
  1822. || mode == GL_POLYGON),
  1823. GL_INVALID_ENUM);
  1824. RETURN_WITH_ERROR_IF(count < 0, GL_INVALID_VALUE);
  1825. // At least the vertex array needs to be enabled
  1826. if (!m_client_side_vertex_array_enabled)
  1827. return;
  1828. auto last = first + count;
  1829. gl_begin(mode);
  1830. for (int i = first; i < last; i++) {
  1831. if (m_client_side_color_array_enabled) {
  1832. float color[4] { 0, 0, 0, 1 };
  1833. read_from_vertex_attribute_pointer(m_client_color_pointer, i, color);
  1834. gl_color(color[0], color[1], color[2], color[3]);
  1835. }
  1836. for (size_t t = 0; t < m_client_tex_coord_pointer.size(); ++t) {
  1837. if (m_client_side_texture_coord_array_enabled[t]) {
  1838. float tex_coords[4] { 0, 0, 0, 0 };
  1839. read_from_vertex_attribute_pointer(m_client_tex_coord_pointer[t], i, tex_coords);
  1840. gl_multi_tex_coord(GL_TEXTURE0 + t, tex_coords[0], tex_coords[1], tex_coords[2], tex_coords[3]);
  1841. }
  1842. }
  1843. if (m_client_side_normal_array_enabled) {
  1844. float normal[3];
  1845. read_from_vertex_attribute_pointer(m_client_normal_pointer, i, normal);
  1846. gl_normal(normal[0], normal[1], normal[2]);
  1847. }
  1848. float vertex[4] { 0, 0, 0, 1 };
  1849. read_from_vertex_attribute_pointer(m_client_vertex_pointer, i, vertex);
  1850. gl_vertex(vertex[0], vertex[1], vertex[2], vertex[3]);
  1851. }
  1852. gl_end();
  1853. }
  1854. void GLContext::gl_draw_elements(GLenum mode, GLsizei count, GLenum type, void const* indices)
  1855. {
  1856. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_elements, mode, count, type, indices);
  1857. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1858. // FIXME: Some modes are still missing (GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES)
  1859. RETURN_WITH_ERROR_IF(!(mode == GL_TRIANGLE_STRIP
  1860. || mode == GL_TRIANGLE_FAN
  1861. || mode == GL_TRIANGLES
  1862. || mode == GL_QUADS
  1863. || mode == GL_QUAD_STRIP
  1864. || mode == GL_POLYGON),
  1865. GL_INVALID_ENUM);
  1866. RETURN_WITH_ERROR_IF(!(type == GL_UNSIGNED_BYTE
  1867. || type == GL_UNSIGNED_SHORT
  1868. || type == GL_UNSIGNED_INT),
  1869. GL_INVALID_ENUM);
  1870. RETURN_WITH_ERROR_IF(count < 0, GL_INVALID_VALUE);
  1871. // At least the vertex array needs to be enabled
  1872. if (!m_client_side_vertex_array_enabled)
  1873. return;
  1874. gl_begin(mode);
  1875. for (int index = 0; index < count; index++) {
  1876. int i = 0;
  1877. switch (type) {
  1878. case GL_UNSIGNED_BYTE:
  1879. i = reinterpret_cast<GLubyte const*>(indices)[index];
  1880. break;
  1881. case GL_UNSIGNED_SHORT:
  1882. i = reinterpret_cast<GLushort const*>(indices)[index];
  1883. break;
  1884. case GL_UNSIGNED_INT:
  1885. i = reinterpret_cast<GLuint const*>(indices)[index];
  1886. break;
  1887. }
  1888. if (m_client_side_color_array_enabled) {
  1889. float color[4] { 0, 0, 0, 1 };
  1890. read_from_vertex_attribute_pointer(m_client_color_pointer, i, color);
  1891. gl_color(color[0], color[1], color[2], color[3]);
  1892. }
  1893. for (size_t t = 0; t < m_client_tex_coord_pointer.size(); ++t) {
  1894. if (m_client_side_texture_coord_array_enabled[t]) {
  1895. float tex_coords[4] { 0, 0, 0, 0 };
  1896. read_from_vertex_attribute_pointer(m_client_tex_coord_pointer[t], i, tex_coords);
  1897. gl_multi_tex_coord(GL_TEXTURE0 + t, tex_coords[0], tex_coords[1], tex_coords[2], tex_coords[3]);
  1898. }
  1899. }
  1900. if (m_client_side_normal_array_enabled) {
  1901. float normal[3];
  1902. read_from_vertex_attribute_pointer(m_client_normal_pointer, i, normal);
  1903. gl_normal(normal[0], normal[1], normal[2]);
  1904. }
  1905. float vertex[4] { 0, 0, 0, 1 };
  1906. read_from_vertex_attribute_pointer(m_client_vertex_pointer, i, vertex);
  1907. gl_vertex(vertex[0], vertex[1], vertex[2], vertex[3]);
  1908. }
  1909. gl_end();
  1910. }
  1911. void GLContext::gl_draw_pixels(GLsizei width, GLsizei height, GLenum format, GLenum type, void const* data)
  1912. {
  1913. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_draw_pixels, width, height, format, type, data);
  1914. RETURN_WITH_ERROR_IF(format < GL_COLOR_INDEX || format > GL_BGRA, GL_INVALID_ENUM);
  1915. RETURN_WITH_ERROR_IF((type < GL_BYTE || type > GL_FLOAT)
  1916. && (type < GL_UNSIGNED_BYTE_3_3_2 || type > GL_UNSIGNED_INT_10_10_10_2)
  1917. && (type < GL_UNSIGNED_BYTE_2_3_3_REV || type > GL_UNSIGNED_INT_2_10_10_10_REV),
  1918. GL_INVALID_ENUM);
  1919. RETURN_WITH_ERROR_IF(type == GL_BITMAP && !(format == GL_COLOR_INDEX || format == GL_STENCIL_INDEX), GL_INVALID_ENUM);
  1920. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  1921. // FIXME: GL_INVALID_OPERATION is generated if format is GL_STENCIL_INDEX and there is no stencil buffer
  1922. // FIXME: GL_INVALID_OPERATION is generated if format is GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_RGB, GL_RGBA,
  1923. // GL_BGR, GL_BGRA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA, and the GL is in color index mode
  1924. RETURN_WITH_ERROR_IF(format != GL_RGB
  1925. && (type == GL_UNSIGNED_BYTE_3_3_2
  1926. || type == GL_UNSIGNED_BYTE_2_3_3_REV
  1927. || type == GL_UNSIGNED_SHORT_5_6_5
  1928. || type == GL_UNSIGNED_SHORT_5_6_5_REV),
  1929. GL_INVALID_OPERATION);
  1930. RETURN_WITH_ERROR_IF(!(format == GL_RGBA || format == GL_BGRA)
  1931. && (type == GL_UNSIGNED_SHORT_4_4_4_4
  1932. || type == GL_UNSIGNED_SHORT_4_4_4_4_REV
  1933. || type == GL_UNSIGNED_SHORT_5_5_5_1
  1934. || type == GL_UNSIGNED_SHORT_1_5_5_5_REV
  1935. || type == GL_UNSIGNED_INT_8_8_8_8
  1936. || type == GL_UNSIGNED_INT_8_8_8_8_REV
  1937. || type == GL_UNSIGNED_INT_10_10_10_2
  1938. || type == GL_UNSIGNED_INT_2_10_10_10_REV),
  1939. GL_INVALID_OPERATION);
  1940. // FIXME: GL_INVALID_OPERATION is generated if a non-zero buffer object name is bound to the GL_PIXEL_UNPACK_BUFFER
  1941. // target and the buffer object's data store is currently mapped.
  1942. // FIXME: GL_INVALID_OPERATION is generated if a non-zero buffer object name is bound to the GL_PIXEL_UNPACK_BUFFER
  1943. // target and the data would be unpacked from the buffer object such that the memory reads required would
  1944. // exceed the data store size.
  1945. // FIXME: GL_INVALID_OPERATION is generated if a non-zero buffer object name is bound to the GL_PIXEL_UNPACK_BUFFER
  1946. // target and data is not evenly divisible into the number of bytes needed to store in memory a datum
  1947. // indicated by type.
  1948. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  1949. // FIXME: we only support RGBA + UNSIGNED_BYTE and DEPTH_COMPONENT + UNSIGNED_SHORT, implement all combinations!
  1950. if (!((format == GL_RGBA && type == GL_UNSIGNED_BYTE) || (format == GL_DEPTH_COMPONENT && type == GL_UNSIGNED_SHORT))) {
  1951. dbgln_if(GL_DEBUG, "gl_draw_pixels(): support for format {:#x} and/or type {:#x} not implemented", format, type);
  1952. return;
  1953. }
  1954. // FIXME: implement support for pixel parameters such as GL_UNPACK_ALIGNMENT
  1955. if (format == GL_RGBA) {
  1956. auto bitmap_or_error = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, { width, height });
  1957. RETURN_WITH_ERROR_IF(bitmap_or_error.is_error(), GL_OUT_OF_MEMORY);
  1958. auto bitmap = bitmap_or_error.release_value();
  1959. auto pixel_data = static_cast<u32 const*>(data);
  1960. for (int y = 0; y < height; ++y)
  1961. for (int x = 0; x < width; ++x)
  1962. bitmap->set_pixel(x, y, Color::from_argb(*(pixel_data++)));
  1963. m_rasterizer->blit_to_color_buffer_at_raster_position(bitmap);
  1964. } else if (format == GL_DEPTH_COMPONENT) {
  1965. Vector<float> depth_values;
  1966. depth_values.ensure_capacity(width * height);
  1967. auto depth_data = static_cast<u16 const*>(data);
  1968. for (int y = 0; y < height; ++y) {
  1969. for (int x = 0; x < width; ++x) {
  1970. auto u16_value = *(depth_data++);
  1971. auto float_value = static_cast<float>(u16_value) / NumericLimits<u16>::max();
  1972. depth_values.append(float_value);
  1973. }
  1974. }
  1975. m_rasterizer->blit_to_depth_buffer_at_raster_position(depth_values, width, height);
  1976. } else {
  1977. VERIFY_NOT_REACHED();
  1978. }
  1979. }
  1980. void GLContext::gl_array_element(GLint i)
  1981. {
  1982. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_array_element, i);
  1983. RETURN_WITH_ERROR_IF(i < 0, GL_INVALID_VALUE);
  1984. // This is effectively the same as `gl_draw_elements`, except we only output a single
  1985. // vertex (this is done between a `gl_begin/end` call) that is to be rendered.
  1986. if (!m_client_side_vertex_array_enabled)
  1987. return;
  1988. if (m_client_side_color_array_enabled) {
  1989. float color[4] { 0, 0, 0, 1 };
  1990. read_from_vertex_attribute_pointer(m_client_color_pointer, i, color);
  1991. gl_color(color[0], color[1], color[2], color[3]);
  1992. }
  1993. for (size_t t = 0; t < m_client_tex_coord_pointer.size(); ++t) {
  1994. if (m_client_side_texture_coord_array_enabled[t]) {
  1995. float tex_coords[4] { 0, 0, 0, 0 };
  1996. read_from_vertex_attribute_pointer(m_client_tex_coord_pointer[t], i, tex_coords);
  1997. gl_multi_tex_coord(GL_TEXTURE0 + t, tex_coords[0], tex_coords[1], tex_coords[2], tex_coords[3]);
  1998. }
  1999. }
  2000. if (m_client_side_normal_array_enabled) {
  2001. float normal[3];
  2002. read_from_vertex_attribute_pointer(m_client_normal_pointer, i, normal);
  2003. gl_normal(normal[0], normal[1], normal[2]);
  2004. }
  2005. float vertex[4] { 0, 0, 0, 1 };
  2006. read_from_vertex_attribute_pointer(m_client_vertex_pointer, i, vertex);
  2007. gl_vertex(vertex[0], vertex[1], vertex[2], vertex[3]);
  2008. }
  2009. void GLContext::gl_depth_range(GLdouble min, GLdouble max)
  2010. {
  2011. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_depth_range, min, max);
  2012. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2013. auto options = m_rasterizer->options();
  2014. options.depth_min = clamp<float>(min, 0.f, 1.f);
  2015. options.depth_max = clamp<float>(max, 0.f, 1.f);
  2016. m_rasterizer->set_options(options);
  2017. }
  2018. void GLContext::gl_depth_func(GLenum func)
  2019. {
  2020. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_depth_func, func);
  2021. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2022. RETURN_WITH_ERROR_IF(!(func == GL_NEVER
  2023. || func == GL_LESS
  2024. || func == GL_EQUAL
  2025. || func == GL_LEQUAL
  2026. || func == GL_GREATER
  2027. || func == GL_NOTEQUAL
  2028. || func == GL_GEQUAL
  2029. || func == GL_ALWAYS),
  2030. GL_INVALID_ENUM);
  2031. auto options = m_rasterizer->options();
  2032. switch (func) {
  2033. case GL_NEVER:
  2034. options.depth_func = GPU::DepthTestFunction::Never;
  2035. break;
  2036. case GL_ALWAYS:
  2037. options.depth_func = GPU::DepthTestFunction::Always;
  2038. break;
  2039. case GL_LESS:
  2040. options.depth_func = GPU::DepthTestFunction::Less;
  2041. break;
  2042. case GL_LEQUAL:
  2043. options.depth_func = GPU::DepthTestFunction::LessOrEqual;
  2044. break;
  2045. case GL_EQUAL:
  2046. options.depth_func = GPU::DepthTestFunction::Equal;
  2047. break;
  2048. case GL_NOTEQUAL:
  2049. options.depth_func = GPU::DepthTestFunction::NotEqual;
  2050. break;
  2051. case GL_GEQUAL:
  2052. options.depth_func = GPU::DepthTestFunction::GreaterOrEqual;
  2053. break;
  2054. case GL_GREATER:
  2055. options.depth_func = GPU::DepthTestFunction::Greater;
  2056. break;
  2057. default:
  2058. VERIFY_NOT_REACHED();
  2059. }
  2060. m_rasterizer->set_options(options);
  2061. }
  2062. // General helper function to read arbitrary vertex attribute data into a float array
  2063. void GLContext::read_from_vertex_attribute_pointer(VertexAttribPointer const& attrib, int index, float* elements)
  2064. {
  2065. auto byte_ptr = reinterpret_cast<char const*>(attrib.pointer);
  2066. auto normalize = attrib.normalize;
  2067. size_t stride = attrib.stride;
  2068. switch (attrib.type) {
  2069. case GL_BYTE: {
  2070. if (stride == 0)
  2071. stride = sizeof(GLbyte) * attrib.size;
  2072. for (int i = 0; i < attrib.size; i++) {
  2073. elements[i] = *(reinterpret_cast<GLbyte const*>(byte_ptr + stride * index) + i);
  2074. if (normalize)
  2075. elements[i] /= 0x80;
  2076. }
  2077. break;
  2078. }
  2079. case GL_UNSIGNED_BYTE: {
  2080. if (stride == 0)
  2081. stride = sizeof(GLubyte) * attrib.size;
  2082. for (int i = 0; i < attrib.size; i++) {
  2083. elements[i] = *(reinterpret_cast<GLubyte const*>(byte_ptr + stride * index) + i);
  2084. if (normalize)
  2085. elements[i] /= 0xff;
  2086. }
  2087. break;
  2088. }
  2089. case GL_SHORT: {
  2090. if (stride == 0)
  2091. stride = sizeof(GLshort) * attrib.size;
  2092. for (int i = 0; i < attrib.size; i++) {
  2093. elements[i] = *(reinterpret_cast<GLshort const*>(byte_ptr + stride * index) + i);
  2094. if (normalize)
  2095. elements[i] /= 0x8000;
  2096. }
  2097. break;
  2098. }
  2099. case GL_UNSIGNED_SHORT: {
  2100. if (stride == 0)
  2101. stride = sizeof(GLushort) * attrib.size;
  2102. for (int i = 0; i < attrib.size; i++) {
  2103. elements[i] = *(reinterpret_cast<GLushort const*>(byte_ptr + stride * index) + i);
  2104. if (normalize)
  2105. elements[i] /= 0xffff;
  2106. }
  2107. break;
  2108. }
  2109. case GL_INT: {
  2110. if (stride == 0)
  2111. stride = sizeof(GLint) * attrib.size;
  2112. for (int i = 0; i < attrib.size; i++) {
  2113. elements[i] = *(reinterpret_cast<GLint const*>(byte_ptr + stride * index) + i);
  2114. if (normalize)
  2115. elements[i] /= 0x80000000;
  2116. }
  2117. break;
  2118. }
  2119. case GL_UNSIGNED_INT: {
  2120. if (stride == 0)
  2121. stride = sizeof(GLuint) * attrib.size;
  2122. for (int i = 0; i < attrib.size; i++) {
  2123. elements[i] = *(reinterpret_cast<GLuint const*>(byte_ptr + stride * index) + i);
  2124. if (normalize)
  2125. elements[i] /= 0xffffffff;
  2126. }
  2127. break;
  2128. }
  2129. case GL_FLOAT: {
  2130. if (stride == 0)
  2131. stride = sizeof(GLfloat) * attrib.size;
  2132. for (int i = 0; i < attrib.size; i++)
  2133. elements[i] = *(reinterpret_cast<GLfloat const*>(byte_ptr + stride * index) + i);
  2134. break;
  2135. }
  2136. case GL_DOUBLE: {
  2137. if (stride == 0)
  2138. stride = sizeof(GLdouble) * attrib.size;
  2139. for (int i = 0; i < attrib.size; i++)
  2140. elements[i] = static_cast<float>(*(reinterpret_cast<GLdouble const*>(byte_ptr + stride * index) + i));
  2141. break;
  2142. }
  2143. }
  2144. }
  2145. void GLContext::gl_color_mask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
  2146. {
  2147. auto options = m_rasterizer->options();
  2148. auto mask = options.color_mask;
  2149. if (!red)
  2150. mask &= ~0x000000ff;
  2151. else
  2152. mask |= 0x000000ff;
  2153. if (!green)
  2154. mask &= ~0x0000ff00;
  2155. else
  2156. mask |= 0x0000ff00;
  2157. if (!blue)
  2158. mask &= ~0x00ff0000;
  2159. else
  2160. mask |= 0x00ff0000;
  2161. if (!alpha)
  2162. mask &= ~0xff000000;
  2163. else
  2164. mask |= 0xff000000;
  2165. options.color_mask = mask;
  2166. m_rasterizer->set_options(options);
  2167. }
  2168. void GLContext::gl_polygon_mode(GLenum face, GLenum mode)
  2169. {
  2170. RETURN_WITH_ERROR_IF(!(face == GL_BACK || face == GL_FRONT || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2171. RETURN_WITH_ERROR_IF(!(mode == GL_POINT || mode == GL_LINE || mode == GL_FILL), GL_INVALID_ENUM);
  2172. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2173. auto options = m_rasterizer->options();
  2174. // FIXME: This must support different polygon modes for front- and backside
  2175. if (face == GL_BACK) {
  2176. dbgln_if(GL_DEBUG, "gl_polygon_mode(GL_BACK, {:#x}): unimplemented", mode);
  2177. return;
  2178. }
  2179. auto map_mode = [](GLenum mode) -> GPU::PolygonMode {
  2180. switch (mode) {
  2181. case GL_FILL:
  2182. return GPU::PolygonMode::Fill;
  2183. case GL_LINE:
  2184. return GPU::PolygonMode::Line;
  2185. case GL_POINT:
  2186. return GPU::PolygonMode::Point;
  2187. default:
  2188. VERIFY_NOT_REACHED();
  2189. }
  2190. };
  2191. options.polygon_mode = map_mode(mode);
  2192. m_rasterizer->set_options(options);
  2193. }
  2194. void GLContext::gl_polygon_offset(GLfloat factor, GLfloat units)
  2195. {
  2196. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_polygon_offset, factor, units);
  2197. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2198. auto rasterizer_options = m_rasterizer->options();
  2199. rasterizer_options.depth_offset_factor = factor;
  2200. rasterizer_options.depth_offset_constant = units;
  2201. m_rasterizer->set_options(rasterizer_options);
  2202. }
  2203. void GLContext::gl_fogfv(GLenum pname, GLfloat* params)
  2204. {
  2205. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_fogfv, pname, params);
  2206. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2207. auto options = m_rasterizer->options();
  2208. switch (pname) {
  2209. case GL_FOG_COLOR:
  2210. options.fog_color = { params[0], params[1], params[2], params[3] };
  2211. break;
  2212. default:
  2213. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2214. }
  2215. m_rasterizer->set_options(options);
  2216. }
  2217. void GLContext::gl_fogf(GLenum pname, GLfloat param)
  2218. {
  2219. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_fogf, pname, param);
  2220. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2221. RETURN_WITH_ERROR_IF(param < 0.0f, GL_INVALID_VALUE);
  2222. auto options = m_rasterizer->options();
  2223. switch (pname) {
  2224. case GL_FOG_DENSITY:
  2225. options.fog_density = param;
  2226. break;
  2227. case GL_FOG_END:
  2228. options.fog_end = param;
  2229. break;
  2230. case GL_FOG_START:
  2231. options.fog_start = param;
  2232. break;
  2233. default:
  2234. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2235. }
  2236. m_rasterizer->set_options(options);
  2237. }
  2238. void GLContext::gl_fogi(GLenum pname, GLint param)
  2239. {
  2240. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_fogi, pname, param);
  2241. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2242. RETURN_WITH_ERROR_IF(param != GL_LINEAR && param != GL_EXP && param != GL_EXP2, GL_INVALID_ENUM);
  2243. auto options = m_rasterizer->options();
  2244. switch (pname) {
  2245. case GL_FOG_MODE:
  2246. switch (param) {
  2247. case GL_LINEAR:
  2248. options.fog_mode = GPU::FogMode::Linear;
  2249. break;
  2250. case GL_EXP:
  2251. options.fog_mode = GPU::FogMode::Exp;
  2252. break;
  2253. case GL_EXP2:
  2254. options.fog_mode = GPU::FogMode::Exp2;
  2255. break;
  2256. }
  2257. break;
  2258. default:
  2259. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2260. }
  2261. m_rasterizer->set_options(options);
  2262. }
  2263. void GLContext::gl_pixel_storei(GLenum pname, GLint param)
  2264. {
  2265. // FIXME: Implement missing parameters
  2266. switch (pname) {
  2267. case GL_PACK_ALIGNMENT:
  2268. RETURN_WITH_ERROR_IF(param != 1 && param != 2 && param != 4 && param != 8, GL_INVALID_VALUE);
  2269. m_pack_alignment = param;
  2270. break;
  2271. case GL_UNPACK_ROW_LENGTH:
  2272. RETURN_WITH_ERROR_IF(param < 0, GL_INVALID_VALUE);
  2273. m_unpack_row_length = static_cast<size_t>(param);
  2274. break;
  2275. case GL_UNPACK_ALIGNMENT:
  2276. RETURN_WITH_ERROR_IF(param != 1 && param != 2 && param != 4 && param != 8, GL_INVALID_VALUE);
  2277. m_unpack_alignment = param;
  2278. break;
  2279. default:
  2280. RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM);
  2281. break;
  2282. }
  2283. }
  2284. void GLContext::gl_scissor(GLint x, GLint y, GLsizei width, GLsizei height)
  2285. {
  2286. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_scissor, x, y, width, height);
  2287. RETURN_WITH_ERROR_IF(width < 0 || height < 0, GL_INVALID_VALUE);
  2288. auto options = m_rasterizer->options();
  2289. options.scissor_box = { x, y, width, height };
  2290. m_rasterizer->set_options(options);
  2291. }
  2292. void GLContext::gl_stencil_func_separate(GLenum face, GLenum func, GLint ref, GLuint mask)
  2293. {
  2294. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_stencil_func_separate, face, func, ref, mask);
  2295. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2296. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2297. RETURN_WITH_ERROR_IF(!(func == GL_NEVER
  2298. || func == GL_LESS
  2299. || func == GL_LEQUAL
  2300. || func == GL_GREATER
  2301. || func == GL_GEQUAL
  2302. || func == GL_EQUAL
  2303. || func == GL_NOTEQUAL
  2304. || func == GL_ALWAYS),
  2305. GL_INVALID_ENUM);
  2306. ref = clamp(ref, 0, (1 << m_device_info.stencil_bits) - 1);
  2307. StencilFunctionOptions new_options = { func, ref, mask };
  2308. if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
  2309. m_stencil_function[Face::Front] = new_options;
  2310. if (face == GL_BACK || face == GL_FRONT_AND_BACK)
  2311. m_stencil_function[Face::Back] = new_options;
  2312. m_stencil_configuration_dirty = true;
  2313. }
  2314. void GLContext::gl_stencil_mask_separate(GLenum face, GLuint mask)
  2315. {
  2316. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_stencil_mask_separate, face, mask);
  2317. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2318. if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
  2319. m_stencil_operation[Face::Front].write_mask = mask;
  2320. if (face == GL_BACK || face == GL_FRONT_AND_BACK)
  2321. m_stencil_operation[Face::Back].write_mask = mask;
  2322. m_stencil_configuration_dirty = true;
  2323. }
  2324. void GLContext::gl_stencil_op_separate(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)
  2325. {
  2326. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_stencil_op_separate, face, sfail, dpfail, dppass);
  2327. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2328. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2329. auto is_valid_op = [](GLenum op) -> bool {
  2330. return op == GL_KEEP || op == GL_ZERO || op == GL_REPLACE || op == GL_INCR || op == GL_INCR_WRAP
  2331. || op == GL_DECR || op == GL_DECR_WRAP || op == GL_INVERT;
  2332. };
  2333. RETURN_WITH_ERROR_IF(!is_valid_op(sfail), GL_INVALID_ENUM);
  2334. RETURN_WITH_ERROR_IF(!is_valid_op(dpfail), GL_INVALID_ENUM);
  2335. RETURN_WITH_ERROR_IF(!is_valid_op(dppass), GL_INVALID_ENUM);
  2336. auto update_stencil_operation = [&](Face face, GLenum sfail, GLenum dpfail, GLenum dppass) {
  2337. auto& stencil_operation = m_stencil_operation[face];
  2338. stencil_operation.op_fail = sfail;
  2339. stencil_operation.op_depth_fail = dpfail;
  2340. stencil_operation.op_pass = dppass;
  2341. };
  2342. if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
  2343. update_stencil_operation(Face::Front, sfail, dpfail, dppass);
  2344. if (face == GL_BACK || face == GL_FRONT_AND_BACK)
  2345. update_stencil_operation(Face::Back, sfail, dpfail, dppass);
  2346. m_stencil_configuration_dirty = true;
  2347. }
  2348. void GLContext::gl_normal(GLfloat nx, GLfloat ny, GLfloat nz)
  2349. {
  2350. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_normal, nx, ny, nz);
  2351. m_current_vertex_normal = { nx, ny, nz };
  2352. }
  2353. void GLContext::gl_raster_pos(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
  2354. {
  2355. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_raster_pos, x, y, z, w);
  2356. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2357. m_rasterizer->set_raster_position({ x, y, z, w }, m_model_view_matrix, m_projection_matrix);
  2358. }
  2359. void GLContext::gl_line_width(GLfloat width)
  2360. {
  2361. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_line_width, width);
  2362. RETURN_WITH_ERROR_IF(width <= 0, GL_INVALID_VALUE);
  2363. m_line_width = width;
  2364. }
  2365. void GLContext::gl_push_attrib(GLbitfield mask)
  2366. {
  2367. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_push_attrib, mask);
  2368. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2369. // FIXME: implement
  2370. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_push_attrib({})", mask);
  2371. }
  2372. void GLContext::gl_pop_attrib()
  2373. {
  2374. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_pop_attrib);
  2375. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2376. // FIXME: implement
  2377. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_pop_attrib()");
  2378. }
  2379. void GLContext::gl_light_model(GLenum pname, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
  2380. {
  2381. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_light_model, pname, x, y, z, w);
  2382. RETURN_WITH_ERROR_IF(pname != GL_LIGHT_MODEL_AMBIENT
  2383. && pname != GL_LIGHT_MODEL_COLOR_CONTROL
  2384. && pname != GL_LIGHT_MODEL_LOCAL_VIEWER
  2385. && pname != GL_LIGHT_MODEL_TWO_SIDE,
  2386. GL_INVALID_ENUM);
  2387. auto lighting_params = m_rasterizer->light_model();
  2388. switch (pname) {
  2389. case GL_LIGHT_MODEL_AMBIENT:
  2390. lighting_params.scene_ambient_color = { x, y, z, w };
  2391. break;
  2392. case GL_LIGHT_MODEL_COLOR_CONTROL: {
  2393. GLenum color_control = static_cast<GLenum>(x);
  2394. RETURN_WITH_ERROR_IF(color_control != GL_SINGLE_COLOR && color_control != GL_SEPARATE_SPECULAR_COLOR, GL_INVALID_ENUM);
  2395. lighting_params.color_control = (color_control == GL_SINGLE_COLOR) ? GPU::ColorControl::SingleColor : GPU::ColorControl::SeparateSpecularColor;
  2396. break;
  2397. }
  2398. case GL_LIGHT_MODEL_LOCAL_VIEWER:
  2399. // 0 means the viewer is at infinity
  2400. // 1 means they're in local (eye) space
  2401. lighting_params.viewer_at_infinity = (x != 1.0f);
  2402. break;
  2403. case GL_LIGHT_MODEL_TWO_SIDE:
  2404. VERIFY(y == 0.0f && z == 0.0f && w == 0.0f);
  2405. lighting_params.two_sided_lighting = x;
  2406. break;
  2407. default:
  2408. VERIFY_NOT_REACHED();
  2409. }
  2410. m_rasterizer->set_light_model_params(lighting_params);
  2411. }
  2412. void GLContext::gl_bitmap(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, GLubyte const* bitmap)
  2413. {
  2414. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_bitmap, width, height, xorig, yorig, xmove, ymove, bitmap);
  2415. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2416. if (bitmap != nullptr) {
  2417. // FIXME: implement
  2418. dbgln_if(GL_DEBUG, "gl_bitmap({}, {}, {}, {}, {}, {}, {}): unimplemented", width, height, xorig, yorig, xmove, ymove, bitmap);
  2419. }
  2420. auto raster_position = m_rasterizer->raster_position();
  2421. raster_position.window_coordinates += { xmove, ymove, 0.f, 0.f };
  2422. m_rasterizer->set_raster_position(raster_position);
  2423. }
  2424. void GLContext::gl_copy_tex_image_2d(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
  2425. {
  2426. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_copy_tex_image_2d, target, level, internalformat, x, y, width, height, border);
  2427. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2428. // FIXME: implement
  2429. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_copy_tex_image_2d({:#x}, {}, {:#x}, {}, {}, {}, {}, {})",
  2430. target, level, internalformat, x, y, width, height, border);
  2431. }
  2432. void GLContext::gl_get_tex_parameter_integerv(GLenum target, GLint level, GLenum pname, GLint* params)
  2433. {
  2434. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2435. // FIXME: support targets other than GL_TEXTURE_2D
  2436. RETURN_WITH_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
  2437. // FIXME: support other parameter names
  2438. RETURN_WITH_ERROR_IF(pname < GL_TEXTURE_WIDTH || pname > GL_TEXTURE_HEIGHT, GL_INVALID_ENUM);
  2439. RETURN_WITH_ERROR_IF(level < 0 || level > Texture2D::LOG2_MAX_TEXTURE_SIZE, GL_INVALID_VALUE);
  2440. // FIXME: GL_INVALID_VALUE is generated if target is GL_TEXTURE_BUFFER and level is not zero
  2441. // FIXME: GL_INVALID_OPERATION is generated if GL_TEXTURE_COMPRESSED_IMAGE_SIZE is queried on texture images with an uncompressed internal format or on proxy targets
  2442. VERIFY(!m_active_texture_unit->texture_2d_target_texture().is_null());
  2443. auto const texture_2d = m_active_texture_unit->texture_2d_target_texture();
  2444. switch (pname) {
  2445. case GL_TEXTURE_HEIGHT:
  2446. *params = texture_2d->height_at_lod(level);
  2447. break;
  2448. case GL_TEXTURE_WIDTH:
  2449. *params = texture_2d->width_at_lod(level);
  2450. break;
  2451. }
  2452. }
  2453. void GLContext::gl_rect(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)
  2454. {
  2455. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_rect, x1, y1, x2, y2);
  2456. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2457. gl_begin(GL_POLYGON);
  2458. gl_vertex(x1, y1, 0.0, 1.0);
  2459. gl_vertex(x2, y1, 0.0, 1.0);
  2460. gl_vertex(x2, y2, 0.0, 1.0);
  2461. gl_vertex(x1, y2, 0.0, 1.0);
  2462. gl_end();
  2463. }
  2464. void GLContext::gl_tex_gen(GLenum coord, GLenum pname, GLint param)
  2465. {
  2466. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_gen, coord, pname, param);
  2467. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2468. RETURN_WITH_ERROR_IF(coord < GL_S || coord > GL_Q, GL_INVALID_ENUM);
  2469. RETURN_WITH_ERROR_IF(pname != GL_TEXTURE_GEN_MODE, GL_INVALID_ENUM);
  2470. RETURN_WITH_ERROR_IF(param != GL_EYE_LINEAR
  2471. && param != GL_OBJECT_LINEAR
  2472. && param != GL_SPHERE_MAP
  2473. && param != GL_NORMAL_MAP
  2474. && param != GL_REFLECTION_MAP,
  2475. GL_INVALID_ENUM);
  2476. RETURN_WITH_ERROR_IF((coord == GL_R || coord == GL_Q) && param == GL_SPHERE_MAP, GL_INVALID_ENUM);
  2477. RETURN_WITH_ERROR_IF(coord == GL_Q && (param == GL_REFLECTION_MAP || param == GL_NORMAL_MAP), GL_INVALID_ENUM);
  2478. GLenum const capability = GL_TEXTURE_GEN_S + (coord - GL_S);
  2479. texture_coordinate_generation(m_active_texture_unit_index, capability).generation_mode = param;
  2480. m_texcoord_generation_dirty = true;
  2481. }
  2482. void GLContext::gl_tex_gen_floatv(GLenum coord, GLenum pname, GLfloat const* params)
  2483. {
  2484. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_tex_gen_floatv, coord, pname, params);
  2485. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2486. RETURN_WITH_ERROR_IF(coord < GL_S || coord > GL_Q, GL_INVALID_ENUM);
  2487. RETURN_WITH_ERROR_IF(pname != GL_TEXTURE_GEN_MODE
  2488. && pname != GL_OBJECT_PLANE
  2489. && pname != GL_EYE_PLANE,
  2490. GL_INVALID_ENUM);
  2491. GLenum const capability = GL_TEXTURE_GEN_S + (coord - GL_S);
  2492. switch (pname) {
  2493. case GL_TEXTURE_GEN_MODE: {
  2494. auto param = static_cast<GLenum>(params[0]);
  2495. RETURN_WITH_ERROR_IF(param != GL_EYE_LINEAR
  2496. && param != GL_OBJECT_LINEAR
  2497. && param != GL_SPHERE_MAP
  2498. && param != GL_NORMAL_MAP
  2499. && param != GL_REFLECTION_MAP,
  2500. GL_INVALID_ENUM);
  2501. RETURN_WITH_ERROR_IF((coord == GL_R || coord == GL_Q) && param == GL_SPHERE_MAP, GL_INVALID_ENUM);
  2502. RETURN_WITH_ERROR_IF(coord == GL_Q && (param == GL_REFLECTION_MAP || param == GL_NORMAL_MAP), GL_INVALID_ENUM);
  2503. texture_coordinate_generation(m_active_texture_unit_index, capability).generation_mode = param;
  2504. break;
  2505. }
  2506. case GL_OBJECT_PLANE:
  2507. texture_coordinate_generation(m_active_texture_unit_index, capability).object_plane_coefficients = { params[0], params[1], params[2], params[3] };
  2508. break;
  2509. case GL_EYE_PLANE: {
  2510. auto const& inverse_model_view = m_model_view_matrix.inverse();
  2511. auto input_coefficients = FloatVector4 { params[0], params[1], params[2], params[3] };
  2512. // Note: we are allowed to store transformed coefficients here, according to the documentation on
  2513. // `glGetTexGen`:
  2514. //
  2515. // "The returned values are those maintained in eye coordinates. They are not equal to the values
  2516. // specified using glTexGen, unless the modelview matrix was identity when glTexGen was called."
  2517. texture_coordinate_generation(m_active_texture_unit_index, capability).eye_plane_coefficients = inverse_model_view * input_coefficients;
  2518. break;
  2519. }
  2520. default:
  2521. VERIFY_NOT_REACHED();
  2522. }
  2523. m_texcoord_generation_dirty = true;
  2524. }
  2525. void GLContext::present()
  2526. {
  2527. m_rasterizer->blit_color_buffer_to(*m_frontbuffer);
  2528. }
  2529. void GLContext::sync_device_config()
  2530. {
  2531. sync_device_sampler_config();
  2532. sync_device_texcoord_config();
  2533. sync_light_state();
  2534. sync_stencil_configuration();
  2535. }
  2536. void GLContext::sync_device_sampler_config()
  2537. {
  2538. if (!m_sampler_config_is_dirty)
  2539. return;
  2540. m_sampler_config_is_dirty = false;
  2541. for (unsigned i = 0; i < m_texture_units.size(); ++i) {
  2542. auto const& texture_unit = m_texture_units[i];
  2543. if (!texture_unit.texture_2d_enabled())
  2544. continue;
  2545. GPU::SamplerConfig config;
  2546. auto texture_2d = texture_unit.texture_2d_target_texture();
  2547. if (texture_2d.is_null()) {
  2548. config.bound_image = nullptr;
  2549. m_rasterizer->set_sampler_config(i, config);
  2550. continue;
  2551. }
  2552. config.bound_image = texture_2d->device_image();
  2553. auto const& sampler = texture_2d->sampler();
  2554. switch (sampler.min_filter()) {
  2555. case GL_NEAREST:
  2556. config.texture_min_filter = GPU::TextureFilter::Nearest;
  2557. config.mipmap_filter = GPU::MipMapFilter::None;
  2558. break;
  2559. case GL_LINEAR:
  2560. config.texture_min_filter = GPU::TextureFilter::Linear;
  2561. config.mipmap_filter = GPU::MipMapFilter::None;
  2562. break;
  2563. case GL_NEAREST_MIPMAP_NEAREST:
  2564. config.texture_min_filter = GPU::TextureFilter::Nearest;
  2565. config.mipmap_filter = GPU::MipMapFilter::Nearest;
  2566. break;
  2567. case GL_LINEAR_MIPMAP_NEAREST:
  2568. config.texture_min_filter = GPU::TextureFilter::Linear;
  2569. config.mipmap_filter = GPU::MipMapFilter::Nearest;
  2570. break;
  2571. case GL_NEAREST_MIPMAP_LINEAR:
  2572. config.texture_min_filter = GPU::TextureFilter::Nearest;
  2573. config.mipmap_filter = GPU::MipMapFilter::Linear;
  2574. break;
  2575. case GL_LINEAR_MIPMAP_LINEAR:
  2576. config.texture_min_filter = GPU::TextureFilter::Linear;
  2577. config.mipmap_filter = GPU::MipMapFilter::Linear;
  2578. break;
  2579. default:
  2580. VERIFY_NOT_REACHED();
  2581. }
  2582. switch (sampler.mag_filter()) {
  2583. case GL_NEAREST:
  2584. config.texture_mag_filter = GPU::TextureFilter::Nearest;
  2585. break;
  2586. case GL_LINEAR:
  2587. config.texture_mag_filter = GPU::TextureFilter::Linear;
  2588. break;
  2589. default:
  2590. VERIFY_NOT_REACHED();
  2591. }
  2592. switch (sampler.wrap_s_mode()) {
  2593. case GL_CLAMP:
  2594. config.texture_wrap_u = GPU::TextureWrapMode::Clamp;
  2595. break;
  2596. case GL_CLAMP_TO_BORDER:
  2597. config.texture_wrap_u = GPU::TextureWrapMode::ClampToBorder;
  2598. break;
  2599. case GL_CLAMP_TO_EDGE:
  2600. config.texture_wrap_u = GPU::TextureWrapMode::ClampToEdge;
  2601. break;
  2602. case GL_REPEAT:
  2603. config.texture_wrap_u = GPU::TextureWrapMode::Repeat;
  2604. break;
  2605. case GL_MIRRORED_REPEAT:
  2606. config.texture_wrap_u = GPU::TextureWrapMode::MirroredRepeat;
  2607. break;
  2608. default:
  2609. VERIFY_NOT_REACHED();
  2610. }
  2611. switch (sampler.wrap_t_mode()) {
  2612. case GL_CLAMP:
  2613. config.texture_wrap_v = GPU::TextureWrapMode::Clamp;
  2614. break;
  2615. case GL_CLAMP_TO_BORDER:
  2616. config.texture_wrap_v = GPU::TextureWrapMode::ClampToBorder;
  2617. break;
  2618. case GL_CLAMP_TO_EDGE:
  2619. config.texture_wrap_v = GPU::TextureWrapMode::ClampToEdge;
  2620. break;
  2621. case GL_REPEAT:
  2622. config.texture_wrap_v = GPU::TextureWrapMode::Repeat;
  2623. break;
  2624. case GL_MIRRORED_REPEAT:
  2625. config.texture_wrap_v = GPU::TextureWrapMode::MirroredRepeat;
  2626. break;
  2627. default:
  2628. VERIFY_NOT_REACHED();
  2629. }
  2630. switch (texture_unit.env_mode()) {
  2631. case GL_MODULATE:
  2632. config.fixed_function_texture_env_mode = GPU::TextureEnvMode::Modulate;
  2633. break;
  2634. case GL_REPLACE:
  2635. config.fixed_function_texture_env_mode = GPU::TextureEnvMode::Replace;
  2636. break;
  2637. case GL_DECAL:
  2638. config.fixed_function_texture_env_mode = GPU::TextureEnvMode::Decal;
  2639. break;
  2640. case GL_ADD:
  2641. config.fixed_function_texture_env_mode = GPU::TextureEnvMode::Add;
  2642. break;
  2643. default:
  2644. VERIFY_NOT_REACHED();
  2645. }
  2646. config.border_color = sampler.border_color();
  2647. m_rasterizer->set_sampler_config(i, config);
  2648. }
  2649. }
  2650. void GLContext::sync_light_state()
  2651. {
  2652. if (!m_light_state_is_dirty)
  2653. return;
  2654. m_light_state_is_dirty = false;
  2655. auto options = m_rasterizer->options();
  2656. options.color_material_enabled = m_color_material_enabled;
  2657. switch (m_color_material_face) {
  2658. case GL_BACK:
  2659. options.color_material_face = GPU::ColorMaterialFace::Back;
  2660. break;
  2661. case GL_FRONT:
  2662. options.color_material_face = GPU::ColorMaterialFace::Front;
  2663. break;
  2664. case GL_FRONT_AND_BACK:
  2665. options.color_material_face = GPU::ColorMaterialFace::FrontAndBack;
  2666. break;
  2667. default:
  2668. VERIFY_NOT_REACHED();
  2669. }
  2670. switch (m_color_material_mode) {
  2671. case GL_AMBIENT:
  2672. options.color_material_mode = GPU::ColorMaterialMode::Ambient;
  2673. break;
  2674. case GL_AMBIENT_AND_DIFFUSE:
  2675. options.color_material_mode = GPU::ColorMaterialMode::Ambient;
  2676. options.color_material_mode = GPU::ColorMaterialMode::Diffuse;
  2677. break;
  2678. case GL_DIFFUSE:
  2679. options.color_material_mode = GPU::ColorMaterialMode::Diffuse;
  2680. break;
  2681. case GL_EMISSION:
  2682. options.color_material_mode = GPU::ColorMaterialMode::Emissive;
  2683. break;
  2684. case GL_SPECULAR:
  2685. options.color_material_mode = GPU::ColorMaterialMode::Specular;
  2686. break;
  2687. default:
  2688. VERIFY_NOT_REACHED();
  2689. }
  2690. m_rasterizer->set_options(options);
  2691. for (auto light_id = 0u; light_id < m_device_info.num_lights; light_id++) {
  2692. auto const& current_light_state = m_light_states.at(light_id);
  2693. m_rasterizer->set_light_state(light_id, current_light_state);
  2694. }
  2695. m_rasterizer->set_material_state(GPU::Face::Front, m_material_states[Face::Front]);
  2696. m_rasterizer->set_material_state(GPU::Face::Back, m_material_states[Face::Back]);
  2697. }
  2698. void GLContext::sync_device_texcoord_config()
  2699. {
  2700. if (!m_texcoord_generation_dirty)
  2701. return;
  2702. m_texcoord_generation_dirty = false;
  2703. auto options = m_rasterizer->options();
  2704. for (size_t i = 0; i < m_device_info.num_texture_units; ++i) {
  2705. u8 enabled_coordinates = GPU::TexCoordGenerationCoordinate::None;
  2706. for (GLenum capability = GL_TEXTURE_GEN_S; capability <= GL_TEXTURE_GEN_Q; ++capability) {
  2707. auto const context_coordinate_config = texture_coordinate_generation(i, capability);
  2708. if (!context_coordinate_config.enabled)
  2709. continue;
  2710. GPU::TexCoordGenerationConfig* texcoord_generation_config;
  2711. switch (capability) {
  2712. case GL_TEXTURE_GEN_S:
  2713. enabled_coordinates |= GPU::TexCoordGenerationCoordinate::S;
  2714. texcoord_generation_config = &options.texcoord_generation_config[i][0];
  2715. break;
  2716. case GL_TEXTURE_GEN_T:
  2717. enabled_coordinates |= GPU::TexCoordGenerationCoordinate::T;
  2718. texcoord_generation_config = &options.texcoord_generation_config[i][1];
  2719. break;
  2720. case GL_TEXTURE_GEN_R:
  2721. enabled_coordinates |= GPU::TexCoordGenerationCoordinate::R;
  2722. texcoord_generation_config = &options.texcoord_generation_config[i][2];
  2723. break;
  2724. case GL_TEXTURE_GEN_Q:
  2725. enabled_coordinates |= GPU::TexCoordGenerationCoordinate::Q;
  2726. texcoord_generation_config = &options.texcoord_generation_config[i][3];
  2727. break;
  2728. default:
  2729. VERIFY_NOT_REACHED();
  2730. }
  2731. switch (context_coordinate_config.generation_mode) {
  2732. case GL_OBJECT_LINEAR:
  2733. texcoord_generation_config->mode = GPU::TexCoordGenerationMode::ObjectLinear;
  2734. texcoord_generation_config->coefficients = context_coordinate_config.object_plane_coefficients;
  2735. break;
  2736. case GL_EYE_LINEAR:
  2737. texcoord_generation_config->mode = GPU::TexCoordGenerationMode::EyeLinear;
  2738. texcoord_generation_config->coefficients = context_coordinate_config.eye_plane_coefficients;
  2739. break;
  2740. case GL_SPHERE_MAP:
  2741. texcoord_generation_config->mode = GPU::TexCoordGenerationMode::SphereMap;
  2742. break;
  2743. case GL_REFLECTION_MAP:
  2744. texcoord_generation_config->mode = GPU::TexCoordGenerationMode::ReflectionMap;
  2745. break;
  2746. case GL_NORMAL_MAP:
  2747. texcoord_generation_config->mode = GPU::TexCoordGenerationMode::NormalMap;
  2748. break;
  2749. }
  2750. }
  2751. options.texcoord_generation_enabled_coordinates[i] = enabled_coordinates;
  2752. }
  2753. m_rasterizer->set_options(options);
  2754. }
  2755. void GLContext::sync_stencil_configuration()
  2756. {
  2757. if (!m_stencil_configuration_dirty)
  2758. return;
  2759. m_stencil_configuration_dirty = false;
  2760. auto set_device_stencil = [&](GPU::Face face, StencilFunctionOptions func, StencilOperationOptions op) {
  2761. GPU::StencilConfiguration device_configuration;
  2762. // Stencil test function
  2763. auto map_func = [](GLenum func) -> GPU::StencilTestFunction {
  2764. switch (func) {
  2765. case GL_ALWAYS:
  2766. return GPU::StencilTestFunction::Always;
  2767. case GL_EQUAL:
  2768. return GPU::StencilTestFunction::Equal;
  2769. case GL_GEQUAL:
  2770. return GPU::StencilTestFunction::GreaterOrEqual;
  2771. case GL_GREATER:
  2772. return GPU::StencilTestFunction::Greater;
  2773. case GL_LESS:
  2774. return GPU::StencilTestFunction::Less;
  2775. case GL_LEQUAL:
  2776. return GPU::StencilTestFunction::LessOrEqual;
  2777. case GL_NEVER:
  2778. return GPU::StencilTestFunction::Never;
  2779. case GL_NOTEQUAL:
  2780. return GPU::StencilTestFunction::NotEqual;
  2781. }
  2782. VERIFY_NOT_REACHED();
  2783. };
  2784. device_configuration.test_function = map_func(func.func);
  2785. device_configuration.reference_value = func.reference_value;
  2786. device_configuration.test_mask = func.mask;
  2787. // Stencil operation
  2788. auto map_operation = [](GLenum operation) -> GPU::StencilOperation {
  2789. switch (operation) {
  2790. case GL_DECR:
  2791. return GPU::StencilOperation::Decrement;
  2792. case GL_DECR_WRAP:
  2793. return GPU::StencilOperation::DecrementWrap;
  2794. case GL_INCR:
  2795. return GPU::StencilOperation::Increment;
  2796. case GL_INCR_WRAP:
  2797. return GPU::StencilOperation::IncrementWrap;
  2798. case GL_INVERT:
  2799. return GPU::StencilOperation::Invert;
  2800. case GL_KEEP:
  2801. return GPU::StencilOperation::Keep;
  2802. case GL_REPLACE:
  2803. return GPU::StencilOperation::Replace;
  2804. case GL_ZERO:
  2805. return GPU::StencilOperation::Zero;
  2806. }
  2807. VERIFY_NOT_REACHED();
  2808. };
  2809. device_configuration.on_stencil_test_fail = map_operation(op.op_fail);
  2810. device_configuration.on_depth_test_fail = map_operation(op.op_depth_fail);
  2811. device_configuration.on_pass = map_operation(op.op_pass);
  2812. device_configuration.write_mask = op.write_mask;
  2813. m_rasterizer->set_stencil_configuration(face, device_configuration);
  2814. };
  2815. set_device_stencil(GPU::Face::Front, m_stencil_function[Face::Front], m_stencil_operation[Face::Front]);
  2816. set_device_stencil(GPU::Face::Back, m_stencil_function[Face::Back], m_stencil_operation[Face::Back]);
  2817. }
  2818. void GLContext::build_extension_string()
  2819. {
  2820. Vector<StringView> extensions;
  2821. // FIXME: npot texture support became a required core feature starting with OpenGL 2.0 (https://www.khronos.org/opengl/wiki/NPOT_Texture)
  2822. // Ideally we would verify if the selected device adheres to the requested OpenGL context version before context creation
  2823. // and refuse to create a context if it doesn't.
  2824. if (m_device_info.supports_npot_textures)
  2825. extensions.append("GL_ARB_texture_non_power_of_two");
  2826. if (m_device_info.num_texture_units > 1)
  2827. extensions.append("GL_ARB_multitexture");
  2828. m_extensions = String::join(" ", extensions);
  2829. }
  2830. void GLContext::gl_lightf(GLenum light, GLenum pname, GLfloat param)
  2831. {
  2832. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_lightf, light, pname, param);
  2833. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2834. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light >= (GL_LIGHT0 + m_device_info.num_lights), GL_INVALID_ENUM);
  2835. RETURN_WITH_ERROR_IF(!(pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION || pname != GL_SPOT_EXPONENT || pname != GL_SPOT_CUTOFF), GL_INVALID_ENUM);
  2836. RETURN_WITH_ERROR_IF(param < 0.f, GL_INVALID_VALUE);
  2837. auto& light_state = m_light_states.at(light - GL_LIGHT0);
  2838. switch (pname) {
  2839. case GL_CONSTANT_ATTENUATION:
  2840. light_state.constant_attenuation = param;
  2841. break;
  2842. case GL_LINEAR_ATTENUATION:
  2843. light_state.linear_attenuation = param;
  2844. break;
  2845. case GL_QUADRATIC_ATTENUATION:
  2846. light_state.quadratic_attenuation = param;
  2847. break;
  2848. case GL_SPOT_EXPONENT:
  2849. RETURN_WITH_ERROR_IF(param > 128.f, GL_INVALID_VALUE);
  2850. light_state.spotlight_exponent = param;
  2851. break;
  2852. case GL_SPOT_CUTOFF:
  2853. RETURN_WITH_ERROR_IF(param > 90.f && param != 180.f, GL_INVALID_VALUE);
  2854. light_state.spotlight_cutoff_angle = param;
  2855. break;
  2856. default:
  2857. VERIFY_NOT_REACHED();
  2858. }
  2859. m_light_state_is_dirty = true;
  2860. }
  2861. void GLContext::gl_lightfv(GLenum light, GLenum pname, GLfloat const* params)
  2862. {
  2863. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_lightfv, light, pname, params);
  2864. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2865. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light >= (GL_LIGHT0 + m_device_info.num_lights), GL_INVALID_ENUM);
  2866. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_POSITION || pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION || pname == GL_SPOT_CUTOFF || pname == GL_SPOT_EXPONENT || pname == GL_SPOT_DIRECTION), GL_INVALID_ENUM);
  2867. auto& light_state = m_light_states.at(light - GL_LIGHT0);
  2868. switch (pname) {
  2869. case GL_AMBIENT:
  2870. light_state.ambient_intensity = { params[0], params[1], params[2], params[3] };
  2871. break;
  2872. case GL_DIFFUSE:
  2873. light_state.diffuse_intensity = { params[0], params[1], params[2], params[3] };
  2874. break;
  2875. case GL_SPECULAR:
  2876. light_state.specular_intensity = { params[0], params[1], params[2], params[3] };
  2877. break;
  2878. case GL_POSITION:
  2879. light_state.position = { params[0], params[1], params[2], params[3] };
  2880. light_state.position = m_model_view_matrix * light_state.position;
  2881. break;
  2882. case GL_CONSTANT_ATTENUATION:
  2883. RETURN_WITH_ERROR_IF(params[0] < 0.f, GL_INVALID_VALUE);
  2884. light_state.constant_attenuation = params[0];
  2885. break;
  2886. case GL_LINEAR_ATTENUATION:
  2887. RETURN_WITH_ERROR_IF(params[0] < 0.f, GL_INVALID_VALUE);
  2888. light_state.linear_attenuation = params[0];
  2889. break;
  2890. case GL_QUADRATIC_ATTENUATION:
  2891. RETURN_WITH_ERROR_IF(params[0] < 0.f, GL_INVALID_VALUE);
  2892. light_state.quadratic_attenuation = params[0];
  2893. break;
  2894. case GL_SPOT_EXPONENT: {
  2895. auto exponent = params[0];
  2896. RETURN_WITH_ERROR_IF(exponent < 0.f || exponent > 128.f, GL_INVALID_VALUE);
  2897. light_state.spotlight_exponent = exponent;
  2898. break;
  2899. }
  2900. case GL_SPOT_CUTOFF: {
  2901. auto cutoff = params[0];
  2902. RETURN_WITH_ERROR_IF((cutoff < 0.f || cutoff > 90.f) && cutoff != 180.f, GL_INVALID_VALUE);
  2903. light_state.spotlight_cutoff_angle = cutoff;
  2904. break;
  2905. }
  2906. case GL_SPOT_DIRECTION: {
  2907. FloatVector4 direction_vector = { params[0], params[1], params[2], 0.f };
  2908. direction_vector = m_model_view_matrix * direction_vector;
  2909. light_state.spotlight_direction = direction_vector.xyz();
  2910. break;
  2911. }
  2912. default:
  2913. VERIFY_NOT_REACHED();
  2914. }
  2915. m_light_state_is_dirty = true;
  2916. }
  2917. void GLContext::gl_lightiv(GLenum light, GLenum pname, GLint const* params)
  2918. {
  2919. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_lightiv, light, pname, params);
  2920. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  2921. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light >= (GL_LIGHT0 + m_device_info.num_lights), GL_INVALID_ENUM);
  2922. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_POSITION || pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION || pname == GL_SPOT_CUTOFF || pname == GL_SPOT_EXPONENT || pname == GL_SPOT_DIRECTION), GL_INVALID_ENUM);
  2923. auto& light_state = m_light_states[light - GL_LIGHT0];
  2924. auto const to_float_vector = [](GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
  2925. return FloatVector4(x, y, z, w);
  2926. };
  2927. switch (pname) {
  2928. case GL_AMBIENT:
  2929. light_state.ambient_intensity = to_float_vector(params[0], params[1], params[2], params[3]);
  2930. break;
  2931. case GL_DIFFUSE:
  2932. light_state.diffuse_intensity = to_float_vector(params[0], params[1], params[2], params[3]);
  2933. break;
  2934. case GL_SPECULAR:
  2935. light_state.specular_intensity = to_float_vector(params[0], params[1], params[2], params[3]);
  2936. break;
  2937. case GL_POSITION:
  2938. light_state.position = to_float_vector(params[0], params[1], params[2], params[3]);
  2939. light_state.position = m_model_view_matrix * light_state.position;
  2940. break;
  2941. case GL_CONSTANT_ATTENUATION:
  2942. RETURN_WITH_ERROR_IF(params[0] < 0, GL_INVALID_VALUE);
  2943. light_state.constant_attenuation = static_cast<float>(params[0]);
  2944. break;
  2945. case GL_LINEAR_ATTENUATION:
  2946. RETURN_WITH_ERROR_IF(params[0] < 0, GL_INVALID_VALUE);
  2947. light_state.linear_attenuation = static_cast<float>(params[0]);
  2948. break;
  2949. case GL_QUADRATIC_ATTENUATION:
  2950. RETURN_WITH_ERROR_IF(params[0] < 0, GL_INVALID_VALUE);
  2951. light_state.quadratic_attenuation = static_cast<float>(params[0]);
  2952. break;
  2953. case GL_SPOT_EXPONENT: {
  2954. auto exponent = static_cast<float>(params[0]);
  2955. RETURN_WITH_ERROR_IF(exponent < 0.f || exponent > 128.f, GL_INVALID_VALUE);
  2956. light_state.spotlight_exponent = exponent;
  2957. break;
  2958. }
  2959. case GL_SPOT_CUTOFF: {
  2960. auto cutoff = static_cast<float>(params[0]);
  2961. RETURN_WITH_ERROR_IF((cutoff < 0.f || cutoff > 90.f) && cutoff != 180.f, GL_INVALID_VALUE);
  2962. light_state.spotlight_cutoff_angle = cutoff;
  2963. break;
  2964. }
  2965. case GL_SPOT_DIRECTION: {
  2966. auto direction_vector = to_float_vector(params[0], params[1], params[2], 0.0f);
  2967. direction_vector = m_model_view_matrix * direction_vector;
  2968. light_state.spotlight_direction = direction_vector.xyz();
  2969. break;
  2970. }
  2971. default:
  2972. VERIFY_NOT_REACHED();
  2973. }
  2974. m_light_state_is_dirty = true;
  2975. }
  2976. void GLContext::gl_materialf(GLenum face, GLenum pname, GLfloat param)
  2977. {
  2978. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_materialf, face, pname, param);
  2979. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  2980. RETURN_WITH_ERROR_IF(pname != GL_SHININESS, GL_INVALID_ENUM);
  2981. RETURN_WITH_ERROR_IF(param > 128.0f, GL_INVALID_VALUE);
  2982. switch (face) {
  2983. case GL_FRONT:
  2984. m_material_states[Face::Front].shininess = param;
  2985. break;
  2986. case GL_BACK:
  2987. m_material_states[Face::Back].shininess = param;
  2988. break;
  2989. case GL_FRONT_AND_BACK:
  2990. m_material_states[Face::Front].shininess = param;
  2991. m_material_states[Face::Back].shininess = param;
  2992. break;
  2993. default:
  2994. VERIFY_NOT_REACHED();
  2995. }
  2996. m_light_state_is_dirty = true;
  2997. }
  2998. void GLContext::gl_materialfv(GLenum face, GLenum pname, GLfloat const* params)
  2999. {
  3000. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_materialfv, face, pname, params);
  3001. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  3002. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_EMISSION || pname == GL_SHININESS || pname == GL_AMBIENT_AND_DIFFUSE), GL_INVALID_ENUM);
  3003. RETURN_WITH_ERROR_IF((pname == GL_SHININESS && *params > 128.0f), GL_INVALID_VALUE);
  3004. auto update_material = [](GPU::Material& material, GLenum pname, GLfloat const* params) {
  3005. switch (pname) {
  3006. case GL_AMBIENT:
  3007. material.ambient = { params[0], params[1], params[2], params[3] };
  3008. break;
  3009. case GL_DIFFUSE:
  3010. material.diffuse = { params[0], params[1], params[2], params[3] };
  3011. break;
  3012. case GL_SPECULAR:
  3013. material.specular = { params[0], params[1], params[2], params[3] };
  3014. break;
  3015. case GL_EMISSION:
  3016. material.emissive = { params[0], params[1], params[2], params[3] };
  3017. break;
  3018. case GL_SHININESS:
  3019. material.shininess = *params;
  3020. break;
  3021. case GL_AMBIENT_AND_DIFFUSE:
  3022. material.ambient = { params[0], params[1], params[2], params[3] };
  3023. material.diffuse = { params[0], params[1], params[2], params[3] };
  3024. break;
  3025. }
  3026. };
  3027. switch (face) {
  3028. case GL_FRONT:
  3029. update_material(m_material_states[Face::Front], pname, params);
  3030. break;
  3031. case GL_BACK:
  3032. update_material(m_material_states[Face::Back], pname, params);
  3033. break;
  3034. case GL_FRONT_AND_BACK:
  3035. update_material(m_material_states[Face::Front], pname, params);
  3036. update_material(m_material_states[Face::Back], pname, params);
  3037. break;
  3038. }
  3039. m_light_state_is_dirty = true;
  3040. }
  3041. void GLContext::gl_materialiv(GLenum face, GLenum pname, GLint const* params)
  3042. {
  3043. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_materialiv, face, pname, params);
  3044. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK || face == GL_FRONT_AND_BACK), GL_INVALID_ENUM);
  3045. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_EMISSION || pname == GL_SHININESS || pname == GL_AMBIENT_AND_DIFFUSE), GL_INVALID_ENUM);
  3046. RETURN_WITH_ERROR_IF((pname == GL_SHININESS && *params > 128), GL_INVALID_VALUE);
  3047. auto update_material = [](GPU::Material& material, GLenum pname, GLint const* params) {
  3048. switch (pname) {
  3049. case GL_AMBIENT:
  3050. material.ambient = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3051. break;
  3052. case GL_DIFFUSE:
  3053. material.diffuse = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3054. break;
  3055. case GL_SPECULAR:
  3056. material.specular = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3057. break;
  3058. case GL_EMISSION:
  3059. material.emissive = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3060. break;
  3061. case GL_SHININESS:
  3062. material.shininess = static_cast<float>(params[0]);
  3063. break;
  3064. case GL_AMBIENT_AND_DIFFUSE:
  3065. material.ambient = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3066. material.diffuse = { static_cast<float>(params[0]), static_cast<float>(params[1]), static_cast<float>(params[2]), static_cast<float>(params[3]) };
  3067. break;
  3068. }
  3069. };
  3070. switch (face) {
  3071. case GL_FRONT:
  3072. update_material(m_material_states[Face::Front], pname, params);
  3073. break;
  3074. case GL_BACK:
  3075. update_material(m_material_states[Face::Back], pname, params);
  3076. break;
  3077. case GL_FRONT_AND_BACK:
  3078. update_material(m_material_states[Face::Front], pname, params);
  3079. update_material(m_material_states[Face::Back], pname, params);
  3080. break;
  3081. }
  3082. m_light_state_is_dirty = true;
  3083. }
  3084. void GLContext::gl_color_material(GLenum face, GLenum mode)
  3085. {
  3086. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_color_material, face, mode);
  3087. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  3088. RETURN_WITH_ERROR_IF(face != GL_FRONT
  3089. && face != GL_BACK
  3090. && face != GL_FRONT_AND_BACK,
  3091. GL_INVALID_ENUM);
  3092. RETURN_WITH_ERROR_IF(mode != GL_EMISSION
  3093. && mode != GL_AMBIENT
  3094. && mode != GL_DIFFUSE
  3095. && mode != GL_SPECULAR
  3096. && mode != GL_AMBIENT_AND_DIFFUSE,
  3097. GL_INVALID_ENUM);
  3098. m_color_material_face = face;
  3099. m_color_material_mode = mode;
  3100. m_light_state_is_dirty = true;
  3101. }
  3102. void GLContext::gl_get_light(GLenum light, GLenum pname, void* params, GLenum type)
  3103. {
  3104. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_get_light, light, pname, params, type);
  3105. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  3106. RETURN_WITH_ERROR_IF(light < GL_LIGHT0 || light > GL_LIGHT0 + m_device_info.num_lights, GL_INVALID_ENUM);
  3107. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_SPOT_DIRECTION || pname == GL_SPOT_EXPONENT || pname == GL_SPOT_CUTOFF || pname == GL_CONSTANT_ATTENUATION || pname == GL_LINEAR_ATTENUATION || pname == GL_QUADRATIC_ATTENUATION), GL_INVALID_ENUM);
  3108. if (type == GL_FLOAT)
  3109. get_light_param<GLfloat>(light, pname, static_cast<GLfloat*>(params));
  3110. else if (type == GL_INT)
  3111. get_light_param<GLint>(light, pname, static_cast<GLint*>(params));
  3112. else
  3113. VERIFY_NOT_REACHED();
  3114. }
  3115. template<typename T>
  3116. void GLContext::get_light_param(GLenum light, GLenum pname, T* params)
  3117. {
  3118. auto const& light_state = m_light_states[light - GL_LIGHT0];
  3119. switch (pname) {
  3120. case GL_AMBIENT:
  3121. params[0] = light_state.ambient_intensity.x();
  3122. params[1] = light_state.ambient_intensity.y();
  3123. params[2] = light_state.ambient_intensity.z();
  3124. params[3] = light_state.ambient_intensity.w();
  3125. break;
  3126. case GL_DIFFUSE:
  3127. params[0] = light_state.diffuse_intensity.x();
  3128. params[1] = light_state.diffuse_intensity.y();
  3129. params[2] = light_state.diffuse_intensity.z();
  3130. params[3] = light_state.diffuse_intensity.w();
  3131. break;
  3132. case GL_SPECULAR:
  3133. params[0] = light_state.specular_intensity.x();
  3134. params[1] = light_state.specular_intensity.y();
  3135. params[2] = light_state.specular_intensity.z();
  3136. params[3] = light_state.specular_intensity.w();
  3137. break;
  3138. case GL_SPOT_DIRECTION:
  3139. params[0] = light_state.spotlight_direction.x();
  3140. params[1] = light_state.spotlight_direction.y();
  3141. params[2] = light_state.spotlight_direction.z();
  3142. break;
  3143. case GL_SPOT_EXPONENT:
  3144. *params = light_state.spotlight_exponent;
  3145. break;
  3146. case GL_SPOT_CUTOFF:
  3147. *params = light_state.spotlight_cutoff_angle;
  3148. break;
  3149. case GL_CONSTANT_ATTENUATION:
  3150. *params = light_state.constant_attenuation;
  3151. break;
  3152. case GL_LINEAR_ATTENUATION:
  3153. *params = light_state.linear_attenuation;
  3154. break;
  3155. case GL_QUADRATIC_ATTENUATION:
  3156. *params = light_state.quadratic_attenuation;
  3157. break;
  3158. }
  3159. }
  3160. void GLContext::gl_get_material(GLenum face, GLenum pname, void* params, GLenum type)
  3161. {
  3162. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_get_material, face, pname, params, type);
  3163. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  3164. RETURN_WITH_ERROR_IF(!(pname == GL_AMBIENT || pname == GL_DIFFUSE || pname == GL_SPECULAR || pname == GL_EMISSION), GL_INVALID_ENUM);
  3165. RETURN_WITH_ERROR_IF(!(face == GL_FRONT || face == GL_BACK), GL_INVALID_ENUM);
  3166. Face material_face = Front;
  3167. switch (face) {
  3168. case GL_FRONT:
  3169. material_face = Front;
  3170. break;
  3171. case GL_BACK:
  3172. material_face = Back;
  3173. break;
  3174. }
  3175. if (type == GL_FLOAT)
  3176. get_material_param<GLfloat>(material_face, pname, static_cast<GLfloat*>(params));
  3177. else if (type == GL_INT)
  3178. get_material_param<GLint>(material_face, pname, static_cast<GLint*>(params));
  3179. else
  3180. VERIFY_NOT_REACHED();
  3181. }
  3182. template<typename T>
  3183. void GLContext::get_material_param(Face face, GLenum pname, T* params)
  3184. {
  3185. auto const& material = m_material_states[face];
  3186. switch (pname) {
  3187. case GL_AMBIENT:
  3188. params[0] = static_cast<T>(material.ambient.x());
  3189. params[1] = static_cast<T>(material.ambient.y());
  3190. params[2] = static_cast<T>(material.ambient.z());
  3191. params[3] = static_cast<T>(material.ambient.w());
  3192. break;
  3193. case GL_DIFFUSE:
  3194. params[0] = static_cast<T>(material.diffuse.x());
  3195. params[1] = static_cast<T>(material.diffuse.y());
  3196. params[2] = static_cast<T>(material.diffuse.z());
  3197. params[3] = static_cast<T>(material.diffuse.w());
  3198. break;
  3199. case GL_SPECULAR:
  3200. params[0] = static_cast<T>(material.specular.x());
  3201. params[1] = static_cast<T>(material.specular.y());
  3202. params[2] = static_cast<T>(material.specular.z());
  3203. params[3] = static_cast<T>(material.specular.w());
  3204. break;
  3205. case GL_EMISSION:
  3206. params[0] = static_cast<T>(material.emissive.x());
  3207. params[1] = static_cast<T>(material.emissive.y());
  3208. params[2] = static_cast<T>(material.emissive.z());
  3209. params[3] = static_cast<T>(material.emissive.w());
  3210. break;
  3211. case GL_SHININESS:
  3212. *params = material.shininess;
  3213. break;
  3214. }
  3215. }
  3216. void GLContext::gl_copy_tex_sub_image_2d(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
  3217. {
  3218. APPEND_TO_CALL_LIST_AND_RETURN_IF_NEEDED(gl_copy_tex_sub_image_2d, target, level, xoffset, yoffset, x, y, width, height);
  3219. RETURN_WITH_ERROR_IF(!(target == GL_TEXTURE_2D || target == GL_TEXTURE_1D_ARRAY), GL_INVALID_ENUM);
  3220. RETURN_WITH_ERROR_IF(level < 0, GL_INVALID_VALUE);
  3221. RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION);
  3222. // FIXME: implement
  3223. dbgln_if(GL_DEBUG, "GLContext FIXME: implement gl_copy_tex_sub_image_2d({:#x}, {}, {}, {}, {}, {}, {}, {})",
  3224. target, level, xoffset, yoffset, x, y, width, height);
  3225. }
  3226. NonnullOwnPtr<GLContext> create_context(Gfx::Bitmap& bitmap)
  3227. {
  3228. // FIXME: Make driver selectable. This is currently hardcoded to LibSoftGPU
  3229. auto driver = MUST(GPU::Driver::try_create("softgpu"));
  3230. auto device = MUST(driver->try_create_device(bitmap.size()));
  3231. auto context = make<GLContext>(driver, move(device), bitmap);
  3232. dbgln_if(GL_DEBUG, "GL::create_context({}) -> {:p}", bitmap.size(), context.ptr());
  3233. if (!g_gl_context)
  3234. make_context_current(context);
  3235. return context;
  3236. }
  3237. void make_context_current(GLContext* context)
  3238. {
  3239. if (g_gl_context == context)
  3240. return;
  3241. dbgln_if(GL_DEBUG, "GL::make_context_current({:p})", context);
  3242. g_gl_context = context;
  3243. }
  3244. void present_context(GLContext* context)
  3245. {
  3246. context->present();
  3247. }
  3248. }