rasterizer_canvas_gles3.cpp 118 KB

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