rasterizer_canvas_gles3.cpp 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840
  1. /**************************************************************************/
  2. /* rasterizer_canvas_gles3.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "rasterizer_canvas_gles3.h"
  31. #ifdef GLES3_ENABLED
  32. #include "core/os/os.h"
  33. #include "rasterizer_gles3.h"
  34. #include "rasterizer_scene_gles3.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/math/geometry_2d.h"
  37. #include "servers/rendering/rendering_server_default.h"
  38. #include "storage/config.h"
  39. #include "storage/material_storage.h"
  40. #include "storage/mesh_storage.h"
  41. #include "storage/particles_storage.h"
  42. #include "storage/texture_storage.h"
  43. void RasterizerCanvasGLES3::_update_transform_2d_to_mat4(const Transform2D &p_transform, float *p_mat4) {
  44. p_mat4[0] = p_transform.columns[0][0];
  45. p_mat4[1] = p_transform.columns[0][1];
  46. p_mat4[2] = 0;
  47. p_mat4[3] = 0;
  48. p_mat4[4] = p_transform.columns[1][0];
  49. p_mat4[5] = p_transform.columns[1][1];
  50. p_mat4[6] = 0;
  51. p_mat4[7] = 0;
  52. p_mat4[8] = 0;
  53. p_mat4[9] = 0;
  54. p_mat4[10] = 1;
  55. p_mat4[11] = 0;
  56. p_mat4[12] = p_transform.columns[2][0];
  57. p_mat4[13] = p_transform.columns[2][1];
  58. p_mat4[14] = 0;
  59. p_mat4[15] = 1;
  60. }
  61. void RasterizerCanvasGLES3::_update_transform_2d_to_mat2x4(const Transform2D &p_transform, float *p_mat2x4) {
  62. p_mat2x4[0] = p_transform.columns[0][0];
  63. p_mat2x4[1] = p_transform.columns[1][0];
  64. p_mat2x4[2] = 0;
  65. p_mat2x4[3] = p_transform.columns[2][0];
  66. p_mat2x4[4] = p_transform.columns[0][1];
  67. p_mat2x4[5] = p_transform.columns[1][1];
  68. p_mat2x4[6] = 0;
  69. p_mat2x4[7] = p_transform.columns[2][1];
  70. }
  71. void RasterizerCanvasGLES3::_update_transform_2d_to_mat2x3(const Transform2D &p_transform, float *p_mat2x3) {
  72. p_mat2x3[0] = p_transform.columns[0][0];
  73. p_mat2x3[1] = p_transform.columns[0][1];
  74. p_mat2x3[2] = p_transform.columns[1][0];
  75. p_mat2x3[3] = p_transform.columns[1][1];
  76. p_mat2x3[4] = p_transform.columns[2][0];
  77. p_mat2x3[5] = p_transform.columns[2][1];
  78. }
  79. void RasterizerCanvasGLES3::_update_transform_to_mat4(const Transform3D &p_transform, float *p_mat4) {
  80. p_mat4[0] = p_transform.basis.rows[0][0];
  81. p_mat4[1] = p_transform.basis.rows[1][0];
  82. p_mat4[2] = p_transform.basis.rows[2][0];
  83. p_mat4[3] = 0;
  84. p_mat4[4] = p_transform.basis.rows[0][1];
  85. p_mat4[5] = p_transform.basis.rows[1][1];
  86. p_mat4[6] = p_transform.basis.rows[2][1];
  87. p_mat4[7] = 0;
  88. p_mat4[8] = p_transform.basis.rows[0][2];
  89. p_mat4[9] = p_transform.basis.rows[1][2];
  90. p_mat4[10] = p_transform.basis.rows[2][2];
  91. p_mat4[11] = 0;
  92. p_mat4[12] = p_transform.origin.x;
  93. p_mat4[13] = p_transform.origin.y;
  94. p_mat4[14] = p_transform.origin.z;
  95. p_mat4[15] = 1;
  96. }
  97. void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_light_list, const Transform2D &p_canvas_transform, RS::CanvasItemTextureFilter p_default_filter, RS::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used) {
  98. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  99. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  100. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  101. Transform2D canvas_transform_inverse = p_canvas_transform.affine_inverse();
  102. // Clear out any state that may have been left from the 3D pass.
  103. reset_canvas();
  104. if (state.canvas_instance_data_buffers[state.current_data_buffer_index].fence != GLsync()) {
  105. GLint syncStatus;
  106. glGetSynciv(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence, GL_SYNC_STATUS, 1, nullptr, &syncStatus);
  107. if (syncStatus == GL_UNSIGNALED) {
  108. // If older than 2 frames, wait for sync OpenGL can have up to 3 frames in flight, any more and we need to sync anyway.
  109. if (state.canvas_instance_data_buffers[state.current_data_buffer_index].last_frame_used < RSG::rasterizer->get_frame_number() - 2) {
  110. #ifndef WEB_ENABLED
  111. // On web, we do nothing as the glSubBufferData will force a sync anyway and WebGL does not like waiting.
  112. glClientWaitSync(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence, 0, 100000000); // wait for up to 100ms
  113. #endif
  114. state.canvas_instance_data_buffers[state.current_data_buffer_index].last_frame_used = RSG::rasterizer->get_frame_number();
  115. glDeleteSync(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence);
  116. state.canvas_instance_data_buffers[state.current_data_buffer_index].fence = GLsync();
  117. } else {
  118. // Used in last frame or frame before that. OpenGL can get up to two frames behind, so these buffers may still be in use
  119. // Allocate a new buffer and use that.
  120. _allocate_instance_data_buffer();
  121. }
  122. } else {
  123. // Already finished all rendering commands, we can use it.
  124. state.canvas_instance_data_buffers[state.current_data_buffer_index].last_frame_used = RSG::rasterizer->get_frame_number();
  125. glDeleteSync(state.canvas_instance_data_buffers[state.current_data_buffer_index].fence);
  126. state.canvas_instance_data_buffers[state.current_data_buffer_index].fence = GLsync();
  127. }
  128. }
  129. //setup directional lights if exist
  130. uint32_t light_count = 0;
  131. uint32_t directional_light_count = 0;
  132. {
  133. Light *l = p_directional_light_list;
  134. uint32_t index = 0;
  135. while (l) {
  136. if (index == data.max_lights_per_render) {
  137. l->render_index_cache = -1;
  138. l = l->next_ptr;
  139. continue;
  140. }
  141. CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
  142. if (!clight) { //unused or invalid texture
  143. l->render_index_cache = -1;
  144. l = l->next_ptr;
  145. ERR_CONTINUE(!clight);
  146. }
  147. Vector2 canvas_light_dir = l->xform_cache.columns[1].normalized();
  148. state.light_uniforms[index].position[0] = -canvas_light_dir.x;
  149. state.light_uniforms[index].position[1] = -canvas_light_dir.y;
  150. _update_transform_2d_to_mat2x4(clight->shadow.directional_xform, state.light_uniforms[index].shadow_matrix);
  151. state.light_uniforms[index].height = l->height; //0..1 here
  152. for (int i = 0; i < 4; i++) {
  153. state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
  154. state.light_uniforms[index].color[i] = l->color[i];
  155. }
  156. state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate
  157. if (state.shadow_fb != 0) {
  158. state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
  159. state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
  160. state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
  161. } else {
  162. state.light_uniforms[index].shadow_pixel_size = 1.0;
  163. state.light_uniforms[index].shadow_z_far_inv = 1.0;
  164. state.light_uniforms[index].shadow_y_ofs = 0;
  165. }
  166. state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
  167. state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
  168. if (clight->shadow.enabled) {
  169. state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
  170. }
  171. l->render_index_cache = index;
  172. index++;
  173. l = l->next_ptr;
  174. }
  175. light_count = index;
  176. directional_light_count = light_count;
  177. state.using_directional_lights = directional_light_count > 0;
  178. }
  179. //setup lights if exist
  180. {
  181. Light *l = p_light_list;
  182. uint32_t index = light_count;
  183. while (l) {
  184. if (index == data.max_lights_per_render) {
  185. l->render_index_cache = -1;
  186. l = l->next_ptr;
  187. continue;
  188. }
  189. CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
  190. if (!clight) { //unused or invalid texture
  191. l->render_index_cache = -1;
  192. l = l->next_ptr;
  193. ERR_CONTINUE(!clight);
  194. }
  195. Vector2 canvas_light_pos = p_canvas_transform.xform(l->xform.get_origin()); //convert light position to canvas coordinates, as all computation is done in canvas coords to avoid precision loss
  196. state.light_uniforms[index].position[0] = canvas_light_pos.x;
  197. state.light_uniforms[index].position[1] = canvas_light_pos.y;
  198. _update_transform_2d_to_mat2x4(l->light_shader_xform.affine_inverse(), state.light_uniforms[index].matrix);
  199. _update_transform_2d_to_mat2x4(l->xform_cache.affine_inverse(), state.light_uniforms[index].shadow_matrix);
  200. state.light_uniforms[index].height = l->height * (p_canvas_transform.columns[0].length() + p_canvas_transform.columns[1].length()) * 0.5; //approximate height conversion to the canvas size, since all calculations are done in canvas coords to avoid precision loss
  201. for (int i = 0; i < 4; i++) {
  202. state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
  203. state.light_uniforms[index].color[i] = l->color[i];
  204. }
  205. state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate
  206. if (state.shadow_fb != 0) {
  207. state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
  208. state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
  209. state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
  210. } else {
  211. state.light_uniforms[index].shadow_pixel_size = 1.0;
  212. state.light_uniforms[index].shadow_z_far_inv = 1.0;
  213. state.light_uniforms[index].shadow_y_ofs = 0;
  214. }
  215. state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
  216. state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
  217. if (clight->shadow.enabled) {
  218. state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
  219. }
  220. if (clight->texture.is_valid()) {
  221. Rect2 atlas_rect = GLES3::TextureStorage::get_singleton()->texture_atlas_get_texture_rect(clight->texture);
  222. state.light_uniforms[index].atlas_rect[0] = atlas_rect.position.x;
  223. state.light_uniforms[index].atlas_rect[1] = atlas_rect.position.y;
  224. state.light_uniforms[index].atlas_rect[2] = atlas_rect.size.width;
  225. state.light_uniforms[index].atlas_rect[3] = atlas_rect.size.height;
  226. } else {
  227. state.light_uniforms[index].atlas_rect[0] = 0;
  228. state.light_uniforms[index].atlas_rect[1] = 0;
  229. state.light_uniforms[index].atlas_rect[2] = 0;
  230. state.light_uniforms[index].atlas_rect[3] = 0;
  231. }
  232. l->render_index_cache = index;
  233. index++;
  234. l = l->next_ptr;
  235. }
  236. light_count = index;
  237. }
  238. if (light_count > 0) {
  239. glBindBufferBase(GL_UNIFORM_BUFFER, LIGHT_UNIFORM_LOCATION, state.canvas_instance_data_buffers[state.current_data_buffer_index].light_ubo);
  240. #ifdef WEB_ENABLED
  241. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightUniform) * light_count, state.light_uniforms);
  242. #else
  243. // On Desktop and mobile we map the memory without synchronizing for maximum speed.
  244. void *ubo = glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(LightUniform) * light_count, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
  245. memcpy(ubo, state.light_uniforms, sizeof(LightUniform) * light_count);
  246. glUnmapBuffer(GL_UNIFORM_BUFFER);
  247. #endif
  248. GLuint texture_atlas = texture_storage->texture_atlas_get_texture();
  249. if (texture_atlas == 0) {
  250. GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
  251. texture_atlas = tex->tex_id;
  252. }
  253. glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 2);
  254. glBindTexture(GL_TEXTURE_2D, texture_atlas);
  255. GLuint shadow_tex = state.shadow_texture;
  256. if (shadow_tex == 0) {
  257. GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
  258. shadow_tex = tex->tex_id;
  259. }
  260. glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 3);
  261. glBindTexture(GL_TEXTURE_2D, shadow_tex);
  262. }
  263. {
  264. //update canvas state uniform buffer
  265. StateBuffer state_buffer;
  266. Size2i ssize = texture_storage->render_target_get_size(p_to_render_target);
  267. // If we've overridden the render target's color texture, then we need
  268. // to invert the Y axis, so 2D texture appear right side up.
  269. // We're probably rendering directly to an XR device.
  270. float y_scale = texture_storage->render_target_get_override_color(p_to_render_target).is_valid() ? -2.0f : 2.0f;
  271. Transform3D screen_transform;
  272. screen_transform.translate_local(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f);
  273. screen_transform.scale(Vector3(2.0f / ssize.width, y_scale / ssize.height, 1.0f));
  274. _update_transform_to_mat4(screen_transform, state_buffer.screen_transform);
  275. _update_transform_2d_to_mat4(p_canvas_transform, state_buffer.canvas_transform);
  276. Transform2D normal_transform = p_canvas_transform;
  277. normal_transform.columns[0].normalize();
  278. normal_transform.columns[1].normalize();
  279. normal_transform.columns[2] = Vector2();
  280. _update_transform_2d_to_mat4(normal_transform, state_buffer.canvas_normal_transform);
  281. state_buffer.canvas_modulate[0] = p_modulate.r;
  282. state_buffer.canvas_modulate[1] = p_modulate.g;
  283. state_buffer.canvas_modulate[2] = p_modulate.b;
  284. state_buffer.canvas_modulate[3] = p_modulate.a;
  285. Size2 render_target_size = texture_storage->render_target_get_size(p_to_render_target);
  286. state_buffer.screen_pixel_size[0] = 1.0 / render_target_size.x;
  287. state_buffer.screen_pixel_size[1] = 1.0 / render_target_size.y;
  288. state_buffer.time = state.time;
  289. state_buffer.use_pixel_snap = p_snap_2d_vertices_to_pixel;
  290. state_buffer.directional_light_count = directional_light_count;
  291. Vector2 canvas_scale = p_canvas_transform.get_scale();
  292. state_buffer.sdf_to_screen[0] = render_target_size.width / canvas_scale.x;
  293. state_buffer.sdf_to_screen[1] = render_target_size.height / canvas_scale.y;
  294. state_buffer.screen_to_sdf[0] = 1.0 / state_buffer.sdf_to_screen[0];
  295. state_buffer.screen_to_sdf[1] = 1.0 / state_buffer.sdf_to_screen[1];
  296. Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_to_render_target);
  297. Rect2 sdf_tex_rect(sdf_rect.position / canvas_scale, sdf_rect.size / canvas_scale);
  298. state_buffer.sdf_to_tex[0] = 1.0 / sdf_tex_rect.size.width;
  299. state_buffer.sdf_to_tex[1] = 1.0 / sdf_tex_rect.size.height;
  300. state_buffer.sdf_to_tex[2] = -sdf_tex_rect.position.x / sdf_tex_rect.size.width;
  301. state_buffer.sdf_to_tex[3] = -sdf_tex_rect.position.y / sdf_tex_rect.size.height;
  302. state_buffer.tex_to_sdf = 1.0 / ((canvas_scale.x + canvas_scale.y) * 0.5);
  303. glBindBufferBase(GL_UNIFORM_BUFFER, BASE_UNIFORM_LOCATION, state.canvas_instance_data_buffers[state.current_data_buffer_index].state_ubo);
  304. glBufferData(GL_UNIFORM_BUFFER, sizeof(StateBuffer), &state_buffer, GL_STREAM_DRAW);
  305. GLuint global_buffer = material_storage->global_shader_parameters_get_uniform_buffer();
  306. glBindBufferBase(GL_UNIFORM_BUFFER, GLOBAL_UNIFORM_LOCATION, global_buffer);
  307. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  308. }
  309. glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 5);
  310. glBindTexture(GL_TEXTURE_2D, texture_storage->render_target_get_sdf_texture(p_to_render_target));
  311. {
  312. state.default_filter = p_default_filter;
  313. state.default_repeat = p_default_repeat;
  314. }
  315. Size2 render_target_size = texture_storage->render_target_get_size(p_to_render_target);
  316. glViewport(0, 0, render_target_size.x, render_target_size.y);
  317. r_sdf_used = false;
  318. int item_count = 0;
  319. bool backbuffer_cleared = false;
  320. bool time_used = false;
  321. bool material_screen_texture_cached = false;
  322. bool material_screen_texture_mipmaps_cached = false;
  323. Rect2 back_buffer_rect;
  324. bool backbuffer_copy = false;
  325. bool backbuffer_gen_mipmaps = false;
  326. bool update_skeletons = false;
  327. Item *ci = p_item_list;
  328. Item *canvas_group_owner = nullptr;
  329. bool skip_item = false;
  330. state.last_item_index = 0;
  331. while (ci) {
  332. if (ci->copy_back_buffer && canvas_group_owner == nullptr) {
  333. backbuffer_copy = true;
  334. if (ci->copy_back_buffer->full) {
  335. back_buffer_rect = Rect2();
  336. } else {
  337. back_buffer_rect = ci->copy_back_buffer->rect;
  338. }
  339. }
  340. // Check material for something that may change flow of rendering, but do not bind for now.
  341. RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
  342. if (material.is_valid()) {
  343. GLES3::CanvasMaterialData *md = static_cast<GLES3::CanvasMaterialData *>(material_storage->material_get_data(material, RS::SHADER_CANVAS_ITEM));
  344. if (md && md->shader_data->valid) {
  345. if (md->shader_data->uses_screen_texture && canvas_group_owner == nullptr) {
  346. if (!material_screen_texture_cached) {
  347. backbuffer_copy = true;
  348. back_buffer_rect = Rect2();
  349. backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
  350. } else if (!material_screen_texture_mipmaps_cached) {
  351. backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
  352. }
  353. }
  354. if (md->shader_data->uses_sdf) {
  355. r_sdf_used = true;
  356. }
  357. if (md->shader_data->uses_time) {
  358. time_used = true;
  359. }
  360. }
  361. }
  362. if (ci->skeleton.is_valid()) {
  363. const Item::Command *c = ci->commands;
  364. while (c) {
  365. if (c->type == Item::Command::TYPE_MESH) {
  366. const Item::CommandMesh *cm = static_cast<const Item::CommandMesh *>(c);
  367. if (cm->mesh_instance.is_valid()) {
  368. mesh_storage->mesh_instance_check_for_update(cm->mesh_instance);
  369. mesh_storage->mesh_instance_set_canvas_item_transform(cm->mesh_instance, canvas_transform_inverse * ci->final_transform);
  370. update_skeletons = true;
  371. }
  372. }
  373. c = c->next;
  374. }
  375. }
  376. if (ci->canvas_group_owner != nullptr) {
  377. if (canvas_group_owner == nullptr) {
  378. if (update_skeletons) {
  379. mesh_storage->update_mesh_instances();
  380. update_skeletons = false;
  381. }
  382. // Canvas group begins here, render until before this item
  383. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used);
  384. item_count = 0;
  385. if (ci->canvas_group_owner->canvas_group->mode != RS::CANVAS_GROUP_MODE_TRANSPARENT) {
  386. Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
  387. texture_storage->render_target_copy_to_back_buffer(p_to_render_target, group_rect, false);
  388. if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
  389. ci->canvas_group_owner->use_canvas_group = false;
  390. items[item_count++] = ci->canvas_group_owner;
  391. }
  392. } else if (!backbuffer_cleared) {
  393. texture_storage->render_target_clear_back_buffer(p_to_render_target, Rect2i(), Color(0, 0, 0, 0));
  394. backbuffer_cleared = true;
  395. }
  396. backbuffer_copy = false;
  397. canvas_group_owner = ci->canvas_group_owner; //continue until owner found
  398. }
  399. ci->canvas_group_owner = nullptr; //must be cleared
  400. }
  401. if (canvas_group_owner == nullptr && ci->canvas_group != nullptr && ci->canvas_group->mode != RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
  402. skip_item = true;
  403. }
  404. if (ci == canvas_group_owner) {
  405. if (update_skeletons) {
  406. mesh_storage->update_mesh_instances();
  407. update_skeletons = false;
  408. }
  409. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, true);
  410. item_count = 0;
  411. if (ci->canvas_group->blur_mipmaps) {
  412. texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, ci->global_rect_cache);
  413. }
  414. canvas_group_owner = nullptr;
  415. // Backbuffer is dirty now and needs to be re-cleared if another CanvasGroup needs it.
  416. backbuffer_cleared = false;
  417. // Tell the renderer to paint this as a canvas group
  418. ci->use_canvas_group = true;
  419. } else {
  420. ci->use_canvas_group = false;
  421. }
  422. if (backbuffer_copy) {
  423. if (update_skeletons) {
  424. mesh_storage->update_mesh_instances();
  425. update_skeletons = false;
  426. }
  427. //render anything pending, including clearing if no items
  428. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used);
  429. item_count = 0;
  430. texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, backbuffer_gen_mipmaps);
  431. backbuffer_copy = false;
  432. material_screen_texture_cached = true; // After a backbuffer copy, screen texture makes no further copies.
  433. material_screen_texture_mipmaps_cached = backbuffer_gen_mipmaps;
  434. backbuffer_gen_mipmaps = false;
  435. }
  436. if (backbuffer_gen_mipmaps) {
  437. texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, back_buffer_rect);
  438. backbuffer_gen_mipmaps = false;
  439. material_screen_texture_mipmaps_cached = true;
  440. }
  441. // just add all items for now
  442. if (skip_item) {
  443. skip_item = false;
  444. } else {
  445. items[item_count++] = ci;
  446. }
  447. if (!ci->next || item_count == MAX_RENDER_ITEMS - 1) {
  448. if (update_skeletons) {
  449. mesh_storage->update_mesh_instances();
  450. update_skeletons = false;
  451. }
  452. _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, canvas_group_owner != nullptr);
  453. //then reset
  454. item_count = 0;
  455. }
  456. ci = ci->next;
  457. }
  458. if (time_used) {
  459. RenderingServerDefault::redraw_request();
  460. }
  461. state.canvas_instance_data_buffers[state.current_data_buffer_index].fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  462. // Clear out state used in 2D pass
  463. reset_canvas();
  464. state.current_data_buffer_index = (state.current_data_buffer_index + 1) % state.canvas_instance_data_buffers.size();
  465. state.current_instance_buffer_index = 0;
  466. }
  467. void RasterizerCanvasGLES3::_render_items(RID p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, bool &r_sdf_used, bool p_to_backbuffer) {
  468. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  469. canvas_begin(p_to_render_target, p_to_backbuffer);
  470. if (p_item_count <= 0) {
  471. // Nothing to draw, just call canvas_begin() to clear the render target and return.
  472. return;
  473. }
  474. uint32_t index = 0;
  475. Item *current_clip = nullptr;
  476. GLES3::CanvasShaderData *shader_data_cache = nullptr;
  477. // Record Batches.
  478. // First item always forms its own batch.
  479. bool batch_broken = false;
  480. _new_batch(batch_broken);
  481. // Override the start position and index as we want to start from where we finished off last time.
  482. state.canvas_instance_batches[state.current_batch_index].start = state.last_item_index;
  483. index = 0;
  484. for (int i = 0; i < p_item_count; i++) {
  485. Item *ci = items[i];
  486. if (ci->final_clip_owner != state.canvas_instance_batches[state.current_batch_index].clip) {
  487. _new_batch(batch_broken);
  488. state.canvas_instance_batches[state.current_batch_index].clip = ci->final_clip_owner;
  489. current_clip = ci->final_clip_owner;
  490. }
  491. RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
  492. if (ci->use_canvas_group) {
  493. if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
  494. material = default_clip_children_material;
  495. } else {
  496. if (material.is_null()) {
  497. if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_ONLY) {
  498. material = default_clip_children_material;
  499. } else {
  500. material = default_canvas_group_material;
  501. }
  502. }
  503. }
  504. }
  505. if (material != state.canvas_instance_batches[state.current_batch_index].material) {
  506. _new_batch(batch_broken);
  507. GLES3::CanvasMaterialData *material_data = nullptr;
  508. if (material.is_valid()) {
  509. material_data = static_cast<GLES3::CanvasMaterialData *>(material_storage->material_get_data(material, RS::SHADER_CANVAS_ITEM));
  510. }
  511. shader_data_cache = nullptr;
  512. if (material_data) {
  513. if (material_data->shader_data->version.is_valid() && material_data->shader_data->valid) {
  514. shader_data_cache = material_data->shader_data;
  515. }
  516. }
  517. state.canvas_instance_batches[state.current_batch_index].material = material;
  518. state.canvas_instance_batches[state.current_batch_index].material_data = material_data;
  519. }
  520. GLES3::CanvasShaderData::BlendMode blend_mode = shader_data_cache ? shader_data_cache->blend_mode : GLES3::CanvasShaderData::BLEND_MODE_MIX;
  521. _record_item_commands(ci, p_to_render_target, p_canvas_transform_inverse, current_clip, blend_mode, p_lights, index, batch_broken, r_sdf_used);
  522. }
  523. if (index == 0) {
  524. // Nothing to render, just return.
  525. state.current_batch_index = 0;
  526. state.canvas_instance_batches.clear();
  527. return;
  528. }
  529. // Copy over all data needed for rendering.
  530. glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.current_instance_buffer_index]);
  531. #ifdef WEB_ENABLED
  532. glBufferSubData(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), sizeof(InstanceData) * index, state.instance_data_array);
  533. #else
  534. // On Desktop and mobile we map the memory without synchronizing for maximum speed.
  535. void *buffer = glMapBufferRange(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), index * sizeof(InstanceData), GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
  536. memcpy(buffer, state.instance_data_array, index * sizeof(InstanceData));
  537. glUnmapBuffer(GL_ARRAY_BUFFER);
  538. #endif
  539. glDisable(GL_SCISSOR_TEST);
  540. current_clip = nullptr;
  541. GLES3::CanvasShaderData::BlendMode last_blend_mode = GLES3::CanvasShaderData::BLEND_MODE_MIX;
  542. Color last_blend_color;
  543. state.current_tex = RID();
  544. for (uint32_t i = 0; i <= state.current_batch_index; i++) {
  545. // Skipping when there is no instances.
  546. if (state.canvas_instance_batches[i].instance_count == 0) {
  547. continue;
  548. }
  549. //setup clip
  550. if (current_clip != state.canvas_instance_batches[i].clip) {
  551. current_clip = state.canvas_instance_batches[i].clip;
  552. if (current_clip) {
  553. glEnable(GL_SCISSOR_TEST);
  554. glScissor(current_clip->final_clip_rect.position.x, current_clip->final_clip_rect.position.y, current_clip->final_clip_rect.size.x, current_clip->final_clip_rect.size.y);
  555. } else {
  556. glDisable(GL_SCISSOR_TEST);
  557. }
  558. }
  559. GLES3::CanvasMaterialData *material_data = state.canvas_instance_batches[i].material_data;
  560. CanvasShaderGLES3::ShaderVariant variant = state.canvas_instance_batches[i].shader_variant;
  561. uint64_t specialization = 0;
  562. specialization |= uint64_t(state.canvas_instance_batches[i].lights_disabled);
  563. specialization |= uint64_t(!GLES3::Config::get_singleton()->float_texture_supported) << 1;
  564. RID shader_version = data.canvas_shader_default_version;
  565. if (material_data) {
  566. if (material_data->shader_data->version.is_valid() && material_data->shader_data->valid) {
  567. // Bind uniform buffer and textures
  568. material_data->bind_uniforms();
  569. shader_version = material_data->shader_data->version;
  570. }
  571. }
  572. bool success = GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(shader_version, variant, specialization);
  573. if (!success) {
  574. continue;
  575. }
  576. GLES3::CanvasShaderData::BlendMode blend_mode = state.canvas_instance_batches[i].blend_mode;
  577. Color blend_color = state.canvas_instance_batches[i].blend_color;
  578. if (last_blend_mode != blend_mode || last_blend_color != blend_color) {
  579. if (last_blend_mode == GLES3::CanvasShaderData::BLEND_MODE_DISABLED) {
  580. // re-enable it
  581. glEnable(GL_BLEND);
  582. } else if (blend_mode == GLES3::CanvasShaderData::BLEND_MODE_DISABLED) {
  583. // disable it
  584. glDisable(GL_BLEND);
  585. }
  586. switch (blend_mode) {
  587. case GLES3::CanvasShaderData::BLEND_MODE_DISABLED: {
  588. // Nothing to do here.
  589. } break;
  590. case GLES3::CanvasShaderData::BLEND_MODE_LCD: {
  591. glBlendEquation(GL_FUNC_ADD);
  592. if (state.transparent_render_target) {
  593. glBlendFuncSeparate(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  594. } else {
  595. glBlendFuncSeparate(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_ZERO, GL_ONE);
  596. }
  597. glBlendColor(blend_color.r, blend_color.g, blend_color.b, blend_color.a);
  598. } break;
  599. case GLES3::CanvasShaderData::BLEND_MODE_MIX: {
  600. glBlendEquation(GL_FUNC_ADD);
  601. if (state.transparent_render_target) {
  602. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  603. } else {
  604. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  605. }
  606. } break;
  607. case GLES3::CanvasShaderData::BLEND_MODE_ADD: {
  608. glBlendEquation(GL_FUNC_ADD);
  609. if (state.transparent_render_target) {
  610. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE);
  611. } else {
  612. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE);
  613. }
  614. } break;
  615. case GLES3::CanvasShaderData::BLEND_MODE_SUB: {
  616. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  617. if (state.transparent_render_target) {
  618. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE);
  619. } else {
  620. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE);
  621. }
  622. } break;
  623. case GLES3::CanvasShaderData::BLEND_MODE_MUL: {
  624. glBlendEquation(GL_FUNC_ADD);
  625. if (state.transparent_render_target) {
  626. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO);
  627. } else {
  628. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE);
  629. }
  630. } break;
  631. case GLES3::CanvasShaderData::BLEND_MODE_PMALPHA: {
  632. glBlendEquation(GL_FUNC_ADD);
  633. if (state.transparent_render_target) {
  634. glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  635. } else {
  636. glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  637. }
  638. } break;
  639. }
  640. last_blend_mode = blend_mode;
  641. last_blend_color = blend_color;
  642. }
  643. _render_batch(p_lights, i);
  644. }
  645. glDisable(GL_SCISSOR_TEST);
  646. state.current_batch_index = 0;
  647. state.canvas_instance_batches.clear();
  648. state.last_item_index += index;
  649. }
  650. void RasterizerCanvasGLES3::_record_item_commands(const Item *p_item, RID p_render_target, const Transform2D &p_canvas_transform_inverse, Item *&current_clip, GLES3::CanvasShaderData::BlendMode p_blend_mode, Light *p_lights, uint32_t &r_index, bool &r_batch_broken, bool &r_sdf_used) {
  651. RenderingServer::CanvasItemTextureFilter texture_filter = p_item->texture_filter == RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT ? state.default_filter : p_item->texture_filter;
  652. if (texture_filter != state.canvas_instance_batches[state.current_batch_index].filter) {
  653. _new_batch(r_batch_broken);
  654. state.canvas_instance_batches[state.current_batch_index].filter = texture_filter;
  655. }
  656. RenderingServer::CanvasItemTextureRepeat texture_repeat = p_item->texture_repeat == RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT ? state.default_repeat : p_item->texture_repeat;
  657. if (texture_repeat != state.canvas_instance_batches[state.current_batch_index].repeat) {
  658. _new_batch(r_batch_broken);
  659. state.canvas_instance_batches[state.current_batch_index].repeat = texture_repeat;
  660. }
  661. Transform2D base_transform = p_canvas_transform_inverse * p_item->final_transform;
  662. Transform2D draw_transform; // Used by transform command
  663. Color base_color = p_item->final_modulate;
  664. uint32_t base_flags = 0;
  665. Size2 texpixel_size;
  666. bool reclip = false;
  667. bool skipping = false;
  668. // TODO: consider making lights a per-batch property and then baking light operations in the shader for better performance.
  669. uint32_t lights[4] = { 0, 0, 0, 0 };
  670. uint16_t light_count = 0;
  671. {
  672. Light *light = p_lights;
  673. while (light) {
  674. if (light->render_index_cache >= 0 && p_item->light_mask & light->item_mask && p_item->z_final >= light->z_min && p_item->z_final <= light->z_max && p_item->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) {
  675. uint32_t light_index = light->render_index_cache;
  676. lights[light_count >> 2] |= light_index << ((light_count & 3) * 8);
  677. light_count++;
  678. if (light_count == data.max_lights_per_item - 1) {
  679. break;
  680. }
  681. }
  682. light = light->next_ptr;
  683. }
  684. base_flags |= light_count << FLAGS_LIGHT_COUNT_SHIFT;
  685. }
  686. bool lights_disabled = light_count == 0 && !state.using_directional_lights;
  687. if (lights_disabled != state.canvas_instance_batches[state.current_batch_index].lights_disabled) {
  688. _new_batch(r_batch_broken);
  689. state.canvas_instance_batches[state.current_batch_index].lights_disabled = lights_disabled;
  690. }
  691. const Item::Command *c = p_item->commands;
  692. while (c) {
  693. if (skipping && c->type != Item::Command::TYPE_ANIMATION_SLICE) {
  694. c = c->next;
  695. continue;
  696. }
  697. if (c->type != Item::Command::TYPE_MESH) {
  698. // For Meshes, this gets updated below.
  699. _update_transform_2d_to_mat2x3(base_transform * draw_transform, state.instance_data_array[r_index].world);
  700. }
  701. // Zero out most fields.
  702. for (int i = 0; i < 4; i++) {
  703. state.instance_data_array[r_index].modulation[i] = 0.0;
  704. state.instance_data_array[r_index].ninepatch_margins[i] = 0.0;
  705. state.instance_data_array[r_index].src_rect[i] = 0.0;
  706. state.instance_data_array[r_index].dst_rect[i] = 0.0;
  707. state.instance_data_array[r_index].lights[i] = uint32_t(0);
  708. }
  709. state.instance_data_array[r_index].color_texture_pixel_size[0] = 0.0;
  710. state.instance_data_array[r_index].color_texture_pixel_size[1] = 0.0;
  711. state.instance_data_array[r_index].pad[0] = 0.0;
  712. state.instance_data_array[r_index].pad[1] = 0.0;
  713. state.instance_data_array[r_index].lights[0] = lights[0];
  714. state.instance_data_array[r_index].lights[1] = lights[1];
  715. state.instance_data_array[r_index].lights[2] = lights[2];
  716. state.instance_data_array[r_index].lights[3] = lights[3];
  717. state.instance_data_array[r_index].flags = base_flags | (state.instance_data_array[r_index == 0 ? 0 : r_index - 1].flags & (FLAGS_DEFAULT_NORMAL_MAP_USED | FLAGS_DEFAULT_SPECULAR_MAP_USED)); // Reset on each command for safety, keep canvastexture binding config.
  718. Color blend_color = base_color;
  719. GLES3::CanvasShaderData::BlendMode blend_mode = p_blend_mode;
  720. if (c->type == Item::Command::TYPE_RECT) {
  721. const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);
  722. if (rect->flags & CANVAS_RECT_LCD) {
  723. blend_mode = GLES3::CanvasShaderData::BLEND_MODE_LCD;
  724. blend_color = rect->modulate * base_color;
  725. }
  726. }
  727. if (blend_mode != state.canvas_instance_batches[state.current_batch_index].blend_mode || blend_color != state.canvas_instance_batches[state.current_batch_index].blend_color) {
  728. _new_batch(r_batch_broken);
  729. state.canvas_instance_batches[state.current_batch_index].blend_mode = blend_mode;
  730. state.canvas_instance_batches[state.current_batch_index].blend_color = blend_color;
  731. }
  732. switch (c->type) {
  733. case Item::Command::TYPE_RECT: {
  734. const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);
  735. if (rect->flags & CANVAS_RECT_TILE && state.canvas_instance_batches[state.current_batch_index].repeat != RenderingServer::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED) {
  736. _new_batch(r_batch_broken);
  737. state.canvas_instance_batches[state.current_batch_index].repeat = RenderingServer::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED;
  738. }
  739. if (rect->texture != state.canvas_instance_batches[state.current_batch_index].tex || state.canvas_instance_batches[state.current_batch_index].command_type != Item::Command::TYPE_RECT) {
  740. _new_batch(r_batch_broken);
  741. state.canvas_instance_batches[state.current_batch_index].tex = rect->texture;
  742. state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_RECT;
  743. state.canvas_instance_batches[state.current_batch_index].command = c;
  744. state.canvas_instance_batches[state.current_batch_index].shader_variant = CanvasShaderGLES3::MODE_QUAD;
  745. }
  746. _prepare_canvas_texture(rect->texture, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
  747. Rect2 src_rect;
  748. Rect2 dst_rect;
  749. if (rect->texture != RID()) {
  750. src_rect = (rect->flags & CANVAS_RECT_REGION) ? Rect2(rect->source.position * texpixel_size, rect->source.size * texpixel_size) : Rect2(0, 0, 1, 1);
  751. dst_rect = Rect2(rect->rect.position, rect->rect.size);
  752. if (dst_rect.size.width < 0) {
  753. dst_rect.position.x += dst_rect.size.width;
  754. dst_rect.size.width *= -1;
  755. }
  756. if (dst_rect.size.height < 0) {
  757. dst_rect.position.y += dst_rect.size.height;
  758. dst_rect.size.height *= -1;
  759. }
  760. if (rect->flags & CANVAS_RECT_FLIP_H) {
  761. src_rect.size.x *= -1;
  762. state.instance_data_array[r_index].flags |= FLAGS_FLIP_H;
  763. }
  764. if (rect->flags & CANVAS_RECT_FLIP_V) {
  765. src_rect.size.y *= -1;
  766. state.instance_data_array[r_index].flags |= FLAGS_FLIP_V;
  767. }
  768. if (rect->flags & CANVAS_RECT_TRANSPOSE) {
  769. state.instance_data_array[r_index].flags |= FLAGS_TRANSPOSE_RECT;
  770. }
  771. if (rect->flags & CANVAS_RECT_CLIP_UV) {
  772. state.instance_data_array[r_index].flags |= FLAGS_CLIP_RECT_UV;
  773. }
  774. } else {
  775. dst_rect = Rect2(rect->rect.position, rect->rect.size);
  776. if (dst_rect.size.width < 0) {
  777. dst_rect.position.x += dst_rect.size.width;
  778. dst_rect.size.width *= -1;
  779. }
  780. if (dst_rect.size.height < 0) {
  781. dst_rect.position.y += dst_rect.size.height;
  782. dst_rect.size.height *= -1;
  783. }
  784. src_rect = Rect2(0, 0, 1, 1);
  785. }
  786. if (rect->flags & CANVAS_RECT_MSDF) {
  787. state.instance_data_array[r_index].flags |= FLAGS_USE_MSDF;
  788. state.instance_data_array[r_index].msdf[0] = rect->px_range; // Pixel range.
  789. state.instance_data_array[r_index].msdf[1] = rect->outline; // Outline size.
  790. state.instance_data_array[r_index].msdf[2] = 0.f; // Reserved.
  791. state.instance_data_array[r_index].msdf[3] = 0.f; // Reserved.
  792. } else if (rect->flags & CANVAS_RECT_LCD) {
  793. state.instance_data_array[r_index].flags |= FLAGS_USE_LCD;
  794. }
  795. state.instance_data_array[r_index].modulation[0] = rect->modulate.r * base_color.r;
  796. state.instance_data_array[r_index].modulation[1] = rect->modulate.g * base_color.g;
  797. state.instance_data_array[r_index].modulation[2] = rect->modulate.b * base_color.b;
  798. state.instance_data_array[r_index].modulation[3] = rect->modulate.a * base_color.a;
  799. state.instance_data_array[r_index].src_rect[0] = src_rect.position.x;
  800. state.instance_data_array[r_index].src_rect[1] = src_rect.position.y;
  801. state.instance_data_array[r_index].src_rect[2] = src_rect.size.width;
  802. state.instance_data_array[r_index].src_rect[3] = src_rect.size.height;
  803. state.instance_data_array[r_index].dst_rect[0] = dst_rect.position.x;
  804. state.instance_data_array[r_index].dst_rect[1] = dst_rect.position.y;
  805. state.instance_data_array[r_index].dst_rect[2] = dst_rect.size.width;
  806. state.instance_data_array[r_index].dst_rect[3] = dst_rect.size.height;
  807. _add_to_batch(r_index, r_batch_broken);
  808. } break;
  809. case Item::Command::TYPE_NINEPATCH: {
  810. const Item::CommandNinePatch *np = static_cast<const Item::CommandNinePatch *>(c);
  811. if (np->texture != state.canvas_instance_batches[state.current_batch_index].tex || state.canvas_instance_batches[state.current_batch_index].command_type != Item::Command::TYPE_NINEPATCH) {
  812. _new_batch(r_batch_broken);
  813. state.canvas_instance_batches[state.current_batch_index].tex = np->texture;
  814. state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_NINEPATCH;
  815. state.canvas_instance_batches[state.current_batch_index].command = c;
  816. state.canvas_instance_batches[state.current_batch_index].shader_variant = CanvasShaderGLES3::MODE_NINEPATCH;
  817. }
  818. _prepare_canvas_texture(np->texture, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
  819. Rect2 src_rect;
  820. Rect2 dst_rect(np->rect.position.x, np->rect.position.y, np->rect.size.x, np->rect.size.y);
  821. if (np->texture == RID()) {
  822. texpixel_size = Size2(1, 1);
  823. src_rect = Rect2(0, 0, 1, 1);
  824. } else {
  825. if (np->source != Rect2()) {
  826. src_rect = Rect2(np->source.position.x * texpixel_size.width, np->source.position.y * texpixel_size.height, np->source.size.x * texpixel_size.width, np->source.size.y * texpixel_size.height);
  827. state.instance_data_array[r_index].color_texture_pixel_size[0] = 1.0 / np->source.size.width;
  828. state.instance_data_array[r_index].color_texture_pixel_size[1] = 1.0 / np->source.size.height;
  829. } else {
  830. src_rect = Rect2(0, 0, 1, 1);
  831. }
  832. }
  833. state.instance_data_array[r_index].modulation[0] = np->color.r * base_color.r;
  834. state.instance_data_array[r_index].modulation[1] = np->color.g * base_color.g;
  835. state.instance_data_array[r_index].modulation[2] = np->color.b * base_color.b;
  836. state.instance_data_array[r_index].modulation[3] = np->color.a * base_color.a;
  837. state.instance_data_array[r_index].src_rect[0] = src_rect.position.x;
  838. state.instance_data_array[r_index].src_rect[1] = src_rect.position.y;
  839. state.instance_data_array[r_index].src_rect[2] = src_rect.size.width;
  840. state.instance_data_array[r_index].src_rect[3] = src_rect.size.height;
  841. state.instance_data_array[r_index].dst_rect[0] = dst_rect.position.x;
  842. state.instance_data_array[r_index].dst_rect[1] = dst_rect.position.y;
  843. state.instance_data_array[r_index].dst_rect[2] = dst_rect.size.width;
  844. state.instance_data_array[r_index].dst_rect[3] = dst_rect.size.height;
  845. state.instance_data_array[r_index].flags |= int(np->axis_x) << FLAGS_NINEPATCH_H_MODE_SHIFT;
  846. state.instance_data_array[r_index].flags |= int(np->axis_y) << FLAGS_NINEPATCH_V_MODE_SHIFT;
  847. if (np->draw_center) {
  848. state.instance_data_array[r_index].flags |= FLAGS_NINEPACH_DRAW_CENTER;
  849. }
  850. state.instance_data_array[r_index].ninepatch_margins[0] = np->margin[SIDE_LEFT];
  851. state.instance_data_array[r_index].ninepatch_margins[1] = np->margin[SIDE_TOP];
  852. state.instance_data_array[r_index].ninepatch_margins[2] = np->margin[SIDE_RIGHT];
  853. state.instance_data_array[r_index].ninepatch_margins[3] = np->margin[SIDE_BOTTOM];
  854. _add_to_batch(r_index, r_batch_broken);
  855. // Restore if overridden.
  856. state.instance_data_array[r_index].color_texture_pixel_size[0] = texpixel_size.x;
  857. state.instance_data_array[r_index].color_texture_pixel_size[1] = texpixel_size.y;
  858. } break;
  859. case Item::Command::TYPE_POLYGON: {
  860. const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c);
  861. // Polygon's can't be batched, so always create a new batch
  862. _new_batch(r_batch_broken);
  863. state.canvas_instance_batches[state.current_batch_index].tex = polygon->texture;
  864. state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_POLYGON;
  865. state.canvas_instance_batches[state.current_batch_index].command = c;
  866. state.canvas_instance_batches[state.current_batch_index].shader_variant = CanvasShaderGLES3::MODE_ATTRIBUTES;
  867. _prepare_canvas_texture(polygon->texture, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
  868. state.instance_data_array[r_index].modulation[0] = base_color.r;
  869. state.instance_data_array[r_index].modulation[1] = base_color.g;
  870. state.instance_data_array[r_index].modulation[2] = base_color.b;
  871. state.instance_data_array[r_index].modulation[3] = base_color.a;
  872. for (int j = 0; j < 4; j++) {
  873. state.instance_data_array[r_index].src_rect[j] = 0;
  874. state.instance_data_array[r_index].dst_rect[j] = 0;
  875. state.instance_data_array[r_index].ninepatch_margins[j] = 0;
  876. }
  877. _add_to_batch(r_index, r_batch_broken);
  878. } break;
  879. case Item::Command::TYPE_PRIMITIVE: {
  880. const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c);
  881. if (primitive->point_count != state.canvas_instance_batches[state.current_batch_index].primitive_points || state.canvas_instance_batches[state.current_batch_index].command_type != Item::Command::TYPE_PRIMITIVE) {
  882. _new_batch(r_batch_broken);
  883. state.canvas_instance_batches[state.current_batch_index].tex = primitive->texture;
  884. state.canvas_instance_batches[state.current_batch_index].primitive_points = primitive->point_count;
  885. state.canvas_instance_batches[state.current_batch_index].command_type = Item::Command::TYPE_PRIMITIVE;
  886. state.canvas_instance_batches[state.current_batch_index].command = c;
  887. state.canvas_instance_batches[state.current_batch_index].shader_variant = CanvasShaderGLES3::MODE_PRIMITIVE;
  888. }
  889. _prepare_canvas_texture(state.canvas_instance_batches[state.current_batch_index].tex, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
  890. for (uint32_t j = 0; j < MIN(3u, primitive->point_count); j++) {
  891. state.instance_data_array[r_index].points[j * 2 + 0] = primitive->points[j].x;
  892. state.instance_data_array[r_index].points[j * 2 + 1] = primitive->points[j].y;
  893. state.instance_data_array[r_index].uvs[j * 2 + 0] = primitive->uvs[j].x;
  894. state.instance_data_array[r_index].uvs[j * 2 + 1] = primitive->uvs[j].y;
  895. Color col = primitive->colors[j] * base_color;
  896. state.instance_data_array[r_index].colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
  897. state.instance_data_array[r_index].colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
  898. }
  899. _add_to_batch(r_index, r_batch_broken);
  900. if (primitive->point_count == 4) {
  901. // Reset base data.
  902. _update_transform_2d_to_mat2x3(base_transform * draw_transform, state.instance_data_array[r_index].world);
  903. _prepare_canvas_texture(state.canvas_instance_batches[state.current_batch_index].tex, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
  904. for (uint32_t j = 0; j < 3; j++) {
  905. int offset = j == 0 ? 0 : 1;
  906. // Second triangle in the quad. Uses vertices 0, 2, 3.
  907. state.instance_data_array[r_index].points[j * 2 + 0] = primitive->points[j + offset].x;
  908. state.instance_data_array[r_index].points[j * 2 + 1] = primitive->points[j + offset].y;
  909. state.instance_data_array[r_index].uvs[j * 2 + 0] = primitive->uvs[j + offset].x;
  910. state.instance_data_array[r_index].uvs[j * 2 + 1] = primitive->uvs[j + offset].y;
  911. Color col = primitive->colors[j + offset] * base_color;
  912. state.instance_data_array[r_index].colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
  913. state.instance_data_array[r_index].colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
  914. }
  915. _add_to_batch(r_index, r_batch_broken);
  916. }
  917. } break;
  918. case Item::Command::TYPE_MESH:
  919. case Item::Command::TYPE_MULTIMESH:
  920. case Item::Command::TYPE_PARTICLES: {
  921. // Mesh's can't be batched, so always create a new batch
  922. _new_batch(r_batch_broken);
  923. Color modulate(1, 1, 1, 1);
  924. state.canvas_instance_batches[state.current_batch_index].shader_variant = CanvasShaderGLES3::MODE_ATTRIBUTES;
  925. if (c->type == Item::Command::TYPE_MESH) {
  926. const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(c);
  927. state.canvas_instance_batches[state.current_batch_index].tex = m->texture;
  928. _update_transform_2d_to_mat2x3(base_transform * draw_transform * m->transform, state.instance_data_array[r_index].world);
  929. modulate = m->modulate;
  930. } else if (c->type == Item::Command::TYPE_MULTIMESH) {
  931. const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(c);
  932. state.canvas_instance_batches[state.current_batch_index].tex = mm->texture;
  933. state.canvas_instance_batches[state.current_batch_index].shader_variant = CanvasShaderGLES3::MODE_INSTANCED;
  934. if (GLES3::MeshStorage::get_singleton()->multimesh_uses_colors(mm->multimesh)) {
  935. state.instance_data_array[r_index].flags |= FLAGS_INSTANCING_HAS_COLORS;
  936. }
  937. if (GLES3::MeshStorage::get_singleton()->multimesh_uses_custom_data(mm->multimesh)) {
  938. state.instance_data_array[r_index].flags |= FLAGS_INSTANCING_HAS_CUSTOM_DATA;
  939. }
  940. } else if (c->type == Item::Command::TYPE_PARTICLES) {
  941. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  942. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  943. const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(c);
  944. RID particles = pt->particles;
  945. state.canvas_instance_batches[state.current_batch_index].tex = pt->texture;
  946. state.canvas_instance_batches[state.current_batch_index].shader_variant = CanvasShaderGLES3::MODE_INSTANCED;
  947. state.instance_data_array[r_index].flags |= FLAGS_INSTANCING_HAS_COLORS;
  948. state.instance_data_array[r_index].flags |= FLAGS_INSTANCING_HAS_CUSTOM_DATA;
  949. if (particles_storage->particles_has_collision(particles) && texture_storage->render_target_is_sdf_enabled(p_render_target)) {
  950. // Pass collision information.
  951. Transform2D xform = p_item->final_transform;
  952. GLuint sdf_texture = texture_storage->render_target_get_sdf_texture(p_render_target);
  953. Rect2 to_screen;
  954. {
  955. Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_render_target);
  956. to_screen.size = Vector2(1.0 / sdf_rect.size.width, 1.0 / sdf_rect.size.height);
  957. to_screen.position = -sdf_rect.position * to_screen.size;
  958. }
  959. particles_storage->particles_set_canvas_sdf_collision(pt->particles, true, xform, to_screen, sdf_texture);
  960. } else {
  961. particles_storage->particles_set_canvas_sdf_collision(pt->particles, false, Transform2D(), Rect2(), 0);
  962. }
  963. r_sdf_used |= particles_storage->particles_has_collision(particles);
  964. }
  965. state.canvas_instance_batches[state.current_batch_index].command = c;
  966. state.canvas_instance_batches[state.current_batch_index].command_type = c->type;
  967. _prepare_canvas_texture(state.canvas_instance_batches[state.current_batch_index].tex, state.canvas_instance_batches[state.current_batch_index].filter, state.canvas_instance_batches[state.current_batch_index].repeat, r_index, texpixel_size);
  968. state.instance_data_array[r_index].modulation[0] = base_color.r * modulate.r;
  969. state.instance_data_array[r_index].modulation[1] = base_color.g * modulate.g;
  970. state.instance_data_array[r_index].modulation[2] = base_color.b * modulate.b;
  971. state.instance_data_array[r_index].modulation[3] = base_color.a * modulate.a;
  972. for (int j = 0; j < 4; j++) {
  973. state.instance_data_array[r_index].src_rect[j] = 0;
  974. state.instance_data_array[r_index].dst_rect[j] = 0;
  975. state.instance_data_array[r_index].ninepatch_margins[j] = 0;
  976. }
  977. _add_to_batch(r_index, r_batch_broken);
  978. } break;
  979. case Item::Command::TYPE_TRANSFORM: {
  980. const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c);
  981. draw_transform = transform->xform;
  982. } break;
  983. case Item::Command::TYPE_CLIP_IGNORE: {
  984. const Item::CommandClipIgnore *ci = static_cast<const Item::CommandClipIgnore *>(c);
  985. if (current_clip) {
  986. if (ci->ignore != reclip) {
  987. _new_batch(r_batch_broken);
  988. if (ci->ignore) {
  989. state.canvas_instance_batches[state.current_batch_index].clip = nullptr;
  990. reclip = true;
  991. } else {
  992. state.canvas_instance_batches[state.current_batch_index].clip = current_clip;
  993. reclip = false;
  994. }
  995. }
  996. }
  997. } break;
  998. case Item::Command::TYPE_ANIMATION_SLICE: {
  999. const Item::CommandAnimationSlice *as = static_cast<const Item::CommandAnimationSlice *>(c);
  1000. double current_time = RSG::rasterizer->get_total_time();
  1001. double local_time = Math::fposmod(current_time - as->offset, as->animation_length);
  1002. skipping = !(local_time >= as->slice_begin && local_time < as->slice_end);
  1003. RenderingServerDefault::redraw_request(); // animation visible means redraw request
  1004. } break;
  1005. }
  1006. c = c->next;
  1007. r_batch_broken = false;
  1008. }
  1009. if (current_clip && reclip) {
  1010. //will make it re-enable clipping if needed afterwards
  1011. current_clip = nullptr;
  1012. }
  1013. }
  1014. void RasterizerCanvasGLES3::_render_batch(Light *p_lights, uint32_t p_index) {
  1015. ERR_FAIL_NULL(state.canvas_instance_batches[state.current_batch_index].command);
  1016. // Used by Polygon and Mesh.
  1017. static const GLenum prim[5] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP };
  1018. _bind_canvas_texture(state.canvas_instance_batches[p_index].tex, state.canvas_instance_batches[p_index].filter, state.canvas_instance_batches[p_index].repeat);
  1019. switch (state.canvas_instance_batches[p_index].command_type) {
  1020. case Item::Command::TYPE_RECT:
  1021. case Item::Command::TYPE_NINEPATCH: {
  1022. glBindVertexArray(data.indexed_quad_array);
  1023. glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
  1024. uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
  1025. _enable_attributes(range_start, false);
  1026. glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, state.canvas_instance_batches[p_index].instance_count);
  1027. glBindVertexArray(0);
  1028. } break;
  1029. case Item::Command::TYPE_POLYGON: {
  1030. const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(state.canvas_instance_batches[p_index].command);
  1031. PolygonBuffers *pb = polygon_buffers.polygons.getptr(polygon->polygon.polygon_id);
  1032. ERR_FAIL_NULL(pb);
  1033. glBindVertexArray(pb->vertex_array);
  1034. glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
  1035. uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
  1036. _enable_attributes(range_start, false);
  1037. if (pb->color_disabled && pb->color != Color(1.0, 1.0, 1.0, 1.0)) {
  1038. glVertexAttrib4f(RS::ARRAY_COLOR, pb->color.r, pb->color.g, pb->color.b, pb->color.a);
  1039. }
  1040. if (pb->index_buffer != 0) {
  1041. glDrawElementsInstanced(prim[polygon->primitive], pb->count, GL_UNSIGNED_INT, nullptr, 1);
  1042. } else {
  1043. glDrawArraysInstanced(prim[polygon->primitive], 0, pb->count, 1);
  1044. }
  1045. glBindVertexArray(0);
  1046. if (pb->color_disabled && pb->color != Color(1.0, 1.0, 1.0, 1.0)) {
  1047. // Reset so this doesn't pollute other draw calls.
  1048. glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0);
  1049. }
  1050. } break;
  1051. case Item::Command::TYPE_PRIMITIVE: {
  1052. glBindVertexArray(data.canvas_quad_array);
  1053. glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
  1054. uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
  1055. _enable_attributes(range_start, true);
  1056. const GLenum primitive[5] = { GL_POINTS, GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLES };
  1057. int instance_count = state.canvas_instance_batches[p_index].instance_count;
  1058. ERR_FAIL_COND(instance_count <= 0);
  1059. if (instance_count >= 1) {
  1060. glDrawArraysInstanced(primitive[state.canvas_instance_batches[p_index].primitive_points], 0, state.canvas_instance_batches[p_index].primitive_points, instance_count);
  1061. }
  1062. } break;
  1063. case Item::Command::TYPE_MESH:
  1064. case Item::Command::TYPE_MULTIMESH:
  1065. case Item::Command::TYPE_PARTICLES: {
  1066. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  1067. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  1068. RID mesh;
  1069. RID mesh_instance;
  1070. uint32_t instance_count = 1;
  1071. GLuint instance_buffer = 0;
  1072. uint32_t instance_stride = 0;
  1073. uint32_t instance_color_offset = 0;
  1074. bool instance_uses_color = false;
  1075. bool instance_uses_custom_data = false;
  1076. bool use_instancing = false;
  1077. if (state.canvas_instance_batches[p_index].command_type == Item::Command::TYPE_MESH) {
  1078. const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(state.canvas_instance_batches[p_index].command);
  1079. mesh = m->mesh;
  1080. mesh_instance = m->mesh_instance;
  1081. } else if (state.canvas_instance_batches[p_index].command_type == Item::Command::TYPE_MULTIMESH) {
  1082. const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(state.canvas_instance_batches[p_index].command);
  1083. RID multimesh = mm->multimesh;
  1084. mesh = mesh_storage->multimesh_get_mesh(multimesh);
  1085. if (mesh_storage->multimesh_get_transform_format(multimesh) != RS::MULTIMESH_TRANSFORM_2D) {
  1086. break;
  1087. }
  1088. instance_count = mesh_storage->multimesh_get_instances_to_draw(multimesh);
  1089. if (instance_count == 0) {
  1090. break;
  1091. }
  1092. instance_buffer = mesh_storage->multimesh_get_gl_buffer(multimesh);
  1093. instance_stride = mesh_storage->multimesh_get_stride(multimesh);
  1094. instance_color_offset = mesh_storage->multimesh_get_color_offset(multimesh);
  1095. instance_uses_color = mesh_storage->multimesh_uses_colors(multimesh);
  1096. instance_uses_custom_data = mesh_storage->multimesh_uses_custom_data(multimesh);
  1097. use_instancing = true;
  1098. } else if (state.canvas_instance_batches[p_index].command_type == Item::Command::TYPE_PARTICLES) {
  1099. const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(state.canvas_instance_batches[p_index].command);
  1100. RID particles = pt->particles;
  1101. mesh = particles_storage->particles_get_draw_pass_mesh(particles, 0);
  1102. ERR_BREAK(particles_storage->particles_get_mode(particles) != RS::PARTICLES_MODE_2D);
  1103. particles_storage->particles_request_process(particles);
  1104. if (particles_storage->particles_is_inactive(particles)) {
  1105. break;
  1106. }
  1107. RenderingServerDefault::redraw_request(); // Active particles means redraw request.
  1108. int dpc = particles_storage->particles_get_draw_passes(particles);
  1109. if (dpc == 0) {
  1110. break; // Nothing to draw.
  1111. }
  1112. instance_count = particles_storage->particles_get_amount(particles);
  1113. instance_buffer = particles_storage->particles_get_gl_buffer(particles);
  1114. instance_stride = 12; // 8 bytes for instance transform and 4 bytes for packed color and custom.
  1115. instance_color_offset = 8; // 8 bytes for instance transform.
  1116. instance_uses_color = true;
  1117. instance_uses_custom_data = true;
  1118. use_instancing = true;
  1119. }
  1120. ERR_FAIL_COND(mesh.is_null());
  1121. uint32_t surf_count = mesh_storage->mesh_get_surface_count(mesh);
  1122. for (uint32_t j = 0; j < surf_count; j++) {
  1123. void *surface = mesh_storage->mesh_get_surface(mesh, j);
  1124. RS::PrimitiveType primitive = mesh_storage->mesh_surface_get_primitive(surface);
  1125. ERR_CONTINUE(primitive < 0 || primitive >= RS::PRIMITIVE_MAX);
  1126. GLuint vertex_array_gl = 0;
  1127. GLuint index_array_gl = 0;
  1128. uint64_t input_mask = RS::ARRAY_FORMAT_VERTEX | RS::ARRAY_FORMAT_COLOR | RS::ARRAY_FORMAT_TEX_UV; // 2D meshes always use the same vertex format.
  1129. if (mesh_instance.is_valid()) {
  1130. mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(mesh_instance, j, input_mask, vertex_array_gl);
  1131. } else {
  1132. mesh_storage->mesh_surface_get_vertex_arrays_and_format(surface, input_mask, vertex_array_gl);
  1133. }
  1134. index_array_gl = mesh_storage->mesh_surface_get_index_buffer(surface, 0);
  1135. bool use_index_buffer = false;
  1136. glBindVertexArray(vertex_array_gl);
  1137. glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.canvas_instance_batches[p_index].instance_buffer_index]);
  1138. uint32_t range_start = state.canvas_instance_batches[p_index].start * sizeof(InstanceData);
  1139. _enable_attributes(range_start, false, instance_count);
  1140. if (index_array_gl != 0) {
  1141. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_array_gl);
  1142. use_index_buffer = true;
  1143. }
  1144. if (use_instancing) {
  1145. if (instance_buffer == 0) {
  1146. break;
  1147. }
  1148. // Bind instance buffers.
  1149. glBindBuffer(GL_ARRAY_BUFFER, instance_buffer);
  1150. glEnableVertexAttribArray(1);
  1151. glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, instance_stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(0));
  1152. glVertexAttribDivisor(1, 1);
  1153. glEnableVertexAttribArray(2);
  1154. glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, instance_stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(4 * 4));
  1155. glVertexAttribDivisor(2, 1);
  1156. if (instance_uses_color || instance_uses_custom_data) {
  1157. glEnableVertexAttribArray(5);
  1158. glVertexAttribIPointer(5, 4, GL_UNSIGNED_INT, instance_stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(instance_color_offset * sizeof(float)));
  1159. glVertexAttribDivisor(5, 1);
  1160. } else {
  1161. // Set all default instance color and custom data values to 1.0 or 0.0 using a compressed format.
  1162. uint16_t zero = Math::make_half_float(0.0f);
  1163. uint16_t one = Math::make_half_float(1.0f);
  1164. GLuint default_color = (uint32_t(one) << 16) | one;
  1165. GLuint default_custom = (uint32_t(zero) << 16) | zero;
  1166. glVertexAttribI4ui(5, default_color, default_color, default_custom, default_custom);
  1167. }
  1168. }
  1169. GLenum primitive_gl = prim[int(primitive)];
  1170. if (use_index_buffer) {
  1171. glDrawElementsInstanced(primitive_gl, mesh_storage->mesh_surface_get_vertices_drawn_count(surface), mesh_storage->mesh_surface_get_index_type(surface), 0, instance_count);
  1172. } else {
  1173. glDrawArraysInstanced(primitive_gl, 0, mesh_storage->mesh_surface_get_vertices_drawn_count(surface), instance_count);
  1174. }
  1175. glBindBuffer(GL_ARRAY_BUFFER, 0);
  1176. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  1177. if (use_instancing) {
  1178. glDisableVertexAttribArray(5);
  1179. glDisableVertexAttribArray(6);
  1180. glDisableVertexAttribArray(7);
  1181. glDisableVertexAttribArray(8);
  1182. }
  1183. }
  1184. } break;
  1185. case Item::Command::TYPE_TRANSFORM:
  1186. case Item::Command::TYPE_CLIP_IGNORE:
  1187. case Item::Command::TYPE_ANIMATION_SLICE: {
  1188. // Can ignore these as they only impact batch creation.
  1189. } break;
  1190. }
  1191. }
  1192. void RasterizerCanvasGLES3::_add_to_batch(uint32_t &r_index, bool &r_batch_broken) {
  1193. state.canvas_instance_batches[state.current_batch_index].instance_count++;
  1194. r_index++;
  1195. if (r_index + state.last_item_index >= data.max_instances_per_buffer) {
  1196. // Copy over all data needed for rendering right away
  1197. // then go back to recording item commands.
  1198. glBindBuffer(GL_ARRAY_BUFFER, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.current_instance_buffer_index]);
  1199. #ifdef WEB_ENABLED
  1200. glBufferSubData(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), sizeof(InstanceData) * r_index, state.instance_data_array);
  1201. #else
  1202. // On Desktop and mobile we map the memory without synchronizing for maximum speed.
  1203. void *buffer = glMapBufferRange(GL_ARRAY_BUFFER, state.last_item_index * sizeof(InstanceData), r_index * sizeof(InstanceData), GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
  1204. memcpy(buffer, state.instance_data_array, r_index * sizeof(InstanceData));
  1205. glUnmapBuffer(GL_ARRAY_BUFFER);
  1206. #endif
  1207. _allocate_instance_buffer();
  1208. r_index = 0;
  1209. state.last_item_index = 0;
  1210. r_batch_broken = false; // Force a new batch to be created
  1211. _new_batch(r_batch_broken);
  1212. state.canvas_instance_batches[state.current_batch_index].start = 0;
  1213. }
  1214. }
  1215. void RasterizerCanvasGLES3::_new_batch(bool &r_batch_broken) {
  1216. if (state.canvas_instance_batches.size() == 0) {
  1217. state.canvas_instance_batches.push_back(Batch());
  1218. return;
  1219. }
  1220. if (r_batch_broken || state.canvas_instance_batches[state.current_batch_index].instance_count == 0) {
  1221. return;
  1222. }
  1223. r_batch_broken = true;
  1224. // Copy the properties of the current batch, we will manually update the things that changed.
  1225. Batch new_batch = state.canvas_instance_batches[state.current_batch_index];
  1226. new_batch.instance_count = 0;
  1227. new_batch.start = state.canvas_instance_batches[state.current_batch_index].start + state.canvas_instance_batches[state.current_batch_index].instance_count;
  1228. new_batch.instance_buffer_index = state.current_instance_buffer_index;
  1229. state.current_batch_index++;
  1230. state.canvas_instance_batches.push_back(new_batch);
  1231. }
  1232. void RasterizerCanvasGLES3::_enable_attributes(uint32_t p_start, bool p_primitive, uint32_t p_rate) {
  1233. uint32_t split = p_primitive ? 11 : 12;
  1234. for (uint32_t i = 6; i < split; i++) {
  1235. glEnableVertexAttribArray(i);
  1236. glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, sizeof(InstanceData), CAST_INT_TO_UCHAR_PTR(p_start + (i - 6) * 4 * sizeof(float)));
  1237. glVertexAttribDivisor(i, p_rate);
  1238. }
  1239. for (uint32_t i = split; i <= 13; i++) {
  1240. glEnableVertexAttribArray(i);
  1241. glVertexAttribIPointer(i, 4, GL_UNSIGNED_INT, sizeof(InstanceData), CAST_INT_TO_UCHAR_PTR(p_start + (i - 6) * 4 * sizeof(float)));
  1242. glVertexAttribDivisor(i, p_rate);
  1243. }
  1244. }
  1245. RID RasterizerCanvasGLES3::light_create() {
  1246. CanvasLight canvas_light;
  1247. return canvas_light_owner.make_rid(canvas_light);
  1248. }
  1249. void RasterizerCanvasGLES3::light_set_texture(RID p_rid, RID p_texture) {
  1250. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1251. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  1252. ERR_FAIL_NULL(cl);
  1253. if (cl->texture == p_texture) {
  1254. return;
  1255. }
  1256. ERR_FAIL_COND(p_texture.is_valid() && !texture_storage->owns_texture(p_texture));
  1257. if (cl->texture.is_valid()) {
  1258. texture_storage->texture_remove_from_texture_atlas(cl->texture);
  1259. }
  1260. cl->texture = p_texture;
  1261. if (cl->texture.is_valid()) {
  1262. texture_storage->texture_add_to_texture_atlas(cl->texture);
  1263. }
  1264. }
  1265. void RasterizerCanvasGLES3::light_set_use_shadow(RID p_rid, bool p_enable) {
  1266. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  1267. ERR_FAIL_NULL(cl);
  1268. cl->shadow.enabled = p_enable;
  1269. }
  1270. void RasterizerCanvasGLES3::light_update_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders) {
  1271. GLES3::Config *config = GLES3::Config::get_singleton();
  1272. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  1273. ERR_FAIL_COND(!cl->shadow.enabled);
  1274. _update_shadow_atlas();
  1275. cl->shadow.z_far = p_far;
  1276. cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(data.max_lights_per_render * 2);
  1277. glBindFramebuffer(GL_FRAMEBUFFER, state.shadow_fb);
  1278. glViewport(0, p_shadow_index * 2, state.shadow_texture_size, 2);
  1279. glDepthMask(GL_TRUE);
  1280. glEnable(GL_DEPTH_TEST);
  1281. glDepthFunc(GL_LESS);
  1282. glDisable(GL_BLEND);
  1283. glEnable(GL_SCISSOR_TEST);
  1284. glScissor(0, p_shadow_index * 2, state.shadow_texture_size, 2);
  1285. glClearColor(p_far, p_far, p_far, 1.0);
  1286. RasterizerGLES3::clear_depth(1.0);
  1287. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1288. glCullFace(GL_BACK);
  1289. glDisable(GL_CULL_FACE);
  1290. RS::CanvasOccluderPolygonCullMode cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
  1291. CanvasOcclusionShaderGLES3::ShaderVariant variant = config->float_texture_supported ? CanvasOcclusionShaderGLES3::MODE_SHADOW : CanvasOcclusionShaderGLES3::MODE_SHADOW_RGBA;
  1292. bool success = shadow_render.shader.version_bind_shader(shadow_render.shader_version, variant);
  1293. if (!success) {
  1294. return;
  1295. }
  1296. for (int i = 0; i < 4; i++) {
  1297. glViewport((state.shadow_texture_size / 4) * i, p_shadow_index * 2, (state.shadow_texture_size / 4), 2);
  1298. Projection projection;
  1299. {
  1300. real_t fov = 90;
  1301. real_t nearp = p_near;
  1302. real_t farp = p_far;
  1303. real_t aspect = 1.0;
  1304. real_t ymax = nearp * Math::tan(Math::deg_to_rad(fov * 0.5));
  1305. real_t ymin = -ymax;
  1306. real_t xmin = ymin * aspect;
  1307. real_t xmax = ymax * aspect;
  1308. projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp);
  1309. }
  1310. Vector3 cam_target = Basis::from_euler(Vector3(0, 0, Math_TAU * ((i + 3) / 4.0))).xform(Vector3(0, 1, 0));
  1311. projection = projection * Projection(Transform3D().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse());
  1312. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::PROJECTION, projection, shadow_render.shader_version, variant);
  1313. static const Vector2 directions[4] = { Vector2(1, 0), Vector2(0, 1), Vector2(-1, 0), Vector2(0, -1) };
  1314. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::DIRECTION, directions[i].x, directions[i].y, shadow_render.shader_version, variant);
  1315. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::Z_FAR, p_far, shadow_render.shader_version, variant);
  1316. LightOccluderInstance *instance = p_occluders;
  1317. while (instance) {
  1318. OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);
  1319. if (!co || co->vertex_array == 0 || !(p_light_mask & instance->light_mask)) {
  1320. instance = instance->next;
  1321. continue;
  1322. }
  1323. Transform2D modelview = p_light_xform * instance->xform_cache;
  1324. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW1, modelview.columns[0][0], modelview.columns[1][0], 0, modelview.columns[2][0], shadow_render.shader_version, variant);
  1325. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW2, modelview.columns[0][1], modelview.columns[1][1], 0, modelview.columns[2][1], shadow_render.shader_version, variant);
  1326. if (co->cull_mode != cull_mode) {
  1327. if (co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
  1328. glDisable(GL_CULL_FACE);
  1329. } else {
  1330. if (cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
  1331. // Last time was disabled, so enable and set proper face.
  1332. glEnable(GL_CULL_FACE);
  1333. }
  1334. glCullFace(co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE ? GL_FRONT : GL_BACK);
  1335. }
  1336. cull_mode = co->cull_mode;
  1337. }
  1338. glBindVertexArray(co->vertex_array);
  1339. glDrawElements(GL_TRIANGLES, 3 * co->line_point_count, GL_UNSIGNED_SHORT, 0);
  1340. instance = instance->next;
  1341. }
  1342. }
  1343. glBindVertexArray(0);
  1344. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  1345. glDepthMask(GL_FALSE);
  1346. glDisable(GL_DEPTH_TEST);
  1347. glDisable(GL_SCISSOR_TEST);
  1348. }
  1349. void RasterizerCanvasGLES3::light_update_directional_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_cull_distance, const Rect2 &p_clip_rect, LightOccluderInstance *p_occluders) {
  1350. GLES3::Config *config = GLES3::Config::get_singleton();
  1351. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  1352. ERR_FAIL_COND(!cl->shadow.enabled);
  1353. _update_shadow_atlas();
  1354. Vector2 light_dir = p_light_xform.columns[1].normalized();
  1355. Vector2 center = p_clip_rect.get_center();
  1356. float to_edge_distance = ABS(light_dir.dot(p_clip_rect.get_support(light_dir)) - light_dir.dot(center));
  1357. Vector2 from_pos = center - light_dir * (to_edge_distance + p_cull_distance);
  1358. float distance = to_edge_distance * 2.0 + p_cull_distance;
  1359. float half_size = p_clip_rect.size.length() * 0.5; //shadow length, must keep this no matter the angle
  1360. cl->shadow.z_far = distance;
  1361. cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(data.max_lights_per_render * 2);
  1362. Transform2D to_light_xform;
  1363. to_light_xform[2] = from_pos;
  1364. to_light_xform[1] = light_dir;
  1365. to_light_xform[0] = -light_dir.orthogonal();
  1366. to_light_xform.invert();
  1367. glBindFramebuffer(GL_FRAMEBUFFER, state.shadow_fb);
  1368. glViewport(0, p_shadow_index * 2, state.shadow_texture_size, 2);
  1369. glDepthMask(GL_TRUE);
  1370. glEnable(GL_DEPTH_TEST);
  1371. glDepthFunc(GL_LESS);
  1372. glDisable(GL_BLEND);
  1373. glEnable(GL_SCISSOR_TEST);
  1374. glScissor(0, p_shadow_index * 2, state.shadow_texture_size, 2);
  1375. glClearColor(1.0, 1.0, 1.0, 1.0);
  1376. RasterizerGLES3::clear_depth(1.0);
  1377. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1378. glCullFace(GL_BACK);
  1379. glDisable(GL_CULL_FACE);
  1380. RS::CanvasOccluderPolygonCullMode cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
  1381. CanvasOcclusionShaderGLES3::ShaderVariant variant = config->float_texture_supported ? CanvasOcclusionShaderGLES3::MODE_SHADOW : CanvasOcclusionShaderGLES3::MODE_SHADOW_RGBA;
  1382. bool success = shadow_render.shader.version_bind_shader(shadow_render.shader_version, variant);
  1383. if (!success) {
  1384. return;
  1385. }
  1386. Projection projection;
  1387. projection.set_orthogonal(-half_size, half_size, -0.5, 0.5, 0.0, distance);
  1388. projection = projection * Projection(Transform3D().looking_at(Vector3(0, 1, 0), Vector3(0, 0, -1)).affine_inverse());
  1389. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::PROJECTION, projection, shadow_render.shader_version, variant);
  1390. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::DIRECTION, 0.0, 1.0, shadow_render.shader_version, variant);
  1391. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::Z_FAR, distance, shadow_render.shader_version, variant);
  1392. LightOccluderInstance *instance = p_occluders;
  1393. while (instance) {
  1394. OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);
  1395. if (!co || co->vertex_array == 0 || !(p_light_mask & instance->light_mask)) {
  1396. instance = instance->next;
  1397. continue;
  1398. }
  1399. Transform2D modelview = to_light_xform * instance->xform_cache;
  1400. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW1, modelview.columns[0][0], modelview.columns[1][0], 0, modelview.columns[2][0], shadow_render.shader_version, variant);
  1401. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW2, modelview.columns[0][1], modelview.columns[1][1], 0, modelview.columns[2][1], shadow_render.shader_version, variant);
  1402. if (co->cull_mode != cull_mode) {
  1403. if (co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
  1404. glDisable(GL_CULL_FACE);
  1405. } else {
  1406. if (cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED) {
  1407. // Last time was disabled, so enable and set proper face.
  1408. glEnable(GL_CULL_FACE);
  1409. }
  1410. glCullFace(co->cull_mode == RS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE ? GL_FRONT : GL_BACK);
  1411. }
  1412. cull_mode = co->cull_mode;
  1413. }
  1414. glBindVertexArray(co->vertex_array);
  1415. glDrawElements(GL_TRIANGLES, 3 * co->line_point_count, GL_UNSIGNED_SHORT, 0);
  1416. instance = instance->next;
  1417. }
  1418. Transform2D to_shadow;
  1419. to_shadow.columns[0].x = 1.0 / -(half_size * 2.0);
  1420. to_shadow.columns[2].x = 0.5;
  1421. cl->shadow.directional_xform = to_shadow * to_light_xform;
  1422. glBindVertexArray(0);
  1423. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  1424. glDepthMask(GL_FALSE);
  1425. glDisable(GL_DEPTH_TEST);
  1426. glDisable(GL_SCISSOR_TEST);
  1427. glDisable(GL_CULL_FACE);
  1428. }
  1429. void RasterizerCanvasGLES3::_update_shadow_atlas() {
  1430. GLES3::Config *config = GLES3::Config::get_singleton();
  1431. if (state.shadow_fb == 0) {
  1432. glActiveTexture(GL_TEXTURE0);
  1433. glGenFramebuffers(1, &state.shadow_fb);
  1434. glBindFramebuffer(GL_FRAMEBUFFER, state.shadow_fb);
  1435. glGenRenderbuffers(1, &state.shadow_depth_buffer);
  1436. glBindRenderbuffer(GL_RENDERBUFFER, state.shadow_depth_buffer);
  1437. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, state.shadow_texture_size, data.max_lights_per_render * 2);
  1438. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, state.shadow_depth_buffer);
  1439. glGenTextures(1, &state.shadow_texture);
  1440. glBindTexture(GL_TEXTURE_2D, state.shadow_texture);
  1441. if (config->float_texture_supported) {
  1442. glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, state.shadow_texture_size, data.max_lights_per_render * 2, 0, GL_RED, GL_FLOAT, nullptr);
  1443. } else {
  1444. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, state.shadow_texture_size, data.max_lights_per_render * 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  1445. }
  1446. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1447. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1448. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  1449. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  1450. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
  1451. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
  1452. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, state.shadow_texture, 0);
  1453. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  1454. if (status != GL_FRAMEBUFFER_COMPLETE) {
  1455. glDeleteFramebuffers(1, &state.shadow_fb);
  1456. glDeleteTextures(1, &state.shadow_texture);
  1457. glDeleteRenderbuffers(1, &state.shadow_depth_buffer);
  1458. state.shadow_fb = 0;
  1459. state.shadow_texture = 0;
  1460. state.shadow_depth_buffer = 0;
  1461. WARN_PRINT("Could not create CanvasItem shadow atlas, status: " + GLES3::TextureStorage::get_singleton()->get_framebuffer_error(status));
  1462. }
  1463. GLES3::Utilities::get_singleton()->texture_allocated_data(state.shadow_texture, state.shadow_texture_size * data.max_lights_per_render * 2 * 4, "2D shadow atlas texture");
  1464. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  1465. }
  1466. }
  1467. void RasterizerCanvasGLES3::render_sdf(RID p_render_target, LightOccluderInstance *p_occluders) {
  1468. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1469. GLuint fb = texture_storage->render_target_get_sdf_framebuffer(p_render_target);
  1470. Rect2i rect = texture_storage->render_target_get_sdf_rect(p_render_target);
  1471. Transform2D to_sdf;
  1472. to_sdf.columns[0] *= rect.size.width;
  1473. to_sdf.columns[1] *= rect.size.height;
  1474. to_sdf.columns[2] = rect.position;
  1475. Transform2D to_clip;
  1476. to_clip.columns[0] *= 2.0;
  1477. to_clip.columns[1] *= 2.0;
  1478. to_clip.columns[2] = -Vector2(1.0, 1.0);
  1479. to_clip = to_clip * to_sdf.affine_inverse();
  1480. glBindFramebuffer(GL_FRAMEBUFFER, fb);
  1481. glViewport(0, 0, rect.size.width, rect.size.height);
  1482. glDepthMask(GL_FALSE);
  1483. glDisable(GL_DEPTH_TEST);
  1484. glDisable(GL_BLEND);
  1485. glDisable(GL_CULL_FACE);
  1486. glDisable(GL_SCISSOR_TEST);
  1487. glClearColor(0.0, 0.0, 0.0, 0.0);
  1488. glClear(GL_COLOR_BUFFER_BIT);
  1489. CanvasOcclusionShaderGLES3::ShaderVariant variant = CanvasOcclusionShaderGLES3::MODE_SDF;
  1490. bool success = shadow_render.shader.version_bind_shader(shadow_render.shader_version, variant);
  1491. if (!success) {
  1492. return;
  1493. }
  1494. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::PROJECTION, Projection(), shadow_render.shader_version, variant);
  1495. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::DIRECTION, 0.0, 0.0, shadow_render.shader_version, variant);
  1496. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::Z_FAR, 0.0, shadow_render.shader_version, variant);
  1497. LightOccluderInstance *instance = p_occluders;
  1498. while (instance) {
  1499. OccluderPolygon *oc = occluder_polygon_owner.get_or_null(instance->occluder);
  1500. if (!oc || oc->sdf_vertex_array == 0) {
  1501. instance = instance->next;
  1502. continue;
  1503. }
  1504. Transform2D modelview = to_clip * instance->xform_cache;
  1505. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW1, modelview.columns[0][0], modelview.columns[1][0], 0, modelview.columns[2][0], shadow_render.shader_version, variant);
  1506. shadow_render.shader.version_set_uniform(CanvasOcclusionShaderGLES3::MODELVIEW2, modelview.columns[0][1], modelview.columns[1][1], 0, modelview.columns[2][1], shadow_render.shader_version, variant);
  1507. glBindVertexArray(oc->sdf_vertex_array);
  1508. glDrawElements(oc->sdf_is_lines ? GL_LINES : GL_TRIANGLES, oc->sdf_index_count, GL_UNSIGNED_INT, 0);
  1509. instance = instance->next;
  1510. }
  1511. texture_storage->render_target_sdf_process(p_render_target); //done rendering, process it
  1512. glBindVertexArray(0);
  1513. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  1514. }
  1515. RID RasterizerCanvasGLES3::occluder_polygon_create() {
  1516. OccluderPolygon occluder;
  1517. return occluder_polygon_owner.make_rid(occluder);
  1518. }
  1519. void RasterizerCanvasGLES3::occluder_polygon_set_shape(RID p_occluder, const Vector<Vector2> &p_points, bool p_closed) {
  1520. OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);
  1521. ERR_FAIL_NULL(oc);
  1522. Vector<Vector2> lines;
  1523. if (p_points.size()) {
  1524. int lc = p_points.size() * 2;
  1525. lines.resize(lc - (p_closed ? 0 : 2));
  1526. {
  1527. Vector2 *w = lines.ptrw();
  1528. const Vector2 *r = p_points.ptr();
  1529. int max = lc / 2;
  1530. if (!p_closed) {
  1531. max--;
  1532. }
  1533. for (int i = 0; i < max; i++) {
  1534. Vector2 a = r[i];
  1535. Vector2 b = r[(i + 1) % (lc / 2)];
  1536. w[i * 2 + 0] = a;
  1537. w[i * 2 + 1] = b;
  1538. }
  1539. }
  1540. }
  1541. if (oc->line_point_count != lines.size() && oc->vertex_array != 0) {
  1542. glDeleteVertexArrays(1, &oc->vertex_array);
  1543. GLES3::Utilities::get_singleton()->buffer_free_data(oc->vertex_buffer);
  1544. GLES3::Utilities::get_singleton()->buffer_free_data(oc->index_buffer);
  1545. oc->vertex_array = 0;
  1546. oc->vertex_buffer = 0;
  1547. oc->index_buffer = 0;
  1548. }
  1549. if (lines.size()) {
  1550. Vector<uint8_t> geometry;
  1551. Vector<uint8_t> indices;
  1552. int lc = lines.size();
  1553. geometry.resize(lc * 6 * sizeof(float));
  1554. indices.resize(lc * 3 * sizeof(uint16_t));
  1555. {
  1556. uint8_t *vw = geometry.ptrw();
  1557. float *vwptr = reinterpret_cast<float *>(vw);
  1558. uint8_t *iw = indices.ptrw();
  1559. uint16_t *iwptr = (uint16_t *)iw;
  1560. const Vector2 *lr = lines.ptr();
  1561. const int POLY_HEIGHT = 16384;
  1562. for (int i = 0; i < lc / 2; i++) {
  1563. vwptr[i * 12 + 0] = lr[i * 2 + 0].x;
  1564. vwptr[i * 12 + 1] = lr[i * 2 + 0].y;
  1565. vwptr[i * 12 + 2] = POLY_HEIGHT;
  1566. vwptr[i * 12 + 3] = lr[i * 2 + 1].x;
  1567. vwptr[i * 12 + 4] = lr[i * 2 + 1].y;
  1568. vwptr[i * 12 + 5] = POLY_HEIGHT;
  1569. vwptr[i * 12 + 6] = lr[i * 2 + 1].x;
  1570. vwptr[i * 12 + 7] = lr[i * 2 + 1].y;
  1571. vwptr[i * 12 + 8] = -POLY_HEIGHT;
  1572. vwptr[i * 12 + 9] = lr[i * 2 + 0].x;
  1573. vwptr[i * 12 + 10] = lr[i * 2 + 0].y;
  1574. vwptr[i * 12 + 11] = -POLY_HEIGHT;
  1575. iwptr[i * 6 + 0] = i * 4 + 0;
  1576. iwptr[i * 6 + 1] = i * 4 + 1;
  1577. iwptr[i * 6 + 2] = i * 4 + 2;
  1578. iwptr[i * 6 + 3] = i * 4 + 2;
  1579. iwptr[i * 6 + 4] = i * 4 + 3;
  1580. iwptr[i * 6 + 5] = i * 4 + 0;
  1581. }
  1582. }
  1583. if (oc->vertex_array == 0) {
  1584. oc->line_point_count = lc;
  1585. glGenVertexArrays(1, &oc->vertex_array);
  1586. glBindVertexArray(oc->vertex_array);
  1587. glGenBuffers(1, &oc->vertex_buffer);
  1588. glBindBuffer(GL_ARRAY_BUFFER, oc->vertex_buffer);
  1589. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, oc->vertex_buffer, lc * 6 * sizeof(float), geometry.ptr(), GL_STATIC_DRAW, "Occluder polygon vertex buffer");
  1590. glEnableVertexAttribArray(RS::ARRAY_VERTEX);
  1591. glVertexAttribPointer(RS::ARRAY_VERTEX, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr);
  1592. glGenBuffers(1, &oc->index_buffer);
  1593. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->index_buffer);
  1594. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ELEMENT_ARRAY_BUFFER, oc->index_buffer, 3 * lc * sizeof(uint16_t), indices.ptr(), GL_STATIC_DRAW, "Occluder polygon index buffer");
  1595. glBindVertexArray(0);
  1596. } else {
  1597. glBindBuffer(GL_ARRAY_BUFFER, oc->vertex_buffer);
  1598. glBufferData(GL_ARRAY_BUFFER, lc * 6 * sizeof(float), geometry.ptr(), GL_STATIC_DRAW);
  1599. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->index_buffer);
  1600. glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * lc * sizeof(uint16_t), indices.ptr(), GL_STATIC_DRAW);
  1601. glBindBuffer(GL_ARRAY_BUFFER, 0);
  1602. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  1603. }
  1604. }
  1605. // sdf
  1606. Vector<int> sdf_indices;
  1607. if (p_points.size()) {
  1608. if (p_closed) {
  1609. sdf_indices = Geometry2D::triangulate_polygon(p_points);
  1610. oc->sdf_is_lines = false;
  1611. } else {
  1612. int max = p_points.size();
  1613. sdf_indices.resize(max * 2);
  1614. int *iw = sdf_indices.ptrw();
  1615. for (int i = 0; i < max; i++) {
  1616. iw[i * 2 + 0] = i;
  1617. iw[i * 2 + 1] = (i + 1) % max;
  1618. }
  1619. oc->sdf_is_lines = true;
  1620. }
  1621. }
  1622. if (oc->sdf_index_count != sdf_indices.size() && oc->sdf_point_count != p_points.size() && oc->sdf_vertex_array != 0) {
  1623. glDeleteVertexArrays(1, &oc->sdf_vertex_array);
  1624. GLES3::Utilities::get_singleton()->buffer_free_data(oc->sdf_vertex_buffer);
  1625. GLES3::Utilities::get_singleton()->buffer_free_data(oc->sdf_index_buffer);
  1626. oc->sdf_vertex_array = 0;
  1627. oc->sdf_vertex_buffer = 0;
  1628. oc->sdf_index_buffer = 0;
  1629. oc->sdf_index_count = sdf_indices.size();
  1630. oc->sdf_point_count = p_points.size();
  1631. }
  1632. if (sdf_indices.size()) {
  1633. if (oc->sdf_vertex_array == 0) {
  1634. oc->sdf_index_count = sdf_indices.size();
  1635. oc->sdf_point_count = p_points.size();
  1636. glGenVertexArrays(1, &oc->sdf_vertex_array);
  1637. glBindVertexArray(oc->sdf_vertex_array);
  1638. glGenBuffers(1, &oc->sdf_vertex_buffer);
  1639. glBindBuffer(GL_ARRAY_BUFFER, oc->sdf_vertex_buffer);
  1640. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, oc->sdf_vertex_buffer, oc->sdf_point_count * 2 * sizeof(float), p_points.to_byte_array().ptr(), GL_STATIC_DRAW, "Occluder polygon SDF vertex buffer");
  1641. glEnableVertexAttribArray(RS::ARRAY_VERTEX);
  1642. glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), nullptr);
  1643. glGenBuffers(1, &oc->sdf_index_buffer);
  1644. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->sdf_index_buffer);
  1645. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ELEMENT_ARRAY_BUFFER, oc->sdf_index_buffer, oc->sdf_index_count * sizeof(uint32_t), sdf_indices.to_byte_array().ptr(), GL_STATIC_DRAW, "Occluder polygon SDF index buffer");
  1646. glBindVertexArray(0);
  1647. } else {
  1648. glBindBuffer(GL_ARRAY_BUFFER, oc->sdf_vertex_buffer);
  1649. glBufferData(GL_ARRAY_BUFFER, p_points.size() * 2 * sizeof(float), p_points.to_byte_array().ptr(), GL_STATIC_DRAW);
  1650. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oc->sdf_index_buffer);
  1651. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sdf_indices.size() * sizeof(uint32_t), sdf_indices.to_byte_array().ptr(), GL_STATIC_DRAW);
  1652. glBindBuffer(GL_ARRAY_BUFFER, 0);
  1653. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  1654. }
  1655. }
  1656. }
  1657. void RasterizerCanvasGLES3::occluder_polygon_set_cull_mode(RID p_occluder, RS::CanvasOccluderPolygonCullMode p_mode) {
  1658. OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);
  1659. ERR_FAIL_NULL(oc);
  1660. oc->cull_mode = p_mode;
  1661. }
  1662. void RasterizerCanvasGLES3::set_shadow_texture_size(int p_size) {
  1663. GLES3::Config *config = GLES3::Config::get_singleton();
  1664. p_size = nearest_power_of_2_templated(p_size);
  1665. if (p_size > config->max_texture_size) {
  1666. p_size = config->max_texture_size;
  1667. WARN_PRINT("Attempting to set CanvasItem shadow atlas size to " + itos(p_size) + " which is beyond limit of " + itos(config->max_texture_size) + "supported by hardware.");
  1668. }
  1669. if (p_size == state.shadow_texture_size) {
  1670. return;
  1671. }
  1672. state.shadow_texture_size = p_size;
  1673. if (state.shadow_fb != 0) {
  1674. glDeleteFramebuffers(1, &state.shadow_fb);
  1675. GLES3::Utilities::get_singleton()->texture_free_data(state.shadow_texture);
  1676. glDeleteRenderbuffers(1, &state.shadow_depth_buffer);
  1677. state.shadow_fb = 0;
  1678. state.shadow_texture = 0;
  1679. state.shadow_depth_buffer = 0;
  1680. }
  1681. _update_shadow_atlas();
  1682. }
  1683. bool RasterizerCanvasGLES3::free(RID p_rid) {
  1684. if (canvas_light_owner.owns(p_rid)) {
  1685. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  1686. ERR_FAIL_NULL_V(cl, false);
  1687. canvas_light_owner.free(p_rid);
  1688. } else if (occluder_polygon_owner.owns(p_rid)) {
  1689. occluder_polygon_set_shape(p_rid, Vector<Vector2>(), false);
  1690. occluder_polygon_owner.free(p_rid);
  1691. } else {
  1692. return false;
  1693. }
  1694. return true;
  1695. }
  1696. void RasterizerCanvasGLES3::update() {
  1697. }
  1698. void RasterizerCanvasGLES3::canvas_begin(RID p_to_render_target, bool p_to_backbuffer) {
  1699. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1700. GLES3::Config *config = GLES3::Config::get_singleton();
  1701. GLES3::RenderTarget *render_target = texture_storage->get_render_target(p_to_render_target);
  1702. if (p_to_backbuffer) {
  1703. glBindFramebuffer(GL_FRAMEBUFFER, render_target->backbuffer_fbo);
  1704. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 4);
  1705. GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
  1706. glBindTexture(GL_TEXTURE_2D, tex->tex_id);
  1707. } else {
  1708. glBindFramebuffer(GL_FRAMEBUFFER, render_target->fbo);
  1709. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 4);
  1710. glBindTexture(GL_TEXTURE_2D, render_target->backbuffer);
  1711. }
  1712. if (render_target->is_transparent || p_to_backbuffer) {
  1713. state.transparent_render_target = true;
  1714. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  1715. } else {
  1716. state.transparent_render_target = false;
  1717. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  1718. }
  1719. if (render_target && render_target->clear_requested) {
  1720. const Color &col = render_target->clear_color;
  1721. glClearColor(col.r, col.g, col.b, render_target->is_transparent ? col.a : 1.0f);
  1722. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  1723. render_target->clear_requested = false;
  1724. }
  1725. glActiveTexture(GL_TEXTURE0);
  1726. GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
  1727. glBindTexture(GL_TEXTURE_2D, tex->tex_id);
  1728. }
  1729. void RasterizerCanvasGLES3::_bind_canvas_texture(RID p_texture, RS::CanvasItemTextureFilter p_base_filter, RS::CanvasItemTextureRepeat p_base_repeat) {
  1730. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1731. GLES3::Config *config = GLES3::Config::get_singleton();
  1732. if (p_texture == RID()) {
  1733. p_texture = default_canvas_texture;
  1734. }
  1735. if (state.current_tex == p_texture && state.current_filter_mode == p_base_filter && state.current_repeat_mode == p_base_repeat) {
  1736. return;
  1737. }
  1738. state.current_tex = p_texture;
  1739. state.current_filter_mode = p_base_filter;
  1740. state.current_repeat_mode = p_base_repeat;
  1741. GLES3::CanvasTexture *ct = nullptr;
  1742. GLES3::Texture *t = texture_storage->get_texture(p_texture);
  1743. if (t) {
  1744. ERR_FAIL_NULL(t->canvas_texture);
  1745. ct = t->canvas_texture;
  1746. if (t->render_target) {
  1747. t->render_target->used_in_frame = true;
  1748. }
  1749. } else {
  1750. ct = texture_storage->get_canvas_texture(p_texture);
  1751. }
  1752. if (!ct) {
  1753. // Invalid Texture RID.
  1754. _bind_canvas_texture(default_canvas_texture, p_base_filter, p_base_repeat);
  1755. return;
  1756. }
  1757. RS::CanvasItemTextureFilter filter = ct->texture_filter != RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT ? ct->texture_filter : p_base_filter;
  1758. ERR_FAIL_COND(filter == RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT);
  1759. RS::CanvasItemTextureRepeat repeat = ct->texture_repeat != RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT ? ct->texture_repeat : p_base_repeat;
  1760. ERR_FAIL_COND(repeat == RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT);
  1761. GLES3::Texture *texture = texture_storage->get_texture(ct->diffuse);
  1762. if (!texture) {
  1763. GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
  1764. glActiveTexture(GL_TEXTURE0);
  1765. glBindTexture(GL_TEXTURE_2D, tex->tex_id);
  1766. } else {
  1767. glActiveTexture(GL_TEXTURE0);
  1768. glBindTexture(GL_TEXTURE_2D, texture->tex_id);
  1769. texture->gl_set_filter(filter);
  1770. texture->gl_set_repeat(repeat);
  1771. if (texture->render_target) {
  1772. texture->render_target->used_in_frame = true;
  1773. }
  1774. }
  1775. GLES3::Texture *normal_map = texture_storage->get_texture(ct->normal_map);
  1776. if (!normal_map) {
  1777. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6);
  1778. GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_NORMAL));
  1779. glBindTexture(GL_TEXTURE_2D, tex->tex_id);
  1780. } else {
  1781. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6);
  1782. glBindTexture(GL_TEXTURE_2D, normal_map->tex_id);
  1783. normal_map->gl_set_filter(filter);
  1784. normal_map->gl_set_repeat(repeat);
  1785. if (normal_map->render_target) {
  1786. normal_map->render_target->used_in_frame = true;
  1787. }
  1788. }
  1789. GLES3::Texture *specular_map = texture_storage->get_texture(ct->specular);
  1790. if (!specular_map) {
  1791. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 7);
  1792. GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
  1793. glBindTexture(GL_TEXTURE_2D, tex->tex_id);
  1794. } else {
  1795. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 7);
  1796. glBindTexture(GL_TEXTURE_2D, specular_map->tex_id);
  1797. specular_map->gl_set_filter(filter);
  1798. specular_map->gl_set_repeat(repeat);
  1799. if (specular_map->render_target) {
  1800. specular_map->render_target->used_in_frame = true;
  1801. }
  1802. }
  1803. }
  1804. void RasterizerCanvasGLES3::_prepare_canvas_texture(RID p_texture, RS::CanvasItemTextureFilter p_base_filter, RS::CanvasItemTextureRepeat p_base_repeat, uint32_t &r_index, Size2 &r_texpixel_size) {
  1805. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1806. if (p_texture == RID()) {
  1807. p_texture = default_canvas_texture;
  1808. }
  1809. GLES3::CanvasTexture *ct = nullptr;
  1810. GLES3::Texture *t = texture_storage->get_texture(p_texture);
  1811. if (t) {
  1812. //regular texture
  1813. if (!t->canvas_texture) {
  1814. t->canvas_texture = memnew(GLES3::CanvasTexture);
  1815. t->canvas_texture->diffuse = p_texture;
  1816. }
  1817. ct = t->canvas_texture;
  1818. } else {
  1819. ct = texture_storage->get_canvas_texture(p_texture);
  1820. }
  1821. if (!ct) {
  1822. // Invalid Texture RID.
  1823. _prepare_canvas_texture(default_canvas_texture, p_base_filter, p_base_repeat, r_index, r_texpixel_size);
  1824. return;
  1825. }
  1826. GLES3::Texture *texture = texture_storage->get_texture(ct->diffuse);
  1827. Size2i size_cache;
  1828. if (!texture) {
  1829. ct->diffuse = texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE);
  1830. GLES3::Texture *tex = texture_storage->get_texture(ct->diffuse);
  1831. size_cache = Size2i(tex->width, tex->height);
  1832. } else {
  1833. size_cache = Size2i(texture->width, texture->height);
  1834. }
  1835. GLES3::Texture *normal_map = texture_storage->get_texture(ct->normal_map);
  1836. if (ct->specular_color.a < 0.999) {
  1837. state.instance_data_array[r_index].flags |= FLAGS_DEFAULT_SPECULAR_MAP_USED;
  1838. } else {
  1839. state.instance_data_array[r_index].flags &= ~FLAGS_DEFAULT_SPECULAR_MAP_USED;
  1840. }
  1841. if (normal_map) {
  1842. state.instance_data_array[r_index].flags |= FLAGS_DEFAULT_NORMAL_MAP_USED;
  1843. } else {
  1844. state.instance_data_array[r_index].flags &= ~FLAGS_DEFAULT_NORMAL_MAP_USED;
  1845. }
  1846. state.instance_data_array[r_index].specular_shininess = uint32_t(CLAMP(ct->specular_color.a * 255.0, 0, 255)) << 24;
  1847. state.instance_data_array[r_index].specular_shininess |= uint32_t(CLAMP(ct->specular_color.b * 255.0, 0, 255)) << 16;
  1848. state.instance_data_array[r_index].specular_shininess |= uint32_t(CLAMP(ct->specular_color.g * 255.0, 0, 255)) << 8;
  1849. state.instance_data_array[r_index].specular_shininess |= uint32_t(CLAMP(ct->specular_color.r * 255.0, 0, 255));
  1850. r_texpixel_size.x = 1.0 / float(size_cache.x);
  1851. r_texpixel_size.y = 1.0 / float(size_cache.y);
  1852. state.instance_data_array[r_index].color_texture_pixel_size[0] = r_texpixel_size.x;
  1853. state.instance_data_array[r_index].color_texture_pixel_size[1] = r_texpixel_size.y;
  1854. }
  1855. void RasterizerCanvasGLES3::reset_canvas() {
  1856. glDisable(GL_CULL_FACE);
  1857. glDisable(GL_DEPTH_TEST);
  1858. glDisable(GL_SCISSOR_TEST);
  1859. glEnable(GL_BLEND);
  1860. glBlendEquation(GL_FUNC_ADD);
  1861. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  1862. glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 2);
  1863. glBindTexture(GL_TEXTURE_2D, 0);
  1864. glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 3);
  1865. glBindTexture(GL_TEXTURE_2D, 0);
  1866. glActiveTexture(GL_TEXTURE0);
  1867. glBindBuffer(GL_ARRAY_BUFFER, 0);
  1868. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  1869. }
  1870. void RasterizerCanvasGLES3::draw_lens_distortion_rect(const Rect2 &p_rect, float p_k1, float p_k2, const Vector2 &p_eye_center, float p_oversample) {
  1871. }
  1872. RendererCanvasRender::PolygonID RasterizerCanvasGLES3::request_polygon(const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, const Vector<int> &p_bones, const Vector<float> &p_weights) {
  1873. // We interleave the vertex data into one big VBO to improve cache coherence
  1874. uint32_t vertex_count = p_points.size();
  1875. uint32_t stride = 2;
  1876. if ((uint32_t)p_colors.size() == vertex_count) {
  1877. stride += 4;
  1878. }
  1879. if ((uint32_t)p_uvs.size() == vertex_count) {
  1880. stride += 2;
  1881. }
  1882. if ((uint32_t)p_bones.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
  1883. stride += 4;
  1884. }
  1885. PolygonBuffers pb;
  1886. glGenBuffers(1, &pb.vertex_buffer);
  1887. glGenVertexArrays(1, &pb.vertex_array);
  1888. glBindVertexArray(pb.vertex_array);
  1889. pb.count = vertex_count;
  1890. pb.index_buffer = 0;
  1891. uint32_t buffer_size = stride * p_points.size();
  1892. Vector<uint8_t> polygon_buffer;
  1893. polygon_buffer.resize(buffer_size * sizeof(float));
  1894. {
  1895. glBindBuffer(GL_ARRAY_BUFFER, pb.vertex_buffer);
  1896. uint8_t *r = polygon_buffer.ptrw();
  1897. float *fptr = reinterpret_cast<float *>(r);
  1898. uint32_t *uptr = (uint32_t *)r;
  1899. uint32_t base_offset = 0;
  1900. {
  1901. // Always uses vertex positions
  1902. glEnableVertexAttribArray(RS::ARRAY_VERTEX);
  1903. glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, stride * sizeof(float), nullptr);
  1904. const Vector2 *points_ptr = p_points.ptr();
  1905. for (uint32_t i = 0; i < vertex_count; i++) {
  1906. fptr[base_offset + i * stride + 0] = points_ptr[i].x;
  1907. fptr[base_offset + i * stride + 1] = points_ptr[i].y;
  1908. }
  1909. base_offset += 2;
  1910. }
  1911. // Next add colors
  1912. if ((uint32_t)p_colors.size() == vertex_count) {
  1913. glEnableVertexAttribArray(RS::ARRAY_COLOR);
  1914. glVertexAttribPointer(RS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
  1915. const Color *color_ptr = p_colors.ptr();
  1916. for (uint32_t i = 0; i < vertex_count; i++) {
  1917. fptr[base_offset + i * stride + 0] = color_ptr[i].r;
  1918. fptr[base_offset + i * stride + 1] = color_ptr[i].g;
  1919. fptr[base_offset + i * stride + 2] = color_ptr[i].b;
  1920. fptr[base_offset + i * stride + 3] = color_ptr[i].a;
  1921. }
  1922. base_offset += 4;
  1923. } else {
  1924. glDisableVertexAttribArray(RS::ARRAY_COLOR);
  1925. pb.color_disabled = true;
  1926. pb.color = p_colors.size() == 1 ? p_colors[0] : Color(1.0, 1.0, 1.0, 1.0);
  1927. }
  1928. if ((uint32_t)p_uvs.size() == vertex_count) {
  1929. glEnableVertexAttribArray(RS::ARRAY_TEX_UV);
  1930. glVertexAttribPointer(RS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
  1931. const Vector2 *uv_ptr = p_uvs.ptr();
  1932. for (uint32_t i = 0; i < vertex_count; i++) {
  1933. fptr[base_offset + i * stride + 0] = uv_ptr[i].x;
  1934. fptr[base_offset + i * stride + 1] = uv_ptr[i].y;
  1935. }
  1936. base_offset += 2;
  1937. } else {
  1938. glDisableVertexAttribArray(RS::ARRAY_TEX_UV);
  1939. }
  1940. if ((uint32_t)p_indices.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
  1941. glEnableVertexAttribArray(RS::ARRAY_BONES);
  1942. glVertexAttribPointer(RS::ARRAY_BONES, 4, GL_UNSIGNED_INT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
  1943. const int *bone_ptr = p_bones.ptr();
  1944. for (uint32_t i = 0; i < vertex_count; i++) {
  1945. uint16_t *bone16w = (uint16_t *)&uptr[base_offset + i * stride];
  1946. bone16w[0] = bone_ptr[i * 4 + 0];
  1947. bone16w[1] = bone_ptr[i * 4 + 1];
  1948. bone16w[2] = bone_ptr[i * 4 + 2];
  1949. bone16w[3] = bone_ptr[i * 4 + 3];
  1950. }
  1951. base_offset += 2;
  1952. } else {
  1953. glDisableVertexAttribArray(RS::ARRAY_BONES);
  1954. }
  1955. if ((uint32_t)p_weights.size() == vertex_count * 4) {
  1956. glEnableVertexAttribArray(RS::ARRAY_WEIGHTS);
  1957. glVertexAttribPointer(RS::ARRAY_WEIGHTS, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(base_offset * sizeof(float)));
  1958. const float *weight_ptr = p_weights.ptr();
  1959. for (uint32_t i = 0; i < vertex_count; i++) {
  1960. uint16_t *weight16w = (uint16_t *)&uptr[base_offset + i * stride];
  1961. weight16w[0] = CLAMP(weight_ptr[i * 4 + 0] * 65535, 0, 65535);
  1962. weight16w[1] = CLAMP(weight_ptr[i * 4 + 1] * 65535, 0, 65535);
  1963. weight16w[2] = CLAMP(weight_ptr[i * 4 + 2] * 65535, 0, 65535);
  1964. weight16w[3] = CLAMP(weight_ptr[i * 4 + 3] * 65535, 0, 65535);
  1965. }
  1966. base_offset += 2;
  1967. } else {
  1968. glDisableVertexAttribArray(RS::ARRAY_WEIGHTS);
  1969. }
  1970. ERR_FAIL_COND_V(base_offset != stride, 0);
  1971. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, pb.vertex_buffer, vertex_count * stride * sizeof(float), polygon_buffer.ptr(), GL_STATIC_DRAW, "Polygon 2D vertex buffer");
  1972. }
  1973. if (p_indices.size()) {
  1974. //create indices, as indices were requested
  1975. Vector<uint8_t> index_buffer;
  1976. index_buffer.resize(p_indices.size() * sizeof(int32_t));
  1977. {
  1978. uint8_t *w = index_buffer.ptrw();
  1979. memcpy(w, p_indices.ptr(), sizeof(int32_t) * p_indices.size());
  1980. }
  1981. glGenBuffers(1, &pb.index_buffer);
  1982. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pb.index_buffer);
  1983. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ELEMENT_ARRAY_BUFFER, pb.index_buffer, p_indices.size() * 4, index_buffer.ptr(), GL_STATIC_DRAW, "Polygon 2D index buffer");
  1984. pb.count = p_indices.size();
  1985. }
  1986. glBindVertexArray(0);
  1987. glBindBuffer(GL_ARRAY_BUFFER, 0);
  1988. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  1989. PolygonID id = polygon_buffers.last_id++;
  1990. polygon_buffers.polygons[id] = pb;
  1991. return id;
  1992. }
  1993. void RasterizerCanvasGLES3::free_polygon(PolygonID p_polygon) {
  1994. PolygonBuffers *pb_ptr = polygon_buffers.polygons.getptr(p_polygon);
  1995. ERR_FAIL_NULL(pb_ptr);
  1996. PolygonBuffers &pb = *pb_ptr;
  1997. if (pb.index_buffer != 0) {
  1998. GLES3::Utilities::get_singleton()->buffer_free_data(pb.index_buffer);
  1999. }
  2000. glDeleteVertexArrays(1, &pb.vertex_array);
  2001. GLES3::Utilities::get_singleton()->buffer_free_data(pb.vertex_buffer);
  2002. polygon_buffers.polygons.erase(p_polygon);
  2003. }
  2004. // Creates a new uniform buffer and uses it right away
  2005. // This expands the instance buffer continually
  2006. // In theory allocations can reach as high as number of windows * 3 frames
  2007. // because OpenGL can start rendering subsequent frames before finishing the current one
  2008. void RasterizerCanvasGLES3::_allocate_instance_data_buffer() {
  2009. GLuint new_buffers[3];
  2010. glGenBuffers(3, new_buffers);
  2011. // Batch UBO.
  2012. glBindBuffer(GL_ARRAY_BUFFER, new_buffers[0]);
  2013. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, new_buffers[0], data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW, "2D Batch UBO[" + itos(state.current_data_buffer_index) + "][0]");
  2014. // Light uniform buffer.
  2015. glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[1]);
  2016. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[1], sizeof(LightUniform) * data.max_lights_per_render, nullptr, GL_STREAM_DRAW, "2D Lights UBO[" + itos(state.current_data_buffer_index) + "]");
  2017. // State buffer.
  2018. glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[2]);
  2019. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[2], sizeof(StateBuffer), nullptr, GL_STREAM_DRAW, "2D State UBO[" + itos(state.current_data_buffer_index) + "]");
  2020. state.current_data_buffer_index = (state.current_data_buffer_index + 1);
  2021. DataBuffer db;
  2022. db.instance_buffers.push_back(new_buffers[0]);
  2023. db.light_ubo = new_buffers[1];
  2024. db.state_ubo = new_buffers[2];
  2025. db.last_frame_used = RSG::rasterizer->get_frame_number();
  2026. state.canvas_instance_data_buffers.insert(state.current_data_buffer_index, db);
  2027. state.current_data_buffer_index = state.current_data_buffer_index % state.canvas_instance_data_buffers.size();
  2028. glBindBuffer(GL_ARRAY_BUFFER, 0);
  2029. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2030. }
  2031. void RasterizerCanvasGLES3::_allocate_instance_buffer() {
  2032. state.current_instance_buffer_index++;
  2033. if (int(state.current_instance_buffer_index) < state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.size()) {
  2034. // We already allocated another buffer in a previous frame, so we can just use it.
  2035. return;
  2036. }
  2037. GLuint new_buffer;
  2038. glGenBuffers(1, &new_buffer);
  2039. glBindBuffer(GL_ARRAY_BUFFER, new_buffer);
  2040. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, new_buffer, data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW, "Batch UBO[" + itos(state.current_data_buffer_index) + "][" + itos(state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.size()) + "]");
  2041. state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.push_back(new_buffer);
  2042. glBindBuffer(GL_ARRAY_BUFFER, 0);
  2043. }
  2044. void RasterizerCanvasGLES3::set_time(double p_time) {
  2045. state.time = p_time;
  2046. }
  2047. RasterizerCanvasGLES3 *RasterizerCanvasGLES3::singleton = nullptr;
  2048. RasterizerCanvasGLES3 *RasterizerCanvasGLES3::get_singleton() {
  2049. return singleton;
  2050. }
  2051. RasterizerCanvasGLES3::RasterizerCanvasGLES3() {
  2052. singleton = this;
  2053. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  2054. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  2055. GLES3::Config *config = GLES3::Config::get_singleton();
  2056. glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0);
  2057. polygon_buffers.last_id = 1;
  2058. // quad buffer
  2059. {
  2060. glGenBuffers(1, &data.canvas_quad_vertices);
  2061. glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
  2062. const float qv[8] = {
  2063. 0, 0,
  2064. 0, 1,
  2065. 1, 1,
  2066. 1, 0
  2067. };
  2068. glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 8, qv, GL_STATIC_DRAW);
  2069. glBindBuffer(GL_ARRAY_BUFFER, 0);
  2070. glGenVertexArrays(1, &data.canvas_quad_array);
  2071. glBindVertexArray(data.canvas_quad_array);
  2072. glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
  2073. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, nullptr);
  2074. glEnableVertexAttribArray(0);
  2075. glBindVertexArray(0);
  2076. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  2077. }
  2078. {
  2079. //particle quad buffers
  2080. glGenBuffers(1, &data.particle_quad_vertices);
  2081. glBindBuffer(GL_ARRAY_BUFFER, data.particle_quad_vertices);
  2082. {
  2083. //quad of size 1, with pivot on the center for particles, then regular UVS. Color is general plus fetched from particle
  2084. const float qv[16] = {
  2085. -0.5, -0.5,
  2086. 0.0, 0.0,
  2087. -0.5, 0.5,
  2088. 0.0, 1.0,
  2089. 0.5, 0.5,
  2090. 1.0, 1.0,
  2091. 0.5, -0.5,
  2092. 1.0, 0.0
  2093. };
  2094. glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, qv, GL_STATIC_DRAW);
  2095. }
  2096. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  2097. glGenVertexArrays(1, &data.particle_quad_array);
  2098. glBindVertexArray(data.particle_quad_array);
  2099. glBindBuffer(GL_ARRAY_BUFFER, data.particle_quad_vertices);
  2100. glEnableVertexAttribArray(RS::ARRAY_VERTEX);
  2101. glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, nullptr);
  2102. glEnableVertexAttribArray(RS::ARRAY_TEX_UV);
  2103. glVertexAttribPointer(RS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(8));
  2104. glBindVertexArray(0);
  2105. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  2106. }
  2107. // ninepatch buffers
  2108. {
  2109. // array buffer
  2110. glGenBuffers(1, &data.ninepatch_vertices);
  2111. glBindBuffer(GL_ARRAY_BUFFER, data.ninepatch_vertices);
  2112. glBufferData(GL_ARRAY_BUFFER, sizeof(float) * (16 + 16) * 2, nullptr, GL_DYNAMIC_DRAW);
  2113. glBindBuffer(GL_ARRAY_BUFFER, 0);
  2114. // element buffer
  2115. glGenBuffers(1, &data.ninepatch_elements);
  2116. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ninepatch_elements);
  2117. #define _EIDX(y, x) (y * 4 + x)
  2118. uint8_t elems[3 * 2 * 9] = {
  2119. // first row
  2120. _EIDX(0, 0), _EIDX(0, 1), _EIDX(1, 1),
  2121. _EIDX(1, 1), _EIDX(1, 0), _EIDX(0, 0),
  2122. _EIDX(0, 1), _EIDX(0, 2), _EIDX(1, 2),
  2123. _EIDX(1, 2), _EIDX(1, 1), _EIDX(0, 1),
  2124. _EIDX(0, 2), _EIDX(0, 3), _EIDX(1, 3),
  2125. _EIDX(1, 3), _EIDX(1, 2), _EIDX(0, 2),
  2126. // second row
  2127. _EIDX(1, 0), _EIDX(1, 1), _EIDX(2, 1),
  2128. _EIDX(2, 1), _EIDX(2, 0), _EIDX(1, 0),
  2129. // the center one would be here, but we'll put it at the end
  2130. // so it's easier to disable the center and be able to use
  2131. // one draw call for both
  2132. _EIDX(1, 2), _EIDX(1, 3), _EIDX(2, 3),
  2133. _EIDX(2, 3), _EIDX(2, 2), _EIDX(1, 2),
  2134. // third row
  2135. _EIDX(2, 0), _EIDX(2, 1), _EIDX(3, 1),
  2136. _EIDX(3, 1), _EIDX(3, 0), _EIDX(2, 0),
  2137. _EIDX(2, 1), _EIDX(2, 2), _EIDX(3, 2),
  2138. _EIDX(3, 2), _EIDX(3, 1), _EIDX(2, 1),
  2139. _EIDX(2, 2), _EIDX(2, 3), _EIDX(3, 3),
  2140. _EIDX(3, 3), _EIDX(3, 2), _EIDX(2, 2),
  2141. // center field
  2142. _EIDX(1, 1), _EIDX(1, 2), _EIDX(2, 2),
  2143. _EIDX(2, 2), _EIDX(2, 1), _EIDX(1, 1)
  2144. };
  2145. #undef _EIDX
  2146. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elems), elems, GL_STATIC_DRAW);
  2147. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  2148. }
  2149. int uniform_max_size = config->max_uniform_buffer_size;
  2150. if (uniform_max_size < 65536) {
  2151. data.max_lights_per_render = 64;
  2152. } else {
  2153. data.max_lights_per_render = 256;
  2154. }
  2155. // Reserve 3 Uniform Buffers for instance data Frame N, N+1 and N+2
  2156. data.max_instances_per_buffer = uint32_t(GLOBAL_GET("rendering/gl_compatibility/item_buffer_size"));
  2157. data.max_instance_buffer_size = data.max_instances_per_buffer * sizeof(InstanceData); // 16,384 instances * 128 bytes = 2,097,152 bytes = 2,048 kb
  2158. state.canvas_instance_data_buffers.resize(3);
  2159. state.canvas_instance_batches.reserve(200);
  2160. for (int i = 0; i < 3; i++) {
  2161. GLuint new_buffers[3];
  2162. glGenBuffers(3, new_buffers);
  2163. // Batch UBO.
  2164. glBindBuffer(GL_ARRAY_BUFFER, new_buffers[0]);
  2165. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, new_buffers[0], data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW, "Batch UBO[0][0]");
  2166. // Light uniform buffer.
  2167. glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[1]);
  2168. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[1], sizeof(LightUniform) * data.max_lights_per_render, nullptr, GL_STREAM_DRAW, "2D lights UBO[0]");
  2169. // State buffer.
  2170. glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[2]);
  2171. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, new_buffers[2], sizeof(StateBuffer), nullptr, GL_STREAM_DRAW, "2D state UBO[0]");
  2172. DataBuffer db;
  2173. db.instance_buffers.push_back(new_buffers[0]);
  2174. db.light_ubo = new_buffers[1];
  2175. db.state_ubo = new_buffers[2];
  2176. db.last_frame_used = 0;
  2177. db.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  2178. state.canvas_instance_data_buffers[i] = db;
  2179. }
  2180. glBindBuffer(GL_ARRAY_BUFFER, 0);
  2181. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2182. state.instance_data_array = memnew_arr(InstanceData, data.max_instances_per_buffer);
  2183. state.light_uniforms = memnew_arr(LightUniform, data.max_lights_per_render);
  2184. {
  2185. const uint32_t indices[6] = { 0, 2, 1, 3, 2, 0 };
  2186. glGenVertexArrays(1, &data.indexed_quad_array);
  2187. glBindVertexArray(data.indexed_quad_array);
  2188. glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
  2189. glGenBuffers(1, &data.indexed_quad_buffer);
  2190. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.indexed_quad_buffer);
  2191. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32_t) * 6, indices, GL_STATIC_DRAW);
  2192. glBindVertexArray(0);
  2193. }
  2194. String global_defines;
  2195. global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
  2196. global_defines += "#define MAX_LIGHTS " + itos(data.max_lights_per_render) + "\n";
  2197. GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.initialize(global_defines, 1);
  2198. data.canvas_shader_default_version = GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_create();
  2199. state.shadow_texture_size = GLOBAL_GET("rendering/2d/shadow_atlas/size");
  2200. shadow_render.shader.initialize();
  2201. shadow_render.shader_version = shadow_render.shader.version_create();
  2202. {
  2203. default_canvas_group_shader = material_storage->shader_allocate();
  2204. material_storage->shader_initialize(default_canvas_group_shader);
  2205. material_storage->shader_set_code(default_canvas_group_shader, R"(
  2206. // Default CanvasGroup shader.
  2207. shader_type canvas_item;
  2208. render_mode unshaded;
  2209. uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;
  2210. void fragment() {
  2211. vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);
  2212. if (c.a > 0.0001) {
  2213. c.rgb /= c.a;
  2214. }
  2215. COLOR *= c;
  2216. }
  2217. )");
  2218. default_canvas_group_material = material_storage->material_allocate();
  2219. material_storage->material_initialize(default_canvas_group_material);
  2220. material_storage->material_set_shader(default_canvas_group_material, default_canvas_group_shader);
  2221. }
  2222. {
  2223. default_clip_children_shader = material_storage->shader_allocate();
  2224. material_storage->shader_initialize(default_clip_children_shader);
  2225. material_storage->shader_set_code(default_clip_children_shader, R"(
  2226. // Default clip children shader.
  2227. shader_type canvas_item;
  2228. render_mode unshaded;
  2229. uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;
  2230. void fragment() {
  2231. vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);
  2232. COLOR.rgb = c.rgb;
  2233. }
  2234. )");
  2235. default_clip_children_material = material_storage->material_allocate();
  2236. material_storage->material_initialize(default_clip_children_material);
  2237. material_storage->material_set_shader(default_clip_children_material, default_clip_children_shader);
  2238. }
  2239. default_canvas_texture = texture_storage->canvas_texture_allocate();
  2240. texture_storage->canvas_texture_initialize(default_canvas_texture);
  2241. state.time = 0.0;
  2242. }
  2243. RasterizerCanvasGLES3::~RasterizerCanvasGLES3() {
  2244. singleton = nullptr;
  2245. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  2246. material_storage->shaders.canvas_shader.version_free(data.canvas_shader_default_version);
  2247. shadow_render.shader.version_free(shadow_render.shader_version);
  2248. material_storage->material_free(default_canvas_group_material);
  2249. material_storage->shader_free(default_canvas_group_shader);
  2250. material_storage->material_free(default_clip_children_material);
  2251. material_storage->shader_free(default_clip_children_shader);
  2252. singleton = nullptr;
  2253. glDeleteBuffers(1, &data.canvas_quad_vertices);
  2254. glDeleteVertexArrays(1, &data.canvas_quad_array);
  2255. glDeleteBuffers(1, &data.canvas_quad_vertices);
  2256. glDeleteVertexArrays(1, &data.canvas_quad_array);
  2257. GLES3::TextureStorage::get_singleton()->canvas_texture_free(default_canvas_texture);
  2258. memdelete_arr(state.instance_data_array);
  2259. memdelete_arr(state.light_uniforms);
  2260. if (state.shadow_fb != 0) {
  2261. glDeleteFramebuffers(1, &state.shadow_fb);
  2262. GLES3::Utilities::get_singleton()->texture_free_data(state.shadow_texture);
  2263. glDeleteRenderbuffers(1, &state.shadow_depth_buffer);
  2264. state.shadow_fb = 0;
  2265. state.shadow_texture = 0;
  2266. state.shadow_depth_buffer = 0;
  2267. }
  2268. for (uint32_t i = 0; i < state.canvas_instance_data_buffers.size(); i++) {
  2269. for (int j = 0; j < state.canvas_instance_data_buffers[i].instance_buffers.size(); j++) {
  2270. if (state.canvas_instance_data_buffers[i].instance_buffers[j]) {
  2271. GLES3::Utilities::get_singleton()->buffer_free_data(state.canvas_instance_data_buffers[i].instance_buffers[j]);
  2272. }
  2273. }
  2274. if (state.canvas_instance_data_buffers[i].light_ubo) {
  2275. GLES3::Utilities::get_singleton()->buffer_free_data(state.canvas_instance_data_buffers[i].light_ubo);
  2276. }
  2277. if (state.canvas_instance_data_buffers[i].state_ubo) {
  2278. GLES3::Utilities::get_singleton()->buffer_free_data(state.canvas_instance_data_buffers[i].state_ubo);
  2279. }
  2280. }
  2281. }
  2282. #endif // GLES3_ENABLED